[
  {
    "difficulty": "Easy",
    "frontendQuestionId": "1",
    "paidOnly": false,
    "title": "Two Sum",
    "titleSlug": "two-sum",
    "url": "https://leetcode.com/problems/two-sum",
    "description_url": "https://leetcode.com/problems/two-sum/description/",
    "description": "<p>Given an array of integers <code>nums</code>&nbsp;and an integer <code>target</code>, return <em>indices of the two numbers such that they add up to <code>target</code></em>.</p>\n\n<p>You may assume that each input would have <strong><em>exactly</em> one solution</strong>, and you may not use the <em>same</em> element twice.</p>\n\n<p>You can return the answer in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,7,11,15], target = 9\n<strong>Output:</strong> [0,1]\n<strong>Explanation:</strong> Because nums[0] + nums[1] == 9, we return [0, 1].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,4], target = 6\n<strong>Output:</strong> [1,2]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,3], target = 6\n<strong>Output:</strong> [0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n\t<li><strong>Only one valid answer exists.</strong></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow-up:&nbsp;</strong>Can you come up with an algorithm that is less than <code>O(n<sup>2</sup>)</code><font face=\"monospace\">&nbsp;</font>time complexity?",
    "solution_url": "https://leetcode.com/problems/two-sum/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n\n---\n\n<div>\n    <div class=\"video-container\">\n        <iframe src=\"https://player.vimeo.com/video/567281997\" width=\"640\" height=\"360\" frameborder=\"0\" allow=\"autoplay; fullscreen\" allowfullscreen></iframe>\n    </div>\n</div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Brute Force\n\n**Algorithm**\n\nThe brute force approach is simple. Loop through each element $$x$$ and find if there is another value that equals to $$target - x$$.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/WTVGRyeD/shared\" frameBorder=\"0\" width=\"100%\" height=\"327\" name=\"WTVGRyeD\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n^2)$$.\nFor each element, we try to find its complement by looping through the rest of the array which takes $$O(n)$$ time. Therefore, the time complexity is $$O(n^2)$$.\n\n* Space complexity: $$O(1)$$.\nThe space required does not depend on the size of the input array, so only constant space is used.\n\n---\n### Approach 2: Two-pass Hash Table\n\n**Intuition**\n\nTo improve our runtime complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to get its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.\n\nWe can reduce the lookup time from $$O(n)$$ to $$O(1)$$ by trading space for speed. A hash table is well suited for this purpose because it supports fast lookup in *near* constant time. I say \"near\" because if a collision occurred, a lookup could degenerate to $$O(n)$$ time. However, lookup in a hash table should be amortized $$O(1)$$ time as long as the hash function was chosen carefully.\n\n**Algorithm**\n\nA simple implementation uses two iterations. In the first iteration, we add each element's value as a key and its index as a value to the hash table. Then, in the second iteration, we check if each element's complement ($$target - nums[i]$$) exists in the hash table. If it does exist, we return current element's index and its complement's index. Beware that the complement must not be $$nums[i]$$ itself!\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/bbEpXJcf/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"bbEpXJcf\"></iframe>  \n\n**Complexity Analysis**\n\n* Time complexity: $$O(n)$$.\nWe traverse the list containing $$n$$ elements exactly twice. Since the hash table reduces the lookup time to $$O(1)$$, the overall time complexity is $$O(n)$$.\n\n* Space complexity: $$O(n)$$.\nThe extra space required depends on the number of items stored in the hash table, which stores exactly $$n$$ elements.\n\n---\n### Approach 3: One-pass Hash Table\n\n**Algorithm**\n    \nIt turns out we can do it in one-pass. While we are iterating and inserting elements into the hash table, we also look back to check if current element's complement already exists in the hash table. If it exists, we have found a solution and return the indices immediately.\n\n**Implementation**    \n    \n<iframe src=\"https://leetcode.com/playground/4KK3DMtw/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4KK3DMtw\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n)$$.\nWe traverse the list containing $$n$$ elements only once. Each lookup in the table costs only $$O(1)$$ time.\n\n* Space complexity: $$O(n)$$.\nThe extra space required depends on the number of items stored in the hash table, which stores at most $$n$$ elements.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def twoSum(self, nums: List[int], target: int) -> List[int]:\n    numToIndex = {}\n\n    for i, num in enumerate(nums):\n      if target - num in numToIndex:\n        return numToIndex[target - num], i\n      numToIndex[num] = i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] twoSum(int[] nums, int target) {\n    Map<Integer, Integer> numToIndex = new HashMap<>();\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (numToIndex.containsKey(target - nums[i]))\n        return new int[] {numToIndex.get(target - nums[i]), i};\n      numToIndex.put(nums[i], i);\n    }\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> twoSum(vector<int>& nums, int target) {\n    unordered_map<int, int> numToIndex;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (numToIndex.count(target - nums[i]))\n        return {numToIndex[target - nums[i]], i};\n      numToIndex[nums[i]] = i;\n    }\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/1.html",
    "category": "Algorithms",
    "acceptance_rate": 55.576690288501965,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [
      "A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.",
      "So, if we fix one of the numbers, say <code>x</code>, we have to scan the entire array to find the next number <code>y</code> which is <code>value - x</code> where value is the input parameter. Can we change our array somehow so that this search becomes faster?",
      "The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?"
    ],
    "likes": 61571,
    "dislikes": 2223,
    "similar_questions": "[{\"title\": \"3Sum\", \"titleSlug\": \"3sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"4Sum\", \"titleSlug\": \"4sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum II - Input Array Is Sorted\", \"titleSlug\": \"two-sum-ii-input-array-is-sorted\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum III - Data structure design\", \"titleSlug\": \"two-sum-iii-data-structure-design\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum IV - Input is a BST\", \"titleSlug\": \"two-sum-iv-input-is-a-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum Less Than K\", \"titleSlug\": \"two-sum-less-than-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Max Number of K-Sum Pairs\", \"titleSlug\": \"max-number-of-k-sum-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Good Meals\", \"titleSlug\": \"count-good-meals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Number of Pairs With Absolute Difference K\", \"titleSlug\": \"count-number-of-pairs-with-absolute-difference-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Pairs of Strings With Concatenation Equal to Target\", \"titleSlug\": \"number-of-pairs-of-strings-with-concatenation-equal-to-target\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All K-Distant Indices in an Array\", \"titleSlug\": \"find-all-k-distant-indices-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"First Letter to Appear Twice\", \"titleSlug\": \"first-letter-to-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Excellent Pairs\", \"titleSlug\": \"number-of-excellent-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Arithmetic Triplets\", \"titleSlug\": \"number-of-arithmetic-triplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Node With Highest Edge Score\", \"titleSlug\": \"node-with-highest-edge-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check Distances Between Same Letters\", \"titleSlug\": \"check-distances-between-same-letters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Subarrays With Equal Sum\", \"titleSlug\": \"find-subarrays-with-equal-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Largest Positive Integer That Exists With Its Negative\", \"titleSlug\": \"largest-positive-integer-that-exists-with-its-negative\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Distinct Averages\", \"titleSlug\": \"number-of-distinct-averages\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Pairs Whose Sum is Less than Target\", \"titleSlug\": \"count-pairs-whose-sum-is-less-than-target\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"17.1M\", \"totalSubmission\": \"30.8M\", \"totalAcceptedRaw\": 17143979, \"totalSubmissionRaw\": 30847470, \"acRate\": \"55.6%\"}",
    "title_pt": "Soma de Dois Números",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>&nbsp;e um inteiro <code>target</code>, retorne <em>os índices dos dois números de modo que eles somem até <code>target</code></em>.</p>\n\n<p>Você pode assumir que cada entrada teria <strong><em>exatamente</em> uma solução</strong>, e você não pode usar o <em>mesmo</em> elemento duas vezes.</p>\n\n<p>Você pode retornar a resposta em qualquer ordem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,7,11,15], target = 9\n<strong>Saída:</strong> [0,1]\n<strong>Explicação:</strong> Como nums[0] + nums[1] == 9, retornamos [0, 1].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,4], target = 6\n<strong>Saída:</strong> [1,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,3], target = 6\n<strong>Saída:</strong> [0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n\t<li><strong>Apenas uma resposta válida existe.</strong></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:&nbsp;</strong>Você consegue criar um algoritmo com complexidade de tempo inferior a <code>O(n<sup>2</sup>)</code><font face=\"monospace\">&nbsp;</font>?",
    "hints_pt": [
      "Dica 1: Uma forma realmente de força bruta seria procurar por todos os pares possíveis de números, mas isso seria lento demais. De novo, é melhor tentar soluções de força bruta apenas por completude. É a partir dessas soluções de força bruta que você pode chegar a otimizações.",
      "Dica 2: Então, se fixarmos um dos números, digamos <code>x</code>, precisamos percorrer todo o array para encontrar o próximo número <code>y</code>, que é <code>value - x</code>, onde value é o parâmetro de entrada. Podemos alterar nosso array de alguma forma para que essa busca se torne mais rápida?",
      "Dica 3: A segunda linha de raciocínio é, sem alterar o array, podemos usar espaço adicional de alguma forma? Talvez uma tabela hash para acelerar a busca?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "2",
    "paidOnly": false,
    "title": "Add Two Numbers",
    "titleSlug": "add-two-numbers",
    "url": "https://leetcode.com/problems/add-two-numbers",
    "description_url": "https://leetcode.com/problems/add-two-numbers/description/",
    "description": "<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p>\n\n<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg\" style=\"width: 483px; height: 342px;\" />\n<pre>\n<strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4]\n<strong>Output:</strong> [7,0,8]\n<strong>Explanation:</strong> 342 + 465 = 807.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> l1 = [0], l2 = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\n<strong>Output:</strong> [8,9,9,9,0,0,0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>It is guaranteed that the list represents a number that does not have leading zeros.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/add-two-numbers/solutions/",
    "solution": "## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Elementary Math\n\n**Intuition**\n\nKeep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.\n\n![Illustration of Adding two numbers](../Figures/2_add_two_numbers.svg){:width=\"539px\"}\n\n\n*Figure 1. Visualization of the addition of two numbers: $$342 + 465 = 807$$.  \nEach node contains a single digit and the digits are stored in reverse order.*\n\n\n**Algorithm**\n\nJust like how you would sum two numbers on a piece of paper, we begin by summing the least-significant digits, which is the head of $$l1$$ and $$l2$$. Since each digit is in the range of $$0 \\ldots 9$$, summing two digits may \"overflow\". For example $$5 + 7 = 12$$. In this case, we set the current digit to $$2$$ and bring over the $$carry = 1$$ to the next iteration. $$carry$$ must be either $$0$$ or $$1$$ because the largest possible sum of two digits (including the carry) is $$9 + 9 + 1 = 19$$.\n\nThe pseudocode is as following:\n\n* Initialize current node to dummy head of the returning list.\n* Initialize carry to $$0$$.\n* Loop through lists $$l1$$ and $$l2$$ until you reach both ends and carry is $$0$$.\n    * Set $$x$$ to node $$l1$$'s value. If $$l1$$ has reached the end of $$l1$$, set to $$0$$.\n    * Set $$y$$ to node $$l2$$'s value. If $$l2$$ has reached the end of $$l2$$, set to $$0$$.\n    * Set $$sum = x + y + carry$$.\n    * Update $$carry = sum / 10$$.\n    * Create a new node with the digit value of $$(sum \\bmod 10)$$ and set it to current node's next, then advance current node to next.\n    * Advance both $$l1$$ and $$l2$$.\n* Return dummy head's next node.\n\nNote that we use a dummy head to simplify the code. Without a dummy head, you would have to write extra conditional statements to initialize the head's value.\n\nTake extra caution of the following cases:\n\n| Test case | Explanation |\n| ------------- | ---------------- |\n| $$l1=[0,1]$$<br>$$l2=[0,1,2]$$ | When one list is longer than the other. |\n| $$l1=[]$$<br>$$l2=[0,1]$$ | When one list is null, which means an empty list. |\n| $$l1=[9,9]$$<br>$$l2=[1]$$ | The sum could have an extra carry of one at the end, which is easy to forget. |\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/XsLdm2AA/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"XsLdm2AA\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(\\max(m, n))$$. Assume that $$m$$ and $$n$$ represents the length of $$l1$$ and $$l2$$ respectively, the algorithm above iterates at most $$\\max(m, n)$$ times.\n\n* Space complexity : $$O(1)$$. The length of the new list is at most $$\\max(m,n) + 1$$ However, we don't count the answer as part of the space complexity.\n\n**Follow up**\n\nWhat if the the digits in the linked list are stored in non-reversed order? For example:\n\n$$\n(3 \\to 4 \\to 2) + (4 \\to 6 \\to 5) = 8 \\to 0 \\to 7\n$$",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n    dummy = ListNode(0)\n    curr = dummy\n    carry = 0\n\n    while carry or l1 or l2:\n      if l1:\n        carry += l1.val\n        l1 = l1.next\n      if l2:\n        carry += l2.val\n        l2 = l2.next\n      curr.next = ListNode(carry % 10)\n      carry //= 10\n      curr = curr.next\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n    ListNode dummy = new ListNode(0);\n    ListNode curr = dummy;\n    int carry = 0;\n\n    while (l1 != null || l2 != null || carry > 0) {\n      if (l1 != null) {\n        carry += l1.val;\n        l1 = l1.next;\n      }\n      if (l2 != null) {\n        carry += l2.val;\n        l2 = l2.next;\n      }\n      curr.next = new ListNode(carry % 10);\n      carry /= 10;\n      curr = curr.next;\n    }\n\n    return dummy.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n    ListNode dummy(0);\n    ListNode* curr = &dummy;\n    int carry = 0;\n\n    while (l1 || l2 || carry) {\n      if (l1 != nullptr) {\n        carry += l1->val;\n        l1 = l1->next;\n      }\n      if (l2 != nullptr) {\n        carry += l2->val;\n        l2 = l2->next;\n      }\n      curr->next = new ListNode(carry % 10);\n      carry /= 10;\n      curr = curr->next;\n    }\n\n    return dummy.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/2.html",
    "category": "Algorithms",
    "acceptance_rate": 45.97311917981128,
    "topics": [
      "Linked List",
      "Math",
      "Recursion"
    ],
    "hints": [],
    "likes": 33475,
    "dislikes": 6721,
    "similar_questions": "[{\"title\": \"Multiply Strings\", \"titleSlug\": \"multiply-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Binary\", \"titleSlug\": \"add-binary\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Two Integers\", \"titleSlug\": \"sum-of-two-integers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Strings\", \"titleSlug\": \"add-strings\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Two Numbers II\", \"titleSlug\": \"add-two-numbers-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add to Array-Form of Integer\", \"titleSlug\": \"add-to-array-form-of-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Two Polynomials Represented as Linked Lists\", \"titleSlug\": \"add-two-polynomials-represented-as-linked-lists\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Double a Number Represented as a Linked List\", \"titleSlug\": \"double-a-number-represented-as-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"5.7M\", \"totalSubmission\": \"12.4M\", \"totalAcceptedRaw\": 5713509, \"totalSubmissionRaw\": 12427950, \"acRate\": \"46.0%\"}",
    "title_pt": "Adicionar Dois Números",
    "description_pt": "<p>Você recebe duas listas encadeadas <strong>não vazias</strong> que representam dois inteiros não negativos. Os dígitos são armazenados em <strong>ordem reversa</strong>, e cada um de seus nós contém um único dígito. Some os dois números e retorne a soma&nbsp;como uma lista encadeada.</p>\n\n<p>Você pode assumir que os dois números não contêm nenhum zero à esquerda, exceto o número 0 em si.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg\" style=\"width: 483px; height: 342px;\" />\n<pre>\n<strong>Entrada:</strong> l1 = [2,4,3], l2 = [5,6,4]\n<strong>Saída:</strong> [7,0,8]\n<strong>Explicação:</strong> 342 + 465 = 807.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> l1 = [0], l2 = [0]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\n<strong>Saída:</strong> [8,9,9,9,0,0,0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em cada lista encadeada está no intervalo <code>[1, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>É garantido que a lista representa um número que não possui zeros à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "3",
    "paidOnly": false,
    "title": "Longest Substring Without Repeating Characters",
    "titleSlug": "longest-substring-without-repeating-characters",
    "url": "https://leetcode.com/problems/longest-substring-without-repeating-characters",
    "description_url": "https://leetcode.com/problems/longest-substring-without-repeating-characters/description/",
    "description": "<p>Given a string <code>s</code>, find the length of the <strong>longest</strong> <span data-keyword=\"substring-nonempty\"><strong>substring</strong></span> without duplicate characters.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abcabcbb&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The answer is &quot;abc&quot;, with the length of 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;bbbbb&quot;\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The answer is &quot;b&quot;, with the length of 1.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;pwwkew&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The answer is &quot;wke&quot;, with the length of 3.\nNotice that the answer must be a substring, &quot;pwke&quot; is a subsequence and not a substring.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of English letters, digits, symbols and spaces.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def lengthOfLongestSubstring(self, s: str) -> int:\n    ans = 0\n    count = Counter()\n\n    l = 0\n    for r, c in enumerate(s):\n      count[c] += 1\n      while count[c] > 1:\n        count[s[l]] -= 1\n        l += 1\n      ans = max(ans, r - l + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int lengthOfLongestSubstring(String s) {\n    int ans = 0;\n    int[] count = new int[128];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      ++count[s.charAt(r)];\n      while (count[s.charAt(r)] > 1)\n        --count[s.charAt(l++)];\n      ans = Math.max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int lengthOfLongestSubstring(string s) {\n    int ans = 0;\n    vector<int> count(128);\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      ++count[s[r]];\n      while (count[s[r]] > 1)\n        --count[s[l++]];\n      ans = max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/3.html",
    "category": "Algorithms",
    "acceptance_rate": 36.73624411453885,
    "topics": [
      "Hash Table",
      "String",
      "Sliding Window"
    ],
    "hints": [
      "Generate all possible substrings & check for each substring if it's valid and keep updating maxLen accordingly."
    ],
    "likes": 41917,
    "dislikes": 2032,
    "similar_questions": "[{\"title\": \"Longest Substring with At Most Two Distinct Characters\", \"titleSlug\": \"longest-substring-with-at-most-two-distinct-characters\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Substring with At Most K Distinct Characters\", \"titleSlug\": \"longest-substring-with-at-most-k-distinct-characters\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subarrays with K Different Integers\", \"titleSlug\": \"subarrays-with-k-different-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Erasure Value\", \"titleSlug\": \"maximum-erasure-value\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Equal Count Substrings\", \"titleSlug\": \"number-of-equal-count-substrings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Consecutive Cards to Pick Up\", \"titleSlug\": \"minimum-consecutive-cards-to-pick-up\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Nice Subarray\", \"titleSlug\": \"longest-nice-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Optimal Partition of String\", \"titleSlug\": \"optimal-partition-of-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Complete Subarrays in an Array\", \"titleSlug\": \"count-complete-subarrays-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Longest Special Substring That Occurs Thrice II\", \"titleSlug\": \"find-longest-special-substring-that-occurs-thrice-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Longest Special Substring That Occurs Thrice I\", \"titleSlug\": \"find-longest-special-substring-that-occurs-thrice-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"7.4M\", \"totalSubmission\": \"20.1M\", \"totalAcceptedRaw\": 7399775, \"totalSubmissionRaw\": 20143025, \"acRate\": \"36.7%\"}",
    "title_pt": "Substring Mais Longa Sem Caracteres Repetidos",
    "description_pt": "<p>Dada uma string <code>s</code>, encontre o comprimento da <strong>maior</strong> <span data-keyword=\"substring-nonempty\"><strong>substring</strong></span> sem caracteres duplicados.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abcabcbb&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A resposta é &quot;abc&quot;, com comprimento 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;bbbbb&quot;\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> A resposta é &quot;b&quot;, com comprimento 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;pwwkew&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A resposta é &quot;wke&quot;, com comprimento 3.\nObserve que a resposta deve ser uma substring, &quot;pwke&quot; é uma subsequência e não uma substring.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste em letras इंग?",
    "hints_pt": [
      "Dica 1: Gere todas as substrings possíveis e verifique, para cada substring, se ela é válida e continue atualizando `maxLen` de acordo."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "4",
    "paidOnly": false,
    "title": "Median of Two Sorted Arrays",
    "titleSlug": "median-of-two-sorted-arrays",
    "url": "https://leetcode.com/problems/median-of-two-sorted-arrays",
    "description_url": "https://leetcode.com/problems/median-of-two-sorted-arrays/description/",
    "description": "<p>Given two sorted arrays <code>nums1</code> and <code>nums2</code> of size <code>m</code> and <code>n</code> respectively, return <strong>the median</strong> of the two sorted arrays.</p>\n\n<p>The overall run time complexity should be <code>O(log (m+n))</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,3], nums2 = [2]\n<strong>Output:</strong> 2.00000\n<strong>Explanation:</strong> merged array = [1,2,3] and median is 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2], nums2 = [3,4]\n<strong>Output:</strong> 2.50000\n<strong>Explanation:</strong> merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>nums1.length == m</code></li>\n\t<li><code>nums2.length == n</code></li>\n\t<li><code>0 &lt;= m &lt;= 1000</code></li>\n\t<li><code>0 &lt;= n &lt;= 1000</code></li>\n\t<li><code>1 &lt;= m + n &lt;= 2000</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/median-of-two-sorted-arrays/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n\n---\n <div class='video-preview'></div>\n\n## Solution\n\n--- \n\n### Overview\n\nIn this problem, we are given two **sorted** arrays, `nums1` and `nums2`. We need to return the **median** of these two arrays.\n\n---\n\n### Approach 1: Merge Sort\n\n#### Intuition   \n\nLet's start with the straightforward approach. If we put the elements of two arrays in one array `A` and arrange them in order. Assume the merged arrays has a length of `n`, then the median is:\n    - `A[n / 2]`, if `n` is odd.\n    - The average of `A[n / 2]` and `A[n / 2 + 1]`, if `n` is even.\n\nHowever, we do not really need to merge and sort these arrays. Note that both arrays are already sorted, so the smallest element is either the first element of `nums1` or the first element of `nums2`. Therefore, we can set two pointers `p1` and `p2` at the start of each array, then we can get the smallest element from the `nums1` and `nums2` by comparing the values `nums1[p1]` and `nums2[p2]`.\n\nPlease refer to the following slide as an example:\n\n!?!../Documents/4/s1.json:601,301!?!\n\n\n<br>\n\n#### Algorithm\n\n1) Get the total size of two arrays `m + n`\n    - If `m + n` is odd, we are looking for the `(m + n) / 2`-th element.\n    - If `m + n` is even, we are looking for the average of the `(m + n) / 2`-th and the `(m + n) / 2 + 1`-th elements.\n2) Set two pointers `p1` and `p2` at the beginning of arrays `nums1` and `nums2`. \n3) If both `p1` and `p2` are in bounds of the arrays, compare the values at `p1` and `p2`:\n\n    - If `nums1[p1]` is smaller than `nums2[p2]`, we move `p1` one place to the right.\n    - Otherwise, we move `p2` one place to the right.\n\n    If `p1` is outside `nums1`, just move `p2` one place to the right.     \n    If `p2` is outside `nums2`, just move `p1` one place to the right.\n4) Get the target elements and calculate the median:\n    - If `m + n` is odd, repeat step 3 by `(m + n + 1) / 2` times and return the element from the last step.\n    - If `m + n` is even, repeat step 3 by `(m + n) / 2 + 1` times and return the average of the elements from the last two steps.\n\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/76VATgZB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"76VATgZB\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$m$$ be the size of array `nums1` and $$n$$ be the size of array `nums2`.\n\n* Time complexity: $$O(m + n)$$\n\n    - We get the smallest element by comparing two values at `p1` and `p2`, it takes $$O(1)$$ to compare two elements and move the corresponding pointer to the right.\n    - We need to traverse half of the arrays before reaching the median element(s).\n    - To sum up, the time complexity is $$O(m + n)$$.\n    \n\n* Space complexity: $$O(1)$$\n\n    - We only need to maintain two pointers `p1` and `p2`.\n\n<br/>\n\n\n\n---\n\n### Approach 2: Binary Search, Recursive\n\n#### Intuition   \n\nBecause the inputs are sorted arrays and the problem asks for a logarithmic time limit, we strongly feel that binary search (or a similar approach) is a promising method. While we're not sure how to cast the same pattern as a normal binary search on this problem, let's go over some steps of a regular binary search and see if we can get any inspiration. (If you are not familiar with binary search, you can refer to our [Binary Search Explore Card](https://leetcode.com/explore/learn/card/binary-search/))\n\n\nHere we use binary search to find `target` in a sorted array `A`:\n\n- Locate the middle index (element) of `A`.\n- Compare the value of the middle element with `target`.\n- Reduce the search space by cutting the current array in half and discarding the half which is guaranteed not to contain `target`.\n\n- Repeat the above process until we either empty the array (move to half a the length of 0) or find `target`.\n\n\n\n![img](../Figures/4/bs.png)\n\nAt each step, the search space is cut in half, so we can quickly get the result. Now back to this problem where we have two sorted arrays. For the sake of convenience, let's call them `A` and `B`. \n\n![img](../Figures/4/2.png)\n\nSimilarly, we can get and compare their middle values `A_mid` and `B_mid`. Without loss of generality in this example we assume `A_mid <= B_mid` initially, as shown in the yellow boxes. \n\n\n\n![img](../Figures/4/3.png)\n\n**What does this comparison imply?**\n\nIt implies that we can compare sections of `A` and `B`.\n\n> For the rest of this article, we will use $$\\le$$ to represent the relative magnitude of values in arrays. For example, $$A_{\\text{left}} \\le A_{\\text{right}}$$ means that every element in $A_{\\text{left}}$ is no larger than any element in $A_{\\text{right}}$. We also 'compare' elements in an array with a single element similarly, for example, $$A_{\\text{left}} \\le A_{\\text{mid}}$$ means that every element in $A_{\\text{left}}$ is no larger than the element $A_{\\text{mid}}$. \nThis may not be the most standard way of expressing it, but is easy enough to understand.\n\nRecall that both arrays are sorted, so we know that:\n- $$A_{\\text{left}} \\le A_{\\text{mid}}$$\n- $$B_{\\text{mid}} \\le B_{\\text{right}}$$\n\nCombine these observations with the comparison we just made:\n\n\n$$A_{\\text{mid}} \\le B_{\\text{mid}}$$\n\nWe have the following result:\n\n$$A_{\\text{left}} \\le A_{\\text{mid}} \\le B_{\\text{mid}} \\le B_{\\text{right}}$$\n\nThus, \n\n$$A_{\\text{left}} \\le B_{\\text{right}}$$\n\nAs shown in the picture below:\n\n![img](../Figures/4/4.png)\n\nSince `A` is sorted, we know that $$A_{\\text{left}} \\le A_{\\text{right}}$$.\n\n![img](../Figures/4/5.png)\n\n\nNow we know that `A_left` is smaller than two halves: `A_right` and `B_right`. Although we still don't know where exactly these elements are, what we do know is **`A_left` doesn't intersect with `A_right + B_right`**! There is an invisible boundary between the `A_left` segment and the mixed segment `A_right + B_right`. As shown in the picture below, the dashed line divides all sorted elements into two halves.\n\n\n\n![img](../Figures/4/6.png)\n\n\nWe can apply all the same logic to the mixed segment $$A_{\\text{left}}$$ + $$B_{\\text{left}}$$ and $$B_{\\text{right}}$$, which also do not intersect. You can try to prove it yourself as an exercise.\n\n\n![img](../Figures/4/7.png)\n\n\nIt looks somewhat clearer, we have clearly separated some subarrays. How do we continue to leverage this knowledge and use the cut-in-half method repeatedly?\n\n\n\n<br>\n\n**The following step is the most important one.**\n\n\nRemember that we are looking for the median of `sorted A + B` which is one or two target values. We regard the index of the target value in the `sorted(A + B)` as `k`. For example: \n\n- If the lengths of `A` and `B` are `6` and `5`, the target index is `k = (6 + 5 + 1) / 2 = 6`, we shall look for the 6th smallest element. \n\n- If the lengths of `A` and `B` are `6` and `6`, the target indexes are `k = (6 + 6) / 2 = 6` and `k + 1 = 7`, we shall look for the 6th and the 7th smallest elements. \n\n\n\nDepending on whether the total number of elements is odd or even, we need the $$k^{th}$$ (and maybe the $$(k + 1)^{th}$$) elements. What matters is that we set an index `k` at the beginning and we want to find the $$k^{th}$$ smallest element using the Binary Search-like algorithm discussed previously (for convenience, we will discuss only the $$k^{th}$$ element for now).\n\n\n\nHowever, during the Binary Search-like algorithm, we keep removing one half of an array, so the index `k` might not stay unchanged. Suppose we removed `3` elements that are smaller than the original $$k^{th}$$ smallest element, we shall look for the $$(k-3)^{th}$$ smallest element from the **remaining** arrays.\n\n\n![img](../Figures/4/exp_1.png)\n\nMore specifically:\n\nIf `k` is larger than half the total number of elements in `sorted(A + B)`, it means that the $$k^{th}$$ element is in the second (larger) half of `sorted(A + B)`, thus $$A_{\\text{left}}$$ (or $$B_{\\text{left}}$$, the smaller of the two smaller sections according to the comparison) is guaranteed not to contain this element, and we can safely cut this half, and reduce `k` by the length of the removed half.\n\n\nIf `k` is not larger than half the total number of elements in `sorted(A + B)`, it means that the $$k^{th}$$ element is in the first (smaller) half of `sorted(A + B)`, thus $$B_{\\text{right}}$$ (or $$A_{\\text{right}}$$, the larger of the two larger sections according to the comparison) is guaranteed not to contain this element, and we can safely discard it. Note that we don't need to modify `k` this time, since we removed one larger half that doesn't affect the order of the $$k^{th}$$ smallest element.\n\n\n\nWe can continue our search like above in the **remaining** arrays. The long arrow that starts from the bottom and points to the top-left indicates that we are repeating the process. Once we cut off part of either `A` or `B`, we regard the remaining arrays as modified `A` and `B` and restart this algorithm. Note that the following picture represents one case only: we consider the case that `a_value < b_value`, thus we remove either the smaller half of `A` or the larger half of `B`. If the comparison result is `a_value >= b_value`, we shall remove either the smaller half of `B` or the larger half of `A`.\n\n![img](../Figures/4/9.png)\n\n\nThat's it. We cut one of the two arrays in half at each step, so this approach has a logarithmic time complexity which we will discuss in detail later.\n\n\n> One more thing!\n\nIn the previous picture, we repeat all processes using the modified arrays, but this is just for the sake of understanding. We won't create copies of two arrays repeatedly, because that would introduce a linear time complexity at least. Instead, we just treat a part of the original array as the modified array for the next step, so that we can repeat the process on the original array without making any duplication. To do this, we need to maintain four pointers, two pointers for each array, e.g., `a_start` and `a_end` represent an inclusive range `[a_start, a_end]` of `A`.\n\n\n<br>\n\n#### Algorithm\n\nLet's define a function that helps us find the $$k^{th}$$ smallest element from two inclusive ranges `[a_start, a_end]` and `[b_start, b_end]` from arrays `A` and `B`.\n\n\n\n1) If the range (for example, a range of `A`) is empty, in other words `a_start > a_end`, it means all elements in `A` are passed, we just return the `(k - a_start)`-th element from the other array `B`. Vice versa if `b_start > b_end`.\n\n2) Otherwise, get the middle indexes of the two ranges: `a_index = (a_start + a_end) / 2`, `b_index = (b_start + b_end) / 2`.\n3) Get the middle values of the two ranges: `a_value = A[a_index]`, `b_value = B[b_index]`.\n4) Cut one array in half, according to:\n    - If `a_index + b_index < k`, cut one smaller half.\n        - If `a_value < b_value`, cut the smaller half of `A`.\n        - Otherwise, cut the smaller half of `B`.\n    - Otherwise, cut one larger half.\n        - If `b_value < a_value`, cut the larger half of `B`.\n        - Otherwise, cut the larger half of `A`.\n5) Repeat step 1 using the new starting and ending indexes of `A` and `B`.\n\n\nThen we move on to find the median elements, and get the length of both arrays `na = len(A)` and `nb = len(B)`.\n- If the total number of elements in `A` and `B` is odd, we just use the above function to find the middle element, that is `k = (na + nb) / 2`.\n- Otherwise, we use the function to find two middle elements: `k = (na + nb) / 2 - 1` and `k = (na + nb) / 2`, and return their average.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/EykqB3jM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"EykqB3jM\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$m$$ be the size of array `nums1` and $$n$$ be the size of array `nums2`.\n\n* Time complexity: $$O(\\log(m \\cdot n))$$\n\n\n    - At each step, we cut one half off from either `nums1` or `nums2`. If one of the arrays is emptied, we can directly get the target from the other array in a constant time. Therefore, the total time spent depends on when one of the arrays is cut into an empty array.\n    - In the worst-case scenario, we may need to cut both arrays before finding the target element.\n    - One of the two arrays is cut in half at each step, thus it takes logarithmic time to empty an array. The time to empty two arrays are independent of each other.\n\n    <br>\n    \n    ![img](../Figures/4/tc.png)\n\n    - Therefore, the time complexity is $$O(\\log m + \\log n)$$.\n     $$O(\\log m + \\log n) = O(\\log (m\\cdot n))$$\n    \n\n* Space complexity: $$O(\\log m + \\log n)$$\n\n    - Similar to the analysis on time complexity, the recursion steps depend on the number of iterations before we cut an array into an empty array. In the worst-case scenario, we need $$O(\\log m + \\log n)$$ recursion steps. \n    - However, during the recursive self-call, we only need to maintain 4 pointers: `a_start`, `a_end`, `b_start` and `b_end`. The last step of the function is to call itself, so if tail call optimization is implemented, the call stack always has $$O(1)$$ records.\n\n    - Please refer to [Tail Call](https://en.wikipedia.org/wiki/Tail_call) for more information on tail call optimization.\n\n<br/>\n\n\n\n---\n\n### Approach 3: A Better Binary Search\n\n\n#### Intuition   \n\nRecall the previous approach where we perform a binary search over the 'merged' array consisting of `nums1` and `nums2`, resulting in a time complexity of $$O(\\log(m \\cdot n))$$. We could further improve the algorithm by performing the binary search only on the smaller array of `nums1` and `nums2`, thus the time complexity is reduced to $$O(\\log(\\min(m, n)))$$.\n\n\nThe main idea is similar to approach 2, where we need to find a point of partition in both arrays such that the maximum of the smaller half is less than or equal to the minimum of the larger half. \n\n\nHowever, instead of partitioning over the merged arrays, we can only focus on partitioning the smaller array (let's call this array `A`). Suppose the partition index is `partitionA`, we specify that the smaller half contains `(m + n + 1) / 2` elements, and we can use this feature to our advantage by directly making `partitionB` equal to `(m + n + 1) / 2 - partitionA`, thus the smaller halves of both arrays always contain a total of `(m + n + 1) / 2` elements, as shown in the picture below.\n\n![img](../Figures/4/2_0.png)\n\nThe next step is to compare these edge elements.\n\n![img](../Figures/4/2_1.png)\n\nIf both `maxLeftA <= minRightB` and `maxLeftB <= minRightA` hold, it means that we have partitioned arrays at the correct place. \n\n- The smaller half consists of two sections `A_left` and `B_left`\n- THe larger half consists of two sections `A_right` and `B_right`\n\nWe just need to find the maximum value from the smaller half as `max(A[maxLeftA], B[maxLeftB])` and the minimum value from the larger half as `min(A[minRightA], B[minRightB])`. The median value depends on these four boundary values and the total length of the input arrays and we can compute it by situation.\n\n![img](../Figures/4/2_2.png)\n\nIf `maxLeftA > minRightB`, it implies that `maxLeftA` is **too large to be in the smaller half** and we should look for a smaller partition value of `A`. \n\n\n![img](../Figures/4/2_3.png)\n\nOtherwise, it denotes that `minRightA` is **too small to be in the larger half** and we should look for a larger partition value of `A`.\n\n![img](../Figures/4/2_4.png)\n\n\n<br>\n\n#### Algorithm\n\n1) Assuming `nums1` to be the smaller array (If `nums2` is smaller, we can swap them). Let `m, n` represent the size of `nums1` and `nums2`, respectively.\n\n2) Define the search space for the partitioning index `partitionA` by setting boundaries as `left = 0` and `right = m`.\n\n3) While `left <= right` holds, do the following.\n\n4) Compute the partition index of `nums1` as `partitionA = (left + right) / 2`. Consequently, the partition index of `nums2` is `(m + n + 1) / 2 - partitionA`.\n\n5) Obtain the edge elements:\n    - Determine the maximum value of the section `A_left` as `maxLeftA = nums1[partitionA - 1]`. If `partitionA - 1 < 0`, set it as `maxLeftA = float(-inf)`.\n    - Determine the minimum value of the section `A_right` as `minRightA = nums1[partitionA]`. If `partitionA >= m`, set it as `minRightA = float(inf)`.\n    - Determine the maximum value of the section `B_left` as `maxLeftB = nums2[partitionB - 1]`. If `partitionB - 1 < 0`, set it as `maxLeftB = float(-inf)`.\n    - Determine the maximum value of the section `B_right` as `minRightB = nums2[partitionB]`. If `partitionB >= n`, set it as `minRightB = float(inf)`.\n\n\n6) Compare and recalculate: Compare `maxLeftA` with `minRightB` and `maxLeftB` with `minRightA`. \n    - If `maxLeftA > minRightB`, it means the `maxLeftA` is too large to be in the smaller half, so we update `right = partitionA - 1` to move to the left half of the search space.\n    - If `maxLeftB > minRightA`, it means that we are too far on the left side for `partitionA` and we need to go to the right half of the search space by updating `left = partitionA + 1`. \n\n    Repeat step 4.\n\n7) When both `maxLeftA <= minRightB` and `maxLeftB <= minRightA` are true:\n    - If `(m + n) % 2 = 0`, the median value is the average of the maximum value of the smaller half and the minimum value of the larger half, given by `answer = (max(maxLeftA, maxLeftB) + min(minRightA, minRightB)) / 2`.\n    - Otherwise, the median value is the maximum value of the smaller half, given by `answer = max(maxLeftA, maxLeftB)`.\n\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/4xFHzYdC/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4xFHzYdC\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$m$$ be the size of array `nums1` and $$n$$ be the size of array `nums2`.\n\n* Time complexity: $$O(\\log(\\min(m, n)))$$\n\n    - We perform a binary search over the smaller array of size $$\\min(m, n)$$.\n\n* Space complexity: $$O(1)$$\n\n    - The algorithm only requires a constant amount of additional space to store and update a few parameters during the binary search.\n\n<br/>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n    n1 = len(nums1)\n    n2 = len(nums2)\n    if n1 > n2:\n      return self.findMedianSortedArrays(nums2, nums1)\n\n    l = 0\n    r = n1\n\n    while l <= r:\n      partition1 = (l + r) // 2\n      partition2 = (n1 + n2 + 1) // 2 - partition1\n      maxLeft1 = -2**31 if partition1 == 0 else nums1[partition1 - 1]\n      maxLeft2 = -2**31 if partition2 == 0 else nums2[partition2 - 1]\n      minRight1 = 2**31 - 1 if partition1 == n1 else nums1[partition1]\n      minRight2 = 2**31 - 1 if partition2 == n2 else nums2[partition2]\n      if maxLeft1 <= minRight2 and maxLeft2 <= minRight1:\n        return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 if (n1 + n2) % 2 == 0 else max(maxLeft1, maxLeft2)\n      elif maxLeft1 > minRight2:\n        r = partition1 - 1\n      else:\n        l = partition1 + 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n    final int n1 = nums1.length;\n    final int n2 = nums2.length;\n    if (n1 > n2)\n      return findMedianSortedArrays(nums2, nums1);\n\n    int l = 0;\n    int r = n1;\n\n    while (l <= r) {\n      final int partition1 = (l + r) / 2;\n      final int partition2 = (n1 + n2 + 1) / 2 - partition1;\n      final int maxLeft1 = partition1 == 0 ? Integer.MIN_VALUE : nums1[partition1 - 1];\n      final int maxLeft2 = partition2 == 0 ? Integer.MIN_VALUE : nums2[partition2 - 1];\n      final int minRight1 = partition1 == n1 ? Integer.MAX_VALUE : nums1[partition1];\n      final int minRight2 = partition2 == n2 ? Integer.MAX_VALUE : nums2[partition2];\n      if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)\n        return (n1 + n2) % 2 == 0\n            ? (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) * 0.5\n            : Math.max(maxLeft1, maxLeft2);\n      else if (maxLeft1 > minRight2)\n        r = partition1 - 1;\n      else\n        l = partition1 + 1;\n    }\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n    const int n1 = nums1.size();\n    const int n2 = nums2.size();\n    if (n1 > n2)\n      return findMedianSortedArrays(nums2, nums1);\n\n    int l = 0;\n    int r = n1;\n\n    while (l <= r) {\n      const int partition1 = (l + r) / 2;\n      const int partition2 = (n1 + n2 + 1) / 2 - partition1;\n      const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1];\n      const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1];\n      const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1];\n      const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2];\n      if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1)\n        return (n1 + n2) % 2 == 0\n                   ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5\n                   : max(maxLeft1, maxLeft2);\n      else if (maxLeft1 > minRight2)\n        r = partition1 - 1;\n      else\n        l = partition1 + 1;\n    }\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/4.html",
    "category": "Algorithms",
    "acceptance_rate": 43.522901794767925,
    "topics": [
      "Array",
      "Binary Search",
      "Divide and Conquer"
    ],
    "hints": [],
    "likes": 29976,
    "dislikes": 3366,
    "similar_questions": "[{\"title\": \"Median of a Row Wise Sorted Matrix\", \"titleSlug\": \"median-of-a-row-wise-sorted-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.4M\", \"totalSubmission\": \"7.7M\", \"totalAcceptedRaw\": 3356457, \"totalSubmissionRaw\": 7711954, \"acRate\": \"43.5%\"}",
    "title_pt": "Mediana de Dois Arrays Ordenados",
    "description_pt": "<p>Dados dois arrays ordenados <code>nums1</code> e <code>nums2</code> de tamanhos <code>m</code> e <code>n</code>, respectivamente, retorne <strong>a mediana</strong> dos dois arrays ordenados.</p>\n\n<p>A complexidade de tempo total deve ser <code>O(log (m+n))</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,3], nums2 = [2]\n<strong>Saída:</strong> 2.00000\n<strong>Explicação:</strong> array mesclado = [1,2,3] e a mediana é 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2], nums2 = [3,4]\n<strong>Saída:</strong> 2.50000\n<strong>Explicação:</strong> array mesclado = [1,2,3,4] e a mediana é (2 + 3) / 2 = 2.5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>nums1.length == m</code></li>\n\t<li><code>nums2.length == n</code></li>\n\t<li><code>0 &lt;= m &lt;= 1000</code></li>\n\t<li><code>0 &lt;= n &lt;= 1000</code></li>\n\t<li><code>1 &lt;= m + n &lt;= 2000</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "5",
    "paidOnly": false,
    "title": "Longest Palindromic Substring",
    "titleSlug": "longest-palindromic-substring",
    "url": "https://leetcode.com/problems/longest-palindromic-substring",
    "description_url": "https://leetcode.com/problems/longest-palindromic-substring/description/",
    "description": "<p>Given a string <code>s</code>, return <em>the longest</em> <span data-keyword=\"palindromic-string\"><em>palindromic</em></span> <span data-keyword=\"substring-nonempty\"><em>substring</em></span> in <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;babad&quot;\n<strong>Output:</strong> &quot;bab&quot;\n<strong>Explanation:</strong> &quot;aba&quot; is also a valid answer.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cbbd&quot;\n<strong>Output:</strong> &quot;bb&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consist of only digits and English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-palindromic-substring/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n\n---\n <div class='video-preview'></div>\n\n\n## Solution\n\n---\n\n### Approach 1: Check All Substrings\n\n**Intuition**\n\nWe can start with a brute-force approach. We will simply check if each substring is a palindrome, and take the longest one that is.\n\nFirst, let's talk about how we can check if a given string is a palindrome. This is a classic problem and we can do it using two pointers. If a string is a palindrome, the first character is equal to the last character. The second character is equal to the second last character, and so on.\n\n![Palindrome Check](../Figures/5/1.png)\n\nWe initialize two pointers: one at the start of the string and another at the end of it. We check if the characters at the pointers are equal - if they aren't, we know the string cannot be a palindrome. If they are equal, we move to the next pair of characters by moving the pointers toward each other. We continue until we either find a mismatch or the pointers meet. If the pointers meet, then we have checked all pairs and we know the string is a palindrome.\n\nOne bonus to using this algorithm is that we frequently exit early on strings that are not palindromes. If you had a string of length `1000` and the third and third last characters did not match, we would exit the algorithm after only 3 iterations.\n\nThere's another optimization that we can do. Because the problem wants the longest palindrome, we can start by checking the longest-length substrings and iterate toward the shorter-length substrings. This way, the first time we find a substring that is a palindrome, we can immediately return it as the answer.\n\n**Algorithm**\n\n1. Create a helper method `check(i, j)` to determine if a substring is a palindrome.\n    - To save space, we will not pass the substring itself. Instead, we will pass two indices that represent the substring in question. The first character will be `s[i]` and the last character will be `s[j - 1]`.\n    - In this function, declare two pointers `left = i` and `right = j - 1`.\n    - While `left < right`, do the following steps:\n    - If `s[left] != s[right]`, return `false`.\n    - Otherwise, increment `left` and decrement `right`.\n    - If we get through the while loop, return `true`.\n2. Use a for loop to iterate a variable `length` starting from `s.length` until `1`. This variable represents the length of the substrings we are currently considering.\n3. Use a for loop to iterate a variable `start` starting from `0` until and including `s.length - length`. This variable represents the starting point of the substring we are currently considering.\n4. In each inner loop iteration, we are considering the substring starting at `start` until `start + length`. Pass these values into `check` to see if this substring is a palindrome. If it is, return the substring.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/nzeDdUw9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"nzeDdUw9\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`,\n\n* Time complexity: $$O(n^3)$$\n\n    The two nested for loops iterate $$O(n^2)$$ times. We check one substring of length `n`, two substrings of length `n - 1`, three substrings of length `n - 2`, and so on.\n\n    There are `n` substrings of length 1, but we don't check them all since any substring of length 1 is a palindrome, and we will return immediately.\n\n    Therefore, the number of substrings that we check in the worst case is `1 + 2 + 3 + ... + n - 1`. This is the partial sum of [this series](https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF#Partial_sums) for `n - 1`, which is equal to $$\\frac{n \\cdot (n - 1)}{2} = O(n^2)$$.\n\n    In each iteration of the while loop, we perform a palindrome check. The cost of this check is linear with `n` as well, giving us a time complexity of $$O(n^3)$$.\n\n    Note that this time complexity is in the worst case and has a significant constant divisor that is dropped by big O. Due to the optimizations of checking the longer length substrings first and exiting the palindrome check early if we determine that a substring cannot be a palindrome, the practical runtime of this algorithm is not too bad.\n\n* Space complexity: $$O(1)$$\n\n    We don't count the answer as part of the space complexity. Thus, all we use are a few integer variables. \n    \n<br/>\n\n---\n\n### Approach 2: Dynamic Programming\n\n**Intuition**\n\nLet's say that we knew the substring with inclusive bounds `i, j` was a palindrome. If `s[i - 1] == s[j + 1]`, then we know the substring with inclusive bounds `i - 1, j + 1` must also be a palindrome, and this check can be done in constant time.\n\nWe can flip the direction of this logic as well - if `s[i] == s[j]` and the substring `i + 1, j - 1` is a palindrome, then the substring `i, j` must also be a palindrome.\n\n![DP Example](../Figures/5/2.png)\n\nWe know that all substrings of length 1 are palindromes. From this, we can check if each substring of length 3 is a palindrome using the above fact. We just need to check every `i, j` pair where `j - i = 2`. Once we know all palindromes of length 3, we can use that information to find all palindromes of length 5, and then 7, and so on.\n\nWhat about even-length palindromes? A substring of length 2 is a palindrome if both characters are equal. That is, `i, i + 1` is a palindrome if `s[i] == s[i + 1]`. From this, we can use the earlier logic to find all palindromes of length 4, then 6, and so on.\n\nLet's use a table `dp` with dimensions of `n * n`. `dp[i][j]` is a boolean representing if the substring with inclusive bounds `i, j` is a palindrome. We initialize `dp[i][i] = true` for the substrings of length 1, and then `dp[i][i + 1] = (s[i] == s[i + 1])` for the substrings of length 2.\n\nNow, we need to populate the table. We iterate over all `i, j` pairs, starting with pairs that have a difference of 2 (representing substrings of length 3), then pairs with a difference of 3, then 4, and so on. For each `i, j` pair, we check the condition from earlier:\n\n`s[i] == s[j] && dp[i + 1][j - 1]`\n\nIf this condition is true, then the substring with inclusive bounds `i, j` must be a palindrome. We set `dp[i][j] = true`.\n\nBecause we are starting with the shortest substrings and iterating toward the longest substrings, every time we find a new palindrome, it must be the longest one we have seen so far. We can use this fact to keep track of the answer on the fly.\n\n**Algorithm**\n\n1. Initialize `n = s.length` and a boolean table `dp` with size `n * n`, and all values to `false`.\n2. Initialize `ans = [0, 0]`. This will hold the inclusive bounds of the answer.\n3. Set all `dp[i][i] = true`.\n4. Iterate over all pairs `i, i + 1`. For each one, if `s[i] == s[i + 1]`, then set `dp[i][i + 1] = true` and update `ans = [i, i + 1]`.\n5. Now, we populate the `dp` table. Iterate over `diff` from `2` until `n`. This variable represents the difference `j - i`.\n6. In a nested for loop, iterate over `i` from `0` until `n - diff`.\n    - Set `j = i + diff`.\n    - Check the condition: if `s[i] == s[j] && dp[i + 1][j - 1]`, we found a palindrome.\n    - In that case, set `dp[i][j] = true` and `ans = [i, j]`\n\n7. Retrieve the answer bounds from `ans` as `i, j`. Return the substring of `s` starting at index `i` and ending with index `j`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/futnTSvZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"futnTSvZ\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`,\n\n* Time complexity: $$O(n^2)$$\n\n    We declare an `n * n` table `dp`, which takes $$O(n^2)$$ time. We then populate $$O(n^2)$$ states `i, j` - each state takes $$O(1)$$ time to compute.\n\n* Space complexity: $$O(n^2)$$\n\n    The table `dp` takes $$O(n^2)$$ space.\n    \n<br/>\n\n---\n\n### Approach 3: Expand From Centers\n\n**Intuition**\n\nIn the first approach, the palindrome check cost $$O(n)$$. In the second approach, the palindrome check cost $$O(1)$$. This allowed us to improve the time complexity from $$O(n^3)$$ to $$O(n^2)$$.\n\nThe problem with the second approach is that we **always** iterated over $$O(n^2)$$ states of `i, j`. Can we optimize further to minimize the number of iterations required?\n\nIn the first approach, we implemented a palindrome check using two pointers. We started by checking the first and last characters, then the second and second last characters, and so on.\n\nInstead of starting the pointers at the edges and moving inwards, the same logic can be applied when starting the pointers at the center and moving outwards. A palindrome mirrors around its center. Let's say you had `s = \"racecar\"`. If we start both pointers at the middle (`\"e\"`) and move them away from each other, we can see that at every iteration, the characters match: `e -> c -> a -> r`.\n\nThe previous two approaches focused on the bounds of a substring - `i, j`. There are $$O(n^2)$$ bounds, but only $$O(n)$$ centers. For each index `i`, we can consider odd-length palindromes by starting the pointers at `i, i`. To consider the even length palindromes, we can start the pointers at `i, i + 1`. There are $$n$$ starting points for the odd-length palindromes and $$n - 1$$ starting points for the even-length palindromes - that's $$2n - 1 = O(n)$$ starting points in total.\n\nThis is very promising - we can lower the minimum iterations required if we focus on the centers instead of on the bounds. Let's use a helper method `expand(i, j)` that starts two pointers `left = i` and `right = j`. In this method, we will consider `i, j` as a center. When `i == j`, we are considering odd-length palindromes. When `i != j`, we are considering even-length palindromes. We will expand from the center as far as we can to find the longest palindrome, and then return the length of this palindrome.\n\nLet's say that we have a center `i, i`. We call `expand` and find a length of `length`. What are the bounds of the palindrome? Because we are centered at `i, i`, it means `length` must be odd. If we perform floor division of `length` by 2, we will get the number of characters `dist` on each side of the palindrome. For example, given `s = \"racecar\"`, we have `length = 7` and `dist = 7 / 2 = 3`. There are 3 characters on each side - `\"rac\"` on the left and `\"car\"` on the right. Therefore, we can determine that the bounds of the palindrome are `i - dist, i + dist`.\n\nWhat about a center at `i, i + 1`? `length` must be even now. If we have a palindrome with length `2`, then `length / 2 = 1`, but there are zero characters on each side of the center. We can see that `dist` is too large by 1. Therefore, we will calculate `dist` as `(length / 2) - 1` instead. Now, `dist` correctly represents the number of characters on each side. The bounds of the palindrome are `i - dist, i + 1 + dist`.\n\n**Algorithm**\n\n1. Create a helper method `expand(i, j)` to find the length of the longest palindrome centered at `i, j`.\n    - Set `left = i` and `right = j`.\n    - While `left` and `right` are both in bounds and `s[left] == s[right]`, move the pointers away from each other.\n    - The formula for the length of a substring starting at `left` and ending at `right` is `right - left + 1`.\n    - However, when the while loop ends, it implies `s[left] != s[right]`. Therefore, we need to subtract `2`. Return `right - left - 1`.\n2. Initialize `ans = [0, 0]`. This will hold the inclusive bounds of the answer.\n3. Iterate `i` over all indices of `s`.\n    - Find the length of the longest odd-length palindrome centered at `i`: `oddLength = expand(i, i)`.\n    - If `oddLength` is the greatest length we have seen so far, i.e. `oddLength > ans[1] - ans[0] + 1`, update `ans`.\n    - Find the length of the longest odd-length palindrome centered at `i`: `evenLength = expand(i, i + 1)`.\n    - If `evenLength` is the greatest length we have seen so far, update `ans`.\n4. Retrieve the answer bounds from `ans` as `i, j`. Return the substring of `s` starting at index `i` and ending with index `j`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/oTLQzLEK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"oTLQzLEK\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`,\n\n* Time complexity: $$O(n^2)$$\n\n    There are $$2n - 1 = O(n)$$ centers. For each center, we call `expand`, which costs up to $$O(n)$$.\n\n    Although the time complexity is the same as in the DP approach, the average/practical runtime of the algorithm is much faster. This is because most centers will not produce long palindromes, so most of the $$O(n)$$ calls to `expand` will cost far less than $$n$$ iterations.\n\n    The worst case scenario is when every character in the string is the same.\n\n* Space complexity: $$O(1)$$\n\n    We don't use any extra space other than a few integers. This is a big improvement on the DP approach.\n    \n<br/>\n\n---\n\n### Approach 4: Manacher's Algorithm\n\nBelieve it or not, this problem can be solved in linear time.\n\n[Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm) finds the longest palindromic substring in $$O(n)$$ time and space.\n\nNote: this algorithm is completely out of scope for coding interviews. Because of this, we will not be talking about the algorithm in detail. This approach has been included for the sake of completeness and for those who are curious about algorithms beyond the scope of interviews.\n\nIf you wish to learn more about Manacher's algorithm, please reference the above link.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/5JHr3EVn/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5JHr3EVn\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`,\n\n* Time complexity: $$O(n)$$\n\n    From Wikipedia (the implementation they describe is slightly different from the above code, but it's the same algorithm):\n\n    > The algorithm runs in linear time. This can be seen by noting that Center strictly increases after each outer loop and the sum Center + Radius is non-decreasing. Moreover, the number of operations in the first inner loop is linear in the increase of the sum Center + Radius while the number of operations in the second inner loop is linear in the increase of Center. Since Center $$\\leq$$ 2n+1 and Radius $$\\leq$$ n, the total number of operations in the first and second inner loops is $$O(n)$$ and the total number of operations in the outer loop, other than those in the inner loops, is also $$O(n)$$. The overall running time is therefore $$O(n)$$.\n\n* Space complexity: $$O(n)$$\n\n    We use `sPrime` and `palindromeRadii`, both of length $$O(n)$$.\n    \n<br/>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestPalindrome(self, s: str) -> str:\n    if not s:\n      return ''\n\n    indices = [0, 0]\n\n    # Returns [start, end] indices of the longest palindrome extended from s[i..j]\n    def extend(s: str, i: int, j: int) -> Tuple[int, int]:\n      while i >= 0 and j < len(s):\n        if s[i] != s[j]:\n          break\n        i -= 1\n        j += 1\n      return i + 1, j - 1\n\n    for i in range(len(s)):\n      l1, r1 = extend(s, i, i)\n      if r1 - l1 > indices[1] - indices[0]:\n        indices = l1, r1\n      if i + 1 < len(s) and s[i] == s[i + 1]:\n        l2, r2 = extend(s, i, i + 1)\n        if r2 - l2 > indices[1] - indices[0]:\n          indices = l2, r2\n\n    return s[indices[0]:indices[1] + 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String longestPalindrome(String s) {\n    if (s.isEmpty())\n      return \"\";\n\n    // [start, end] indices of the longest palindrome in s\n    int[] indices = {0, 0};\n\n    for (int i = 0; i < s.length(); ++i) {\n      int[] indices1 = extend(s, i, i);\n      if (indices1[1] - indices1[0] > indices[1] - indices[0])\n        indices = indices1;\n      if (i + 1 < s.length() && s.charAt(i) == s.charAt(i + 1)) {\n        int[] indices2 = extend(s, i, i + 1);\n        if (indices2[1] - indices2[0] > indices[1] - indices[0])\n          indices = indices2;\n      }\n    }\n\n    return s.substring(indices[0], indices[1] + 1);\n  }\n\n  // Returns [start, end] indices of the longest palindrome extended from s[i..j]\n  private int[] extend(final String s, int i, int j) {\n    for (; i >= 0 && j < s.length(); --i, ++j)\n      if (s.charAt(i) != s.charAt(j))\n        break;\n    return new int[] {i + 1, j - 1};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string longestPalindrome(string s) {\n    if (s.empty())\n      return \"\";\n\n    // [start, end] indices of the longest palindrome in s\n    pair<int, int> indices{0, 0};\n\n    for (int i = 0; i < s.length(); ++i) {\n      const auto [l1, r1] = extend(s, i, i);\n      if (r1 - l1 > indices.second - indices.first)\n        indices = {l1, r1};\n      if (i + 1 < s.length() && s[i] == s[i + 1]) {\n        const auto [l2, r2] = extend(s, i, i + 1);\n        if (r2 - l2 > indices.second - indices.first)\n          indices = {l2, r2};\n      }\n    }\n\n    return s.substr(indices.first, indices.second - indices.first + 1);\n  }\n\n private:\n  // Returns [start, end] indices of the longest palindrome extended from\n  // s[i..j]\n  pair<int, int> extend(const string& s, int i, int j) {\n    for (; i >= 0 && j < s.length(); --i, ++j)\n      if (s[i] != s[j])\n        break;\n    return {i + 1, j - 1};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/5.html",
    "category": "Algorithms",
    "acceptance_rate": 35.66839764005258,
    "topics": [
      "Two Pointers",
      "String",
      "Dynamic Programming"
    ],
    "hints": [
      "How can we reuse a previously computed palindrome to compute a larger palindrome?",
      "If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?",
      "Complexity based hint:</br>\r\nIf we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation."
    ],
    "likes": 30717,
    "dislikes": 1894,
    "similar_questions": "[{\"title\": \"Shortest Palindrome\", \"titleSlug\": \"shortest-palindrome\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Palindrome Permutation\", \"titleSlug\": \"palindrome-permutation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Palindrome Pairs\", \"titleSlug\": \"palindrome-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Palindromic Subsequence\", \"titleSlug\": \"longest-palindromic-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindromic Substrings\", \"titleSlug\": \"palindromic-substrings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Non-overlapping Palindrome Substrings\", \"titleSlug\": \"maximum-number-of-non-overlapping-palindrome-substrings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.8M\", \"totalSubmission\": \"10.7M\", \"totalAcceptedRaw\": 3815325, \"totalSubmissionRaw\": 10696655, \"acRate\": \"35.7%\"}",
    "title_pt": "Maior Substring Palindrômica",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne <em>a maior</em> <span data-keyword=\"palindromic-string\"><em>substring palindrômica</em></span> em <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;babad&quot;\n<strong>Saída:</strong> &quot;bab&quot;\n<strong>Explicação:</strong> &quot;aba&quot; também é uma resposta válida.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cbbd&quot;\n<strong>Saída:</strong> &quot;bb&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consiste apenas de dígitos e letras inglesas.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Como podemos reutilizar um palíndromo previamente computado para computar um palíndromo maior?",
      "- Dica 2: Se “aba” é um palíndromo, “xabax” também é um palíndromo? Da mesma forma, “xabay” também é um palíndromo?",
      "- Dica 3: Dica baseada em complexidade:</br>\r\nSe usarmos força bruta e verificarmos se, para toda posição inicial e final, uma substring é um palíndromo, temos O(n^2) pares início-fim e O(n) verificações de palíndromo. Podemos reduzir o tempo das verificações de palíndromo para O(1) reutilizando algum cálculo anterior."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "6",
    "paidOnly": false,
    "title": "Zigzag Conversion",
    "titleSlug": "zigzag-conversion",
    "url": "https://leetcode.com/problems/zigzag-conversion",
    "description_url": "https://leetcode.com/problems/zigzag-conversion/description/",
    "description": "<p>The string <code>&quot;PAYPALISHIRING&quot;</code> is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)</p>\n\n<pre>\nP   A   H   N\nA P L S I I G\nY   I   R\n</pre>\n\n<p>And then read line by line: <code>&quot;PAHNAPLSIIGYIR&quot;</code></p>\n\n<p>Write the code that will take a string and make this conversion given a number of rows:</p>\n\n<pre>\nstring convert(string s, int numRows);\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3\n<strong>Output:</strong> &quot;PAHNAPLSIIGYIR&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4\n<strong>Output:</strong> &quot;PINALSIGYAHRPI&quot;\n<strong>Explanation:</strong>\nP     I    N\nA   L S  I G\nY A   H R\nP     I\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;A&quot;, numRows = 1\n<strong>Output:</strong> &quot;A&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consists of English letters (lower-case and upper-case), <code>&#39;,&#39;</code> and <code>&#39;.&#39;</code>.</li>\n\t<li><code>1 &lt;= numRows &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/zigzag-conversion/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def convert(self, s: str, numRows: int) -> str:\n    rows = [''] * numRows\n    k = 0\n    direction = (numRows == 1) - 1\n\n    for c in s:\n      rows[k] += c\n      if k == 0 or k == numRows - 1:\n        direction *= -1\n      k += direction\n\n    return ''.join(rows)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String convert(String s, int numRows) {\n    StringBuilder sb = new StringBuilder();\n    List<Character>[] rows = new List[numRows];\n    int k = 0;\n    int direction = numRows == 1 ? 0 : -1;\n\n    for (int i = 0; i < numRows; ++i)\n      rows[i] = new ArrayList<>();\n\n    for (final char c : s.toCharArray()) {\n      rows[k].add(c);\n      if (k == 0 || k == numRows - 1)\n        direction *= -1;\n      k += direction;\n    }\n\n    for (List<Character> row : rows)\n      for (final char c : row)\n        sb.append(c);\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string convert(string s, int numRows) {\n    string ans;\n    vector<vector<char>> rows(numRows);\n    int k = 0;\n    int direction = (numRows == 1) - 1;\n\n    for (const char c : s) {\n      rows[k].push_back(c);\n      if (k == 0 || k == numRows - 1)\n        direction *= -1;\n      k += direction;\n    }\n\n    for (const vector<char>& row : rows)\n      for (const char c : row)\n        ans += c;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/6.html",
    "category": "Algorithms",
    "acceptance_rate": 51.3572214373564,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 8453,
    "dislikes": 15336,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"3.4M\", \"totalAcceptedRaw\": 1741281, \"totalSubmissionRaw\": 3390529, \"acRate\": \"51.4%\"}",
    "title_pt": "Conversão em Zigzag",
    "description_pt": "<p>A string <code>&quot;PAYPALISHIRING&quot;</code> é escrita em um padrão em zigzag em um determinado número de linhas, assim: (talvez você queira exibir este padrão em uma fonte de largura fixa para melhor legibilidade)</p>\n\n<pre>\nP   A   H   N\nA P L S I I G\nY   I   R\n</pre>\n\n<p>E então lida linha por linha: <code>&quot;PAHNAPLSIIGYIR&quot;</code></p>\n\n<p>Escreva o código que receberá uma string e fará esta conversão dado um número de linhas:</p>\n\n<pre>\nstring convert(string s, int numRows);\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 3\n<strong>Saída:</strong> &quot;PAHNAPLSIIGYIR&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;PAYPALISHIRING&quot;, numRows = 4\n<strong>Saída:</strong> &quot;PINALSIGYAHRPI&quot;\n<strong>Explicação:</strong>\nP     I    N\nA   L S  I G\nY A   H R\nP     I\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;A&quot;, numRows = 1\n<strong>Saída:</strong> &quot;A&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consiste em letras ইং?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "7",
    "paidOnly": false,
    "title": "Reverse Integer",
    "titleSlug": "reverse-integer",
    "url": "https://leetcode.com/problems/reverse-integer",
    "description_url": "https://leetcode.com/problems/reverse-integer/description/",
    "description": "<p>Given a signed 32-bit integer <code>x</code>, return <code>x</code><em> with its digits reversed</em>. If reversing <code>x</code> causes the value to go outside the signed 32-bit integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then return <code>0</code>.</p>\n\n<p><strong>Assume the environment does not allow you to store 64-bit integers (signed or unsigned).</strong></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 123\n<strong>Output:</strong> 321\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = -123\n<strong>Output:</strong> -321\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 120\n<strong>Output:</strong> 21\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-integer/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Pop and Push Digits & Check before Overflow\n\n**Intuition**\n\nWe can build up the reverse integer one digit at a time.\nWhile doing so, we can check beforehand whether or not appending another digit would cause overflow.\n\n**Algorithm**\n\nReversing an integer can be done similarly to reversing a string.\n\nWe want to repeatedly \"pop\" the last digit off of $$x$$ and \"push\" it to the back of the $$\\text{rev}$$. In the end, $$\\text{rev}$$ will be the reverse of the $$x$$.\n\nTo \"pop\" and \"push\" digits without the help of some auxiliary stack/array, we can use math.\n\n```cpp\n// pop operation:\npop = x % 10;\nx /= 10;\n\n// push operation:\ntemp = rev * 10 + pop;\nrev = temp;\n```\n\nHowever, this approach is dangerous, because the statement $$\\text{temp} = \\text{rev} \\cdot 10 + \\text{pop}$$ can cause overflow.\n\nLuckily, it is easy to check beforehand whether or this statement would cause an overflow.\n\nTo explain, lets assume that $$\\text{rev}$$ is positive.\n\n1. If $$temp = \\text{rev} \\cdot 10 + \\text{pop}$$ causes overflow, then it must be that $$\\text{rev} \\geq \\frac{INTMAX}{10}$$\n2. If $$\\text{rev} > \\frac{INTMAX}{10}$$, then $$temp = \\text{rev} \\cdot 10 + \\text{pop}$$ is guaranteed to overflow.\n3. If $$\\text{rev} == \\frac{INTMAX}{10}$$, then $$temp = \\text{rev} \\cdot 10 + \\text{pop}$$ will overflow if and only if $$\\text{pop} > 7$$\n\nSimilar logic can be applied when $$\\text{rev}$$ is negative.\n\n<iframe src=\"https://leetcode.com/playground/fm5j6WLP/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"fm5j6WLP\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(\\log(x))$$. There are roughly $$\\log_{10}(x)$$ digits in $$x$$.\n* Space Complexity: $$O(1)$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverse(self, x: int) -> int:\n    ans = 0\n    sign = -1 if x < 0 else 1\n    x *= sign\n\n    while x:\n      ans = ans * 10 + x % 10\n      x //= 10\n\n    return 0 if ans < -2**31 or ans > 2**31 - 1 else sign * ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int reverse(int x) {\n    long ans = 0;\n\n    while (x != 0) {\n      ans = ans * 10 + x % 10;\n      x /= 10;\n    }\n\n    return (ans < Integer.MIN_VALUE || ans > Integer.MAX_VALUE) ? 0 : (int) ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int reverse(int x) {\n    long ans = 0;\n\n    while (x) {\n      ans = ans * 10 + x % 10;\n      x /= 10;\n    }\n\n    return (ans < INT_MIN || ans > INT_MAX) ? 0 : ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/7.html",
    "category": "Algorithms",
    "acceptance_rate": 30.161576622980913,
    "topics": [
      "Math"
    ],
    "hints": [],
    "likes": 14072,
    "dislikes": 13760,
    "similar_questions": "[{\"title\": \"String to Integer (atoi)\", \"titleSlug\": \"string-to-integer-atoi\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Reverse Bits\", \"titleSlug\": \"reverse-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"A Number After a Double Reversal\", \"titleSlug\": \"a-number-after-a-double-reversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Number of Distinct Integers After Reverse Operations\", \"titleSlug\": \"count-number-of-distinct-integers-after-reverse-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4M\", \"totalSubmission\": \"13.3M\", \"totalAcceptedRaw\": 4024847, \"totalSubmissionRaw\": 13344291, \"acRate\": \"30.2%\"}",
    "title_pt": "Inverter Inteiro",
    "description_pt": "<p>Dado um inteiro com sinal de 32 bits <code>x</code>, retorne <code>x</code><em> com seus dígitos invertidos</em>. Se inverter <code>x</code> fizer com que o valor saia do intervalo de inteiro com sinal de 32 bits <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, então retorne <code>0</code>.</p>\n\n<p><strong>Assuma que o ambiente não permite armazenar inteiros de 64 bits (com sinal ou sem sinal).</strong></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 123\n<strong>Saída:</strong> 321\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = -123\n<strong>Saída:</strong> -321\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 120\n<strong>Saída:</strong> 21\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "8",
    "paidOnly": false,
    "title": "String to Integer (atoi)",
    "titleSlug": "string-to-integer-atoi",
    "url": "https://leetcode.com/problems/string-to-integer-atoi",
    "description_url": "https://leetcode.com/problems/string-to-integer-atoi/description/",
    "description": "<p>Implement the <code>myAtoi(string s)</code> function, which converts a string to a 32-bit signed integer.</p>\n\n<p>The algorithm for <code>myAtoi(string s)</code> is as follows:</p>\n\n<ol>\n\t<li><strong>Whitespace</strong>: Ignore any leading whitespace (<code>&quot; &quot;</code>).</li>\n\t<li><strong>Signedness</strong>: Determine the sign by checking if the next character is <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code>, assuming positivity if neither present.</li>\n\t<li><strong>Conversion</strong>: Read the integer by skipping leading zeros&nbsp;until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.</li>\n\t<li><strong>Rounding</strong>: If the integer is out of the 32-bit signed integer range <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, then round the integer to remain in the range. Specifically, integers less than <code>-2<sup>31</sup></code> should be rounded to <code>-2<sup>31</sup></code>, and integers greater than <code>2<sup>31</sup> - 1</code> should be rounded to <code>2<sup>31</sup> - 1</code>.</li>\n</ol>\n\n<p>Return the integer as the final result.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;42&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">42</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\nThe underlined characters are what is read in and the caret is the current reader position.\nStep 1: &quot;42&quot; (no characters read because there is no leading whitespace)\n         ^\nStep 2: &quot;42&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;)\n         ^\nStep 3: &quot;<u>42</u>&quot; (&quot;42&quot; is read in)\n           ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot; -042&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">-42</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\nStep 1: &quot;<u>   </u>-042&quot; (leading whitespace is read and ignored)\n            ^\nStep 2: &quot;   <u>-</u>042&quot; (&#39;-&#39; is read, so the result should be negative)\n             ^\nStep 3: &quot;   -<u>042</u>&quot; (&quot;042&quot; is read in, leading zeros ignored in the result)\n               ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;1337c0d3&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">1337</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\nStep 1: &quot;1337c0d3&quot; (no characters read because there is no leading whitespace)\n         ^\nStep 2: &quot;1337c0d3&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;)\n         ^\nStep 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; is read in; reading stops because the next character is a non-digit)\n             ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;0-1&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\nStep 1: &quot;0-1&quot; (no characters read because there is no leading whitespace)\n         ^\nStep 2: &quot;0-1&quot; (no characters read because there is neither a &#39;-&#39; nor &#39;+&#39;)\n         ^\nStep 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; is read in; reading stops because the next character is a non-digit)\n          ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 5:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;words and 987&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Reading stops at the first non-digit character &#39;w&#39;.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 200</code></li>\n\t<li><code>s</code> consists of English letters (lower-case and upper-case), digits (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;.&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/string-to-integer-atoi/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def myAtoi(self, s: str) -> int:\n    s = s.strip()\n    if not s:\n      return 0\n\n    sign = -1 if s[0] == '-' else 1\n    if s[0] in {'-', '+'}:\n      s = s[1:]\n\n    num = 0\n\n    for c in s:\n      if not c.isdigit():\n        break\n      num = num * 10 + ord(c) - ord('0')\n      if sign * num <= -2**31:\n        return -2**31\n      if sign * num >= 2**31 - 1:\n        return 2**31 - 1\n\n    return sign * num",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int myAtoi(String s) {\n    s = s.strip();\n    if (s.isEmpty())\n      return 0;\n\n    final int sign = s.charAt(0) == '-' ? -1 : 1;\n    if (s.charAt(0) == '+' || s.charAt(0) == '-')\n      s = s.substring(1);\n\n    long num = 0;\n\n    for (final char c : s.toCharArray()) {\n      if (!Character.isDigit(c))\n        break;\n      num = num * 10 + (c - '0');\n      if (sign * num <= Integer.MIN_VALUE)\n        return Integer.MIN_VALUE;\n      if (sign * num >= Integer.MAX_VALUE)\n        return Integer.MAX_VALUE;\n    }\n\n    return sign * (int) num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int myAtoi(string s) {\n    trim(s);\n    if (s.empty())\n      return 0;\n\n    const int sign = s[0] == '-' ? -1 : 1;\n    if (s[0] == '+' || s[0] == '-')\n      s = s.substr(1);\n\n    long num = 0;\n\n    for (const char c : s) {\n      if (!isdigit(c))\n        break;\n      num = num * 10 + (c - '0');\n      if (sign * num < INT_MIN)\n        return INT_MIN;\n      if (sign * num > INT_MAX)\n        return INT_MAX;\n    }\n\n    return sign * num;\n  }\n\n private:\n  void trim(string& s) {\n    s.erase(0, s.find_first_not_of(' '));\n    s.erase(s.find_last_not_of(' ') + 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/8.html",
    "category": "Algorithms",
    "acceptance_rate": 19.04709548049706,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 5286,
    "dislikes": 14651,
    "similar_questions": "[{\"title\": \"Reverse Integer\", \"titleSlug\": \"reverse-integer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Valid Number\", \"titleSlug\": \"valid-number\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check if Numbers Are Ascending in a Sentence\", \"titleSlug\": \"check-if-numbers-are-ascending-in-a-sentence\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"10.3M\", \"totalAcceptedRaw\": 1952362, \"totalSubmissionRaw\": 10250193, \"acRate\": \"19.0%\"}",
    "title_pt": "String to Integer (atoi)",
    "description_pt": "<p>Implemente a função <code>myAtoi(string s)</code>, que converte uma string em um inteiro assinado de 32 bits.</p>\n\n<p>O algoritmo para <code>myAtoi(string s)</code> é o seguinte:</p>\n\n<ol>\n\t<li><strong>Espaço em branco</strong>: Ignore qualquer espaço em branco inicial (<code>&quot; &quot;</code>).</li>\n\t<li><strong>Sinal</strong>: Determine o sinal verificando se o próximo caractere é <code>&#39;-&#39;</code> ou <code>&#39;+&#39;</code>, assumindo positividade se nenhum estiver presente.</li>\n\t<li><strong>Conversão</strong>: Leia o inteiro pulando zeros à esquerda&nbsp;até que um caractere não numérico seja encontrado ou o fim da string seja alcançado. Se nenhum dígito foi lido, então o resultado é 0.</li>\n\t<li><strong>Arredondamento</strong>: Se o inteiro estiver fora do intervalo de inteiro assinado de 32 bits <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>, então arredonde o inteiro para permanecer no intervalo. Especificamente, inteiros menores que <code>-2<sup>31</sup></code> devem ser arredondados para <code>-2<sup>31</sup></code>, e inteiros maiores que <code>2<sup>31</sup> - 1</code> devem ser arredondados para <code>2<sup>31</sup> - 1</code>.</li>\n</ol>\n\n<p>Retorne o inteiro como resultado final.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;42&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">42</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\nOs caracteres sublinhados são o que é lido, e o acento circunflexo indica a posição atual do leitor.\nPasso 1: &quot;42&quot; (nenhum caractere lido porque não há espaço em branco inicial)\n         ^\nPasso 2: &quot;42&quot; (nenhum caractere lido porque não há nem um &#39;-&#39; nem um &#39;+&#39;)\n         ^\nPasso 3: &quot;<u>42</u>&quot; (&quot;42&quot; é lido)\n           ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot; -042&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">-42</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\nPasso 1: &quot;<u>   </u>-042&quot; (o espaço em branco inicial é lido e ignorado)\n            ^\nPasso 2: &quot;   <u>-</u>042&quot; (&#39;-&#39; é lido, então o resultado deve ser negativo)\n             ^\nPasso 3: &quot;   -<u>042</u>&quot; (&quot;042&quot; é lido, zeros à esquerda são ignorados no resultado)\n               ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;1337c0d3&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">1337</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\nPasso 1: &quot;1337c0d3&quot; (nenhum caractere lido porque não há espaço em branco inicial)\n         ^\nPasso 2: &quot;1337c0d3&quot; (nenhum caractere lido porque não há nem um &#39;-&#39; nem um &#39;+&#39;)\n         ^\nPasso 3: &quot;<u>1337</u>c0d3&quot; (&quot;1337&quot; é lido; a leitura para porque o próximo caractere não é um dígito)\n             ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;0-1&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\nPasso 1: &quot;0-1&quot; (nenhum caractere lido porque não há espaço em branco inicial)\n         ^\nPasso 2: &quot;0-1&quot; (nenhum caractere lido porque não há nem um &#39;-&#39; nem um &#39;+&#39;)\n         ^\nPasso 3: &quot;<u>0</u>-1&quot; (&quot;0&quot; é lido; a leitura para porque o próximo caractere não é um dígito)\n          ^\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 5:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;words and 987&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A leitura para no primeiro caractere não numérico &#39;w&#39;.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 200</code></li>\n\t<li><code>s</code> consiste em letras do alfabeto inglês (minúsculas e maiúsculas), dígitos (<code>0-9</code>), <code>&#39; &#39;</code>, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, e <code>&#39;.&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "9",
    "paidOnly": false,
    "title": "Palindrome Number",
    "titleSlug": "palindrome-number",
    "url": "https://leetcode.com/problems/palindrome-number",
    "description_url": "https://leetcode.com/problems/palindrome-number/description/",
    "description": "<p>Given an integer <code>x</code>, return <code>true</code><em> if </em><code>x</code><em> is a </em><span data-keyword=\"palindrome-integer\"><em><strong>palindrome</strong></em></span><em>, and </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 121\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 121 reads as 121 from left to right and from right to left.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = -121\n<strong>Output:</strong> false\n<strong>Explanation:</strong> From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 10\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Reads 01 from right to left. Therefore it is not a palindrome.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without converting the integer to a string?",
    "solution_url": "https://leetcode.com/problems/palindrome-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPalindrome(self, x: int) -> bool:\n    if x < 0:\n      return False\n\n    rev = 0\n    y = x\n\n    while y:\n      rev = rev * 10 + y % 10\n      y //= 10\n\n    return rev == x",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPalindrome(int x) {\n    if (x < 0)\n      return false;\n\n    long reversed = 0;\n    int y = x;\n\n    while (y > 0) {\n      reversed = reversed * 10 + y % 10;\n      y /= 10;\n    }\n\n    return reversed == x;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPalindrome(int x) {\n    if (x < 0)\n      return false;\n\n    long reversed = 0;\n    int y = x;\n\n    while (y) {\n      reversed = reversed * 10 + y % 10;\n      y /= 10;\n    }\n\n    return reversed == x;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/9.html",
    "category": "Algorithms",
    "acceptance_rate": 59.06786656567634,
    "topics": [
      "Math"
    ],
    "hints": [
      "Beware of overflow when you reverse the integer."
    ],
    "likes": 13944,
    "dislikes": 2813,
    "similar_questions": "[{\"title\": \"Palindrome Linked List\", \"titleSlug\": \"palindrome-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Palindrome With Fixed Length\", \"titleSlug\": \"find-palindrome-with-fixed-length\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Strictly Palindromic Number\", \"titleSlug\": \"strictly-palindromic-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"  Count Symmetric Integers\", \"titleSlug\": \"count-symmetric-integers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Count of Good Integers\", \"titleSlug\": \"find-the-count-of-good-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Largest Palindrome Divisible by K\", \"titleSlug\": \"find-the-largest-palindrome-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"6.3M\", \"totalSubmission\": \"10.7M\", \"totalAcceptedRaw\": 6301939, \"totalSubmissionRaw\": 10668989, \"acRate\": \"59.1%\"}",
    "title_pt": "Número Palíndromo",
    "description_pt": "<p>Dado um inteiro <code>x</code>, retorne <code>true</code><em> se </em><code>x</code><em> for um </em><span data-keyword=\"palindrome-integer\"><em><strong>palíndromo</strong></em></span><em>, e </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 121\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 121 é lido como 121 da esquerda para a direita e da direita para a esquerda.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = -121\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Da esquerda para a direita, lê-se -121. Da direita para a esquerda, torna-se 121-. Portanto, não é um palíndromo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 10\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Lê-se 01 da direita para a esquerda. Portanto, não é um palíndromo.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup>&nbsp;&lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você poderia resolvê-lo sem converter o inteiro para uma string?",
    "hints_pt": [
      "Dica 1: Cuidado com overflow quando você reverter o inteiro."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "10",
    "paidOnly": false,
    "title": "Regular Expression Matching",
    "titleSlug": "regular-expression-matching",
    "url": "https://leetcode.com/problems/regular-expression-matching",
    "description_url": "https://leetcode.com/problems/regular-expression-matching/description/",
    "description": "<p>Given an input string <code>s</code>&nbsp;and a pattern <code>p</code>, implement regular expression matching with support for <code>&#39;.&#39;</code> and <code>&#39;*&#39;</code> where:</p>\n\n<ul>\n\t<li><code>&#39;.&#39;</code> Matches any single character.​​​​</li>\n\t<li><code>&#39;*&#39;</code> Matches zero or more of the preceding element.</li>\n</ul>\n\n<p>The matching should cover the <strong>entire</strong> input string (not partial).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a*&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> &#39;*&#39; means zero or more of the preceding element, &#39;a&#39;. Therefore, by repeating &#39;a&#39; once, it becomes &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;ab&quot;, p = &quot;.*&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> &quot;.*&quot; means &quot;zero or more (*) of any character (.)&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li>\n\t<li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li>\n\t<li><code>s</code> contains only lowercase English letters.</li>\n\t<li><code>p</code> contains only lowercase English letters, <code>&#39;.&#39;</code>, and&nbsp;<code>&#39;*&#39;</code>.</li>\n\t<li>It is guaranteed for each appearance of the character <code>&#39;*&#39;</code>, there will be a previous valid character to match.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/regular-expression-matching/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Recursion\n\n**Intuition**\n\nIf there were no Kleene stars (the `*` wildcard character for regular expressions), the problem would be easier - we simply check from left to right if each character of the text matches the pattern.\n\nWhen a star is present, we may need to check many different suffixes of the text and see if they match the rest of the pattern.  A recursive solution is a straightforward way to represent this relationship.\n\n**Algorithm**\n\nWithout a Kleene star, our solution would look like this:\n\n\n<iframe src=\"https://leetcode.com/playground/WHCkKfaZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"140\" name=\"WHCkKfaZ\"></iframe>\n\nIf a star is present in the pattern, it will be in the second position $$\\text{pattern[1]}$$.  Then, we may ignore this part of the pattern, or delete a matching character in the text.  If we have a match on the remaining strings after any of these operations, then the initial inputs matched.\n\n<iframe src=\"https://leetcode.com/playground/QZA8SsdJ/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"QZA8SsdJ\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: Let $$T, P$$ be the lengths of the text and the pattern respectively.  In the worst case, a call to `match(text[i:], pattern[2j:])` will be made $$\\binom{i+j}{i}$$ times, and strings of the order $$O(T - i)$$ and $$O(P - 2*j)$$ will be made.  Thus, the complexity has the order $$\\sum_{i = 0}^T \\sum_{j = 0}^{P/2} \\binom{i+j}{i} O(T+P-i-2j)$$.  With some effort outside the scope of this article, we can show this is bounded by $$O\\big((T+P)2^{T + \\frac{P}{2}}\\big)$$.\n\n* Space Complexity:  For every call to `match`, we will create those strings as described above, possibly creating duplicates.  If memory is not freed, this will also take a total of $$O\\big((T+P)2^{T + \\frac{P}{2}}\\big)$$ space, even though there are only order $$O(T^2 + P^2)$$ unique suffixes of $$P$$ and  $$T$$ that are actually required.\n<br />\n<br />\n\n---\n\n### Approach 2: Dynamic Programming\n\n**Intuition**\n\nAs the problem has an **optimal substructure**, it is natural to cache intermediate results.  We ask the question $$\\text{dp(i, j)}$$: does $$\\text{text[i:]}$$ and $$\\text{pattern[j:]}$$ match?  We can describe our answer in terms of answers to questions involving smaller strings.\n\n**Algorithm**\n\nWe proceed with the same recursion as in [Approach 1](#approach-1-recursion), except because calls will only ever be made to `match(text[i:], pattern[j:])`, we use $$\\text{dp(i, j)}$$ to handle those calls instead, saving us expensive string-building operations and allowing us to cache the intermediate results.\n\n\n*Top-Down Variation*\n<iframe src=\"https://leetcode.com/playground/cXs5KPLc/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"cXs5KPLc\"></iframe>\n\n*Bottom-Up Variation*\n\n<iframe src=\"https://leetcode.com/playground/GnSNNEQb/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"GnSNNEQb\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: Let $$T, P$$ be the lengths of the text and the pattern respectively.  The work for every call to `dp(i, j)` for $$i=0, ... ,T$$; $$j=0, ... ,P$$ is done once, and it is $$O(1)$$ work.  Hence, the time complexity is $$O(TP)$$.\n\n* Space Complexity:  The only memory we use is the $$O(TP)$$ boolean entries in our cache.  Hence, the space complexity is $$O(TP)$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isMatch(self, s: str, p: str) -> bool:\n    m = len(s)\n    n = len(p)\n    # dp[i][j] := True if s[0..i) matches p[0..j)\n    dp = [[False] * (n + 1) for _ in range(m + 1)]\n    dp[0][0] = True\n\n    def isMatch(i: int, j: int) -> bool:\n      return j >= 0 and p[j] == '.' or s[i] == p[j]\n\n    for j, c in enumerate(p):\n      if c == '*' and dp[0][j - 1]:\n        dp[0][j + 1] = True\n\n    for i in range(m):\n      for j in range(n):\n        if p[j] == '*':\n          noRepeat = dp[i + 1][j - 1]  # Min index of '*' is 1\n          doRepeat = isMatch(i, j - 1) and dp[i][j + 1]\n          dp[i + 1][j + 1] = noRepeat or doRepeat\n        elif isMatch(i, j):\n          dp[i + 1][j + 1] = dp[i][j]\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isMatch(String s, String p) {\n    final int m = s.length();\n    final int n = p.length();\n    // dp[i][j] := true if s[0..i) matches p[0..j)\n    boolean[][] dp = new boolean[m + 1][n + 1];\n    dp[0][0] = true;\n\n    for (int j = 0; j < p.length(); ++j)\n      if (p.charAt(j) == '*' && dp[0][j - 1])\n        dp[0][j + 1] = true;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (p.charAt(j) == '*') {\n          final boolean noRepeat = dp[i + 1][j - 1]; // Min index of '*' is 1\n          final boolean doRepeat = isMatch(s, i, p, j - 1) && dp[i][j + 1];\n          dp[i + 1][j + 1] = noRepeat || doRepeat;\n        } else if (isMatch(s, i, p, j)) {\n          dp[i + 1][j + 1] = dp[i][j];\n        }\n\n    return dp[m][n];\n  }\n\n  private boolean isMatch(final String s, int i, final String p, int j) {\n    return j >= 0 && p.charAt(j) == '.' || s.charAt(i) == p.charAt(j);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isMatch(string s, string p) {\n    const int m = s.length();\n    const int n = p.length();\n    // dp[i][j] := true if s[0..i) matches p[0..j)\n    vector<vector<bool>> dp(m + 1, vector<bool>(n + 1));\n    dp[0][0] = true;\n\n    auto isMatch = [&](int i, int j) -> bool {\n      return j >= 0 && p[j] == '.' || s[i] == p[j];\n    };\n\n    for (int j = 0; j < p.length(); ++j)\n      if (p[j] == '*' && dp[0][j - 1])\n        dp[0][j + 1] = true;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (p[j] == '*') {\n          const bool noRepeat = dp[i + 1][j - 1];  // Min index of '*' is 1\n          const bool doRepeat = isMatch(i, j - 1) && dp[i][j + 1];\n          dp[i + 1][j + 1] = noRepeat || doRepeat;\n        } else if (isMatch(i, j)) {\n          dp[i + 1][j + 1] = dp[i][j];\n        }\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/10.html",
    "category": "Algorithms",
    "acceptance_rate": 29.193293330706215,
    "topics": [
      "String",
      "Dynamic Programming",
      "Recursion"
    ],
    "hints": [],
    "likes": 12672,
    "dislikes": 2282,
    "similar_questions": "[{\"title\": \"Wildcard Matching\", \"titleSlug\": \"wildcard-matching\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"3.9M\", \"totalAcceptedRaw\": 1149743, \"totalSubmissionRaw\": 3938389, \"acRate\": \"29.2%\"}",
    "title_pt": "Correspondência de Expressão Regular",
    "description_pt": "<p>Dada uma string de entrada <code>s</code>&nbsp;e um padrão <code>p</code>, implemente a correspondência de expressão regular com suporte a <code>&#39;.&#39;</code> e <code>&#39;*&#39;</code>, onde:</p>\n\n<ul>\n\t<li><code>&#39;.&#39;</code> corresponde a qualquer único caractere.​​​​</li>\n\t<li><code>&#39;*&#39;</code> corresponde a zero ou mais do elemento precedente.</li>\n</ul>\n\n<p>A correspondência deve cobrir a <strong>totalidade</strong> da string de entrada (não parcialmente).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aa&quot;, p = &quot;a&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> &quot;a&quot; não corresponde à string inteira &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aa&quot;, p = &quot;a*&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> &#39;*&#39; significa zero ou mais do elemento precedente, &#39;a&#39;. Portanto, ao repetir &#39;a&#39; uma vez, ele se torna &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;ab&quot;, p = &quot;.*&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> &quot;.*&quot; significa &quot;zero ou mais (*) de qualquer caractere (.)&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length&nbsp;&lt;= 20</code></li>\n\t<li><code>1 &lt;= p.length&nbsp;&lt;= 20</code></li>\n\t<li><code>s</code> contém apenas letras minúsculas do inglês.</li>\n\t<li><code>p</code> contém apenas letras minúsculas do inglês, <code>&#39;.&#39;</code>, e&nbsp;<code>&#39;*&#39;</code>.</li>\n\t<li>É garantido que, para cada ocorrência do caractere <code>&#39;*&#39;</code>, haverá um caractere válido anterior para corresponder.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "11",
    "paidOnly": false,
    "title": "Container With Most Water",
    "titleSlug": "container-with-most-water",
    "url": "https://leetcode.com/problems/container-with-most-water",
    "description_url": "https://leetcode.com/problems/container-with-most-water/description/",
    "description": "<p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p>\n\n<p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p>\n\n<p>Return <em>the maximum amount of water a container can store</em>.</p>\n\n<p><strong>Notice</strong> that you may not slant the container.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg\" style=\"width: 600px; height: 287px;\" />\n<pre>\n<strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7]\n<strong>Output:</strong> 49\n<strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> height = [1,1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/container-with-most-water/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxArea(self, height: List[int]) -> int:\n    ans = 0\n    l = 0\n    r = len(height) - 1\n\n    while l < r:\n      minHeight = min(height[l], height[r])\n      ans = max(ans, minHeight * (r - l))\n      if height[l] < height[r]:\n        l += 1\n      else:\n        r -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxArea(int[] height) {\n    int ans = 0;\n    int l = 0;\n    int r = height.length - 1;\n\n    while (l < r) {\n      final int minHeight = Math.min(height[l], height[r]);\n      ans = Math.max(ans, minHeight * (r - l));\n      if (height[l] < height[r])\n        ++l;\n      else\n        --r;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxArea(vector<int>& height) {\n    int ans = 0;\n    int l = 0;\n    int r = height.size() - 1;\n\n    while (l < r) {\n      const int minHeight = min(height[l], height[r]);\n      ans = max(ans, minHeight * (r - l));\n      if (height[l] < height[r])\n        ++l;\n      else\n        --r;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/11.html",
    "category": "Algorithms",
    "acceptance_rate": 57.599907581720245,
    "topics": [
      "Array",
      "Two Pointers",
      "Greedy"
    ],
    "hints": [
      "If you simulate the problem, it will be O(n^2) which is not efficient.",
      "Try to use two-pointers. Set one pointer to the left and one to the right of the array. Always move the pointer that points to the lower line.",
      "How can you calculate the amount of water at each step?"
    ],
    "likes": 31145,
    "dislikes": 1991,
    "similar_questions": "[{\"title\": \"Trapping Rain Water\", \"titleSlug\": \"trapping-rain-water\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Tastiness of Candy Basket\", \"titleSlug\": \"maximum-tastiness-of-candy-basket\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber IV\", \"titleSlug\": \"house-robber-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4M\", \"totalSubmission\": \"7M\", \"totalAcceptedRaw\": 4023702, \"totalSubmissionRaw\": 6985608, \"acRate\": \"57.6%\"}",
    "title_pt": "Recipiente com Maior Quantidade de Água",
    "description_pt": "<p>Você recebe um array inteiro <code>height</code> de comprimento <code>n</code>. Há <code>n</code> linhas verticais desenhadas de modo que os dois extremos da <code>i<sup>ésima</sup></code> linha sejam <code>(i, 0)</code> e <code>(i, height[i])</code>.</p>\n\n<p>Encontre duas linhas que, juntamente com o eixo x, formem um recipiente, de modo que o recipiente contenha a maior quantidade de água.</p>\n\n<p>Retorne <em>a quantidade máxima de água que um recipiente pode armazenar</em>.</p>\n\n<p><strong>Observe</strong> que você não pode inclinar o recipiente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg\" style=\"width: 600px; height: 287px;\" />\n<pre>\n<strong>Entrada:</strong> height = [1,8,6,2,5,4,8,3,7]\n<strong>Saída:</strong> 49\n<strong>Explicação:</strong> As linhas verticais acima são representadas pelo array [1,8,6,2,5,4,8,3,7]. Neste caso, a área máxima de água (seção azul) que o recipiente pode conter é 49.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> height = [1,1]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Se você simular o problema, isso será <code>O(n^2)</code>, o que não é eficiente.",
      "Dica 2: Tente usar dois ponteiros. Defina um ponteiro à esquerda e um à direita do array. Sempre mova o ponteiro que aponta para a linha mais baixa.",
      "Dica 3: Como você pode calcular a quantidade de água em cada passo?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "12",
    "paidOnly": false,
    "title": "Integer to Roman",
    "titleSlug": "integer-to-roman",
    "url": "https://leetcode.com/problems/integer-to-roman",
    "description_url": "https://leetcode.com/problems/integer-to-roman/description/",
    "description": "<p>Seven different symbols represent Roman numerals with the following values:</p>\n\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<th>Symbol</th>\n\t\t\t<th>Value</th>\n\t\t</tr>\n\t</thead>\n\t<tbody>\n\t\t<tr>\n\t\t\t<td>I</td>\n\t\t\t<td>1</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>V</td>\n\t\t\t<td>5</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>X</td>\n\t\t\t<td>10</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>L</td>\n\t\t\t<td>50</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>C</td>\n\t\t\t<td>100</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>D</td>\n\t\t\t<td>500</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>M</td>\n\t\t\t<td>1000</td>\n\t\t</tr>\n\t</tbody>\n</table>\n\n<p>Roman numerals are formed by appending&nbsp;the conversions of&nbsp;decimal place values&nbsp;from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:</p>\n\n<ul>\n\t<li>If the value does not start with 4 or&nbsp;9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.</li>\n\t<li>If the value starts with 4 or 9 use the&nbsp;<strong>subtractive form</strong>&nbsp;representing&nbsp;one symbol subtracted from the following symbol, for example,&nbsp;4 is 1 (<code>I</code>) less than 5 (<code>V</code>): <code>IV</code>&nbsp;and 9 is 1 (<code>I</code>) less than 10 (<code>X</code>): <code>IX</code>.&nbsp;Only the following subtractive forms are used: 4 (<code>IV</code>), 9 (<code>IX</code>),&nbsp;40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) and 900 (<code>CM</code>).</li>\n\t<li>Only powers of 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5&nbsp;(<code>V</code>), 50 (<code>L</code>), or 500 (<code>D</code>) multiple times. If you need to append a symbol&nbsp;4 times&nbsp;use the <strong>subtractive form</strong>.</li>\n</ul>\n\n<p>Given an integer, convert it to a Roman numeral.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">num = 3749</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;MMMDCCXLIX&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\n3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n  40 = XL as 10 (X) less of 50 (L)\n   9 = IX as 1 (I) less of 10 (X)\nNote: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">num = 58</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;LVIII&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\n50 = L\n 8 = VIII\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">num = 1994</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;MCMXCIV&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\n1000 = M\n 900 = CM\n  90 = XC\n   4 = IV\n</pre>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 3999</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/integer-to-roman/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def intToRoman(self, num: int) -> str:\n    valueSymbols = [(1000, 'M'), (900, 'CM'),\n                    (500, 'D'), (400, 'CD'),\n                    (100, 'C'), (90, 'XC'),\n                    (50, 'L'), (40, 'XL'),\n                    (10, 'X'), (9, 'IX'),\n                    (5, 'V'), (4, 'IV'),\n                    (1, 'I')]\n    ans = []\n\n    for value, symbol in valueSymbols:\n      if num == 0:\n        break\n      count, num = divmod(num, value)\n      ans.append(symbol * count)\n\n    return ''.join(ans)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String intToRoman(int num) {\n    final int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n    final String[] symbols = {\"M\",  \"CM\", \"D\",  \"CD\", \"C\",  \"XC\", \"L\",\n                              \"XL\", \"X\",  \"IX\", \"V\",  \"IV\", \"I\"};\n    StringBuilder sb = new StringBuilder();\n\n    for (int i = 0; i < values.length; ++i) {\n      if (num == 0)\n        break;\n      while (num >= values[i]) {\n        num -= values[i];\n        sb.append(symbols[i]);\n      }\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string intToRoman(int num) {\n    const vector<pair<int, string>> valueSymbols{\n        {1000, \"M\"}, {900, \"CM\"}, {500, \"D\"}, {400, \"CD\"}, {100, \"C\"},\n        {90, \"XC\"},  {50, \"L\"},   {40, \"XL\"}, {10, \"X\"},   {9, \"IX\"},\n        {5, \"V\"},    {4, \"IV\"},   {1, \"I\"}};\n    string ans;\n\n    for (const auto& [value, symbol] : valueSymbols) {\n      if (num == 0)\n        break;\n      while (num >= value) {\n        num -= value;\n        ans += symbol;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/12.html",
    "category": "Algorithms",
    "acceptance_rate": 68.36468065914671,
    "topics": [
      "Hash Table",
      "Math",
      "String"
    ],
    "hints": [],
    "likes": 7784,
    "dislikes": 5649,
    "similar_questions": "[{\"title\": \"Roman to Integer\", \"titleSlug\": \"roman-to-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Integer to English Words\", \"titleSlug\": \"integer-to-english-words\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1711345, \"totalSubmissionRaw\": 2503269, \"acRate\": \"68.4%\"}",
    "title_pt": "Inteiro para Romano",
    "description_pt": "<p>Sete símbolos diferentes representam algarismos romanos com os seguintes valores:</p>\n\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<th>Símbolo</th>\n\t\t\t<th>Valor</th>\n\t\t</tr>\n\t</thead>\n\t<tbody>\n\t\t<tr>\n\t\t\t<td>I</td>\n\t\t\t<td>1</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>V</td>\n\t\t\t<td>5</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>X</td>\n\t\t\t<td>10</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>L</td>\n\t\t\t<td>50</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>C</td>\n\t\t\t<td>100</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>D</td>\n\t\t\t<td>500</td>\n\t\t</tr>\n\t\t<tr>\n\t\t\t<td>M</td>\n\t\t\t<td>1000</td>\n\t\t</tr>\n\t</tbody>\n</table>\n\n<p>Os algarismos romanos são formados anexando as conversões dos valores posicionais decimais do maior para o menor. Converter um valor posicional decimal em um algarismo romano tem as seguintes regras:</p>\n\n<ul>\n\t<li>Se o valor não começar com 4 ou 9, selecione o símbolo de maior valor que pode ser subtraído da entrada, anexe esse símbolo ao resultado, subtraia seu valor e converta o restante para um algarismo romano.</li>\n\t<li>Se o valor começar com 4 ou 9, use a <strong>forma subtrativa</strong> representando um símbolo subtraído do símbolo seguinte; por exemplo, 4 é 1 (<code>I</code>) menor que 5 (<code>V</code>): <code>IV</code> e 9 é 1 (<code>I</code>) menor que 10 (<code>X</code>): <code>IX</code>. Apenas as seguintes formas subtrativas são usadas: 4 (<code>IV</code>), 9 (<code>IX</code>), 40 (<code>XL</code>), 90 (<code>XC</code>), 400 (<code>CD</code>) e 900 (<code>CM</code>).</li>\n\t<li>Apenas potências de 10 (<code>I</code>, <code>X</code>, <code>C</code>, <code>M</code>) podem ser anexadas consecutivamente no máximo 3 vezes para representar múltiplos de 10. Você não pode anexar 5&nbsp;(<code>V</code>), 50 (<code>L</code>) ou 500 (<code>D</code>) múltiplas vezes. Se precisar anexar um símbolo 4 vezes, use a <strong>forma subtrativa</strong>.</li>\n</ul>\n\n<p>Dado um inteiro, converta-o em um algarismo romano.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">num = 3749</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;MMMDCCXLIX&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\n3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n  40 = XL as 10 (X) less of 50 (L)\n   9 = IX as 1 (I) less of 10 (X)\nNota: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">num = 58</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;LVIII&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\n50 = L\n 8 = VIII\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">num = 1994</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;MCMXCIV&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\n1000 = M\n 900 = CM\n  90 = XC\n   4 = IV\n</pre>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 3999</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "13",
    "paidOnly": false,
    "title": "Roman to Integer",
    "titleSlug": "roman-to-integer",
    "url": "https://leetcode.com/problems/roman-to-integer",
    "description_url": "https://leetcode.com/problems/roman-to-integer/description/",
    "description": "<p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>\n\n<pre>\n<strong>Symbol</strong>       <strong>Value</strong>\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000</pre>\n\n<p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two ones added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>\n\n<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>\n\n<ul>\n\t<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li>\n\t<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li>\n\t<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>\n</ul>\n\n<p>Given a roman numeral, convert it to an integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;III&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> III = 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;LVIII&quot;\n<strong>Output:</strong> 58\n<strong>Explanation:</strong> L = 50, V= 5, III = 3.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;MCMXCIV&quot;\n<strong>Output:</strong> 1994\n<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 15</code></li>\n\t<li><code>s</code> contains only&nbsp;the characters <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li>\n\t<li>It is <strong>guaranteed</strong>&nbsp;that <code>s</code> is a valid roman numeral in the range <code>[1, 3999]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/roman-to-integer/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def romanToInt(self, s: str) -> int:\n    ans = 0\n    roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50,\n             'C': 100, 'D': 500, 'M': 1000}\n\n    for a, b in zip(s, s[1:]):\n      if roman[a] < roman[b]:\n        ans -= roman[a]\n      else:\n        ans += roman[a]\n\n    return ans + roman[s[-1]]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int romanToInt(String s) {\n    int ans = 0;\n    int[] roman = new int[128];\n\n    roman['I'] = 1;\n    roman['V'] = 5;\n    roman['X'] = 10;\n    roman['L'] = 50;\n    roman['C'] = 100;\n    roman['D'] = 500;\n    roman['M'] = 1000;\n\n    for (int i = 0; i + 1 < s.length(); ++i)\n      if (roman[s.charAt(i)] < roman[s.charAt(i + 1)])\n        ans -= roman[s.charAt(i)];\n      else\n        ans += roman[s.charAt(i)];\n\n    return ans + roman[s.charAt(s.length() - 1)];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int romanToInt(string s) {\n    int ans = 0;\n    vector<int> roman(128);\n\n    roman['I'] = 1;\n    roman['V'] = 5;\n    roman['X'] = 10;\n    roman['L'] = 50;\n    roman['C'] = 100;\n    roman['D'] = 500;\n    roman['M'] = 1000;\n\n    for (int i = 0; i + 1 < s.length(); ++i)\n      if (roman[s[i]] < roman[s[i + 1]])\n        ans -= roman[s[i]];\n      else\n        ans += roman[s[i]];\n\n    return ans + roman[s.back()];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/13.html",
    "category": "Algorithms",
    "acceptance_rate": 64.65175360650753,
    "topics": [
      "Hash Table",
      "Math",
      "String"
    ],
    "hints": [
      "Problem is simpler to solve by working the string from back to front and using a map."
    ],
    "likes": 15804,
    "dislikes": 1082,
    "similar_questions": "[{\"title\": \"Integer to Roman\", \"titleSlug\": \"integer-to-roman\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.8M\", \"totalSubmission\": \"7.4M\", \"totalAcceptedRaw\": 4770019, \"totalSubmissionRaw\": 7378023, \"acRate\": \"64.7%\"}",
    "title_pt": "Números Romanos para Inteiro",
    "description_pt": "<p>Os numerais romanos são representados por sete símbolos diferentes:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> e <code>M</code>.</p>\n\n<pre>\n<strong>Símbolo</strong>       <strong>Valor</strong>\nI             1\nV             5\nX             10\nL             50\nC             100\nD             500\nM             1000</pre>\n\n<p>Por exemplo,&nbsp;<code>2</code> é escrito como <code>II</code>&nbsp;em numeral romano, apenas dois uns somados. <code>12</code> é escrito como&nbsp;<code>XII</code>, que é simplesmente <code>X + II</code>. O número <code>27</code> é escrito como <code>XXVII</code>, que é <code>XX + V + II</code>.</p>\n\n<p>Numerais romanos geralmente são escritos do maior para o menor, da esquerda para a direita. No entanto, o numeral para quatro não é <code>IIII</code>. Em vez disso, o número quatro é escrito como <code>IV</code>. Como o um vem antes do cinco, nós o subtraímos, resultando em quatro. O mesmo princípio se aplica ao número nove, que é escrito como <code>IX</code>. Há seis casos em que a subtração é usada:</p>\n\n<ul>\n\t<li><code>I</code> pode ser colocado antes de <code>V</code> (5) e <code>X</code> (10) para formar 4 e 9.&nbsp;</li>\n\t<li><code>X</code> pode ser colocado antes de <code>L</code> (50) e <code>C</code> (100) para formar 40 e 90.&nbsp;</li>\n\t<li><code>C</code> pode ser colocado antes de <code>D</code> (500) e <code>M</code> (1000) para formar 400 e 900.</li>\n</ul>\n\n<p>Dado um numeral romano, converta-o para um inteiro.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;III&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> III = 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;LVIII&quot;\n<strong>Saída:</strong> 58\n<strong>Explicação:</strong> L = 50, V= 5, III = 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;MCMXCIV&quot;\n<strong>Saída:</strong> 1994\n<strong>Explicação:</strong> M = 1000, CM = 900, XC = 90 e IV = 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 15</code></li>\n\t<li><code>s</code> contém apenas&nbsp;os caracteres <code>(&#39;I&#39;, &#39;V&#39;, &#39;X&#39;, &#39;L&#39;, &#39;C&#39;, &#39;D&#39;, &#39;M&#39;)</code>.</li>\n\t<li>É <strong>garantido</strong>&nbsp;que <code>s</code> é um numeral romano válido no intervalo <code>[1, 3999]</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: O problema é mais simples de resolver percorrendo a string de trás para frente e usando um mapa."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "14",
    "paidOnly": false,
    "title": "Longest Common Prefix",
    "titleSlug": "longest-common-prefix",
    "url": "https://leetcode.com/problems/longest-common-prefix",
    "description_url": "https://leetcode.com/problems/longest-common-prefix/description/",
    "description": "<p>Write a function to find the longest common prefix string amongst an array of strings.</p>\n\n<p>If there is no common prefix, return an empty string <code>&quot;&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;]\n<strong>Output:</strong> &quot;fl&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;]\n<strong>Output:</strong> &quot;&quot;\n<strong>Explanation:</strong> There is no common prefix among the input strings.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 200</code></li>\n\t<li><code>0 &lt;= strs[i].length &lt;= 200</code></li>\n\t<li><code>strs[i]</code> consists of only lowercase English letters if it is non-empty.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-common-prefix/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n\n### Approach 1: Horizontal scanning\n\n#### Intuition\n\nFor a start we will describe a simple way of finding the longest prefix shared by a set of strings $$LCP(S_1  \\ldots  S_n)$$.\nWe will use the observation that :\n\n$$LCP(S_1 \\ldots S_n) = LCP(LCP(LCP(S_1, S_2),S_3),\\ldots S_n)$$\n\n#### Algorithm\n\n To employ this idea, the algorithm iterates through the strings $$[S_1  \\ldots  S_n]$$, finding at each iteration $$i$$ the longest common prefix of strings $$LCP(S_1  \\ldots  S_i)$$ When $$LCP(S_1  \\ldots  S_i)$$ is an empty string, the algorithm ends. Otherwise after $$n$$ iterations, the algorithm returns $$LCP(S_1  \\ldots  S_n)$$.\n\n ![Finding the longest common prefix](https://leetcode.com/media/original_images/14_basic.png){:width=\"539px\"}\n \n\n *Figure 1. Finding the longest common prefix (Horizontal scanning)*\n \n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Eyfryo9Z/shared\" frameBorder=\"0\" width=\"100%\" height=\"310\" name=\"Eyfryo9Z\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(S)$$ , where S is the sum of all characters in all strings.\n\n    In the worst case all $$n$$ strings are the same. The algorithm compares the string $$S1$$ with the other strings $$[S_2 \\ldots S_n]$$ There are $$S$$ character comparisons, where $$S$$ is the sum of all characters in the input array.\n\n* Space complexity : $$O(1)$$. We only used constant extra space.\n\n---\n\n### Approach 2: Vertical scanning\n\n#### Algorithm\n\nImagine a very short string is the common prefix at the end of the array. The above approach will still do $$S$$ comparisons. One way to optimize this case is to do vertical scanning. We compare characters from top to bottom on the same column (same character index of  the strings) before moving on to the next column.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/WSSYVp4m/shared\" frameBorder=\"0\" width=\"100%\" height=\"310\" name=\"WSSYVp4m\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(S)$$ , where S is the sum of all characters in all strings.\nIn the worst case there will be $$n$$ equal strings with length $$m$$ and the algorithm performs  $$S = m \\cdot n$$ character comparisons.\nEven though the worst case is still the same as [Approach 1](#approach-1-horizontal-scanning), in the best case there are at most $$n \\cdot minLen$$ comparisons where $$minLen$$ is the length of the shortest string in the array.\n* Space complexity : $$O(1)$$. We only used constant extra space.\n\n---\n\n### Approach 3: Divide and conquer\n\n#### Intuition\n\nThe idea of the algorithm comes from the associative property of LCP operation. We notice that :\n$$LCP(S_1 \\ldots S_n) = LCP(LCP(S_1 \\ldots S_k), LCP (S_{k+1} \\ldots S_n))$$\n, where $$LCP(S_1 \\ldots S_n)$$ is the longest common prefix in set of strings $$[S_1 \\ldots S_n]$$ , $$1 < k < n$$\n\n#### Algorithm\n\nTo apply the observation above, we use divide and conquer technique, where we split the $$LCP(S_i \\ldots S_j)$$ problem into two subproblems $$LCP(S_i \\ldots S_{mid})$$   and $$LCP(S_{mid+1} \\ldots S_j)$$, where `mid` is $$\\frac{i + j}{2}$$. We use their solutions `lcpLeft` and `lcpRight` to construct the solution of the main problem $$LCP(S_i \\ldots S_j)$$. To accomplish this we compare one by one the characters of `lcpLeft` and `lcpRight` till there is no character match. The found common prefix of `lcpLeft` and `lcpRight` is the solution of the  $$LCP(S_i \\ldots S_j)$$.\n\n![Finding the longest common prefix](https://leetcode.com/media/original_images/14_lcp_diviso_et_lmpera.png){:width=\"539px\"}\n\n\n*Figure 2. Finding the longest common prefix of strings using divide and conquer technique*\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/DR56kG9E/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"DR56kG9E\"></iframe>\n\n#### Complexity Analysis\n\nIn the worst case we have $$n$$ equal strings with length $$m$$\n\n* Time complexity : $$O(S)$$, where $$S$$ is the number of all characters in the array, $$S = m \\cdot n$$\n Time complexity is $$2 \\cdot T\\left ( \\frac{n}{2} \\right ) + O(m)$$. Therefore time complexity is $$O(S)$$.\n  In the best case this algorithm performs  $$O(minLen \\cdot n)$$ comparisons, where  $$minLen$$ is the shortest string of the array\n\n* Space complexity : $$O(m \\cdot \\log n)$$\n\n    There is a memory overhead since we store recursive calls in the execution stack. There are $$\\log n$$ recursive calls, each store need $$m$$ space to store the result,  so space complexity is $$O(m \\cdot \\log n)$$\n\n\n---\n\n### Approach 4: Binary search\n\n#### Intuition\n\nThe idea is to apply binary search method to find the string with maximum value `L`, which is common prefix of all of the strings. The algorithm searches space is the interval $$(0 \\ldots minLen)$$, where `minLen` is minimum string length and the maximum possible common prefix. Each time search space is divided in two equal parts, one of them is discarded, because it is sure that it doesn't contain the solution. There are two possible cases:\n* `S[1...mid]` is not a common string. This means that for each `j > i S[1..j]` is not a common string and we discard the second half of the  search space.\n* `S[1...mid]` is common string. This means that for each `i < j S[1..i]` is a common string and we discard the first half of the search space, because we try to find longer common prefix.\n\n![Finding the longest common prefix](https://leetcode.com/media/original_images/14_lcp_binary_search.png){:width=\"539px\"}\n\n\n*Figure 3. Finding the longest common prefix of strings using binary search technique*\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/M2tJuDXZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"M2tJuDXZ\"></iframe>\n\n#### Complexity Analysis\n\nIn the worst case we have $$n$$ equal strings with length $$m$$\n\n* Time complexity : $$O(S \\cdot \\log m)$$, where $$S$$ is the sum of all characters in all strings.\n\n    The algorithm makes $$\\log m$$ iterations, for each of them there are $$S = m \\cdot n$$ comparisons, which gives in total $$O(S \\cdot \\log m)$$ time complexity.\n\n* Space complexity : $$O(1)$$. We only used constant extra space.\n\n---\n\n### Further Thoughts / Follow up\n\nLet's take a look at a slightly different problem:\n\n> Given a set of keys S = $$[S_1,S_2 \\ldots S_n]$$, find the longest common prefix among a string `q` and S. This LCP query will be called frequently.\n\nWe could optimize LCP queries by storing the set of keys S in a Trie. For more information about Trie, please see this article [Implement a trie (Prefix trie)](https://leetcode.com/articles/implement-trie-prefix-tree/). In a Trie, each node descending from the root represents a common prefix of some keys. But we need to find the longest common prefix of a string `q` and all key strings. This means that we have to find the deepest path from the root, which satisfies the following conditions:\n* it is prefix of query string `q`\n* each node along the path must contain only one child element. Otherwise the found path will not be a common prefix among all strings.\n* the path doesn't comprise of nodes which are marked as end of key. Otherwise the path couldn't be a prefix a of key which is shorter than itself.\n\n#### Algorithm\n\nThe only question left, is how to find the deepest path in the Trie, that fulfills the requirements above. The most effective way is to build a trie from $$[S_1 \\ldots   S_n]$$ strings. Then find the prefix of query string `q` in the Trie. We traverse the Trie from the root, till it is impossible to continue the path in the Trie because one of the conditions above is not satisfied.\n\n![Finding the longest common prefix using Trie](../Figures/14/14_lcp_trie_fix.png)\n\n*Figure 4. Finding the longest common prefix of strings using Trie*\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/bcDyZ5WU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"bcDyZ5WU\"></iframe>\n\n#### Complexity Analysis\n\nIn the worst case query $$q$$ has length $$m$$ and it is equal to all $$n$$ strings of the array.\n\n* Time complexity : preprocessing $$O(S)$$, where $$S$$ is the number of all characters in the array, LCP query $$O(m)$$.\n\n    Trie build has $$O(S)$$ time complexity. To find the common prefix of $$q$$ in the Trie takes in the worst case $$O(m)$$.\n\n* Space complexity : $$O(S)$$. We only used additional  $$S$$ extra space for the Trie.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestCommonPrefix(self, strs: List[str]) -> str:\n    if not strs:\n      return ''\n\n    for i in range(len(strs[0])):\n      for j in range(1, len(strs)):\n        if i == len(strs[j]) or strs[j][i] != strs[0][i]:\n          return strs[0][:i]\n\n    return strs[0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String longestCommonPrefix(String[] strs) {\n    if (strs.length == 0)\n      return \"\";\n\n    for (int i = 0; i < strs[0].length(); ++i)\n      for (int j = 1; j < strs.length; ++j)\n        if (i == strs[j].length() || strs[j].charAt(i) != strs[0].charAt(i))\n          return strs[0].substring(0, i);\n\n    return strs[0];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string longestCommonPrefix(vector<string>& strs) {\n    if (strs.empty())\n      return \"\";\n\n    for (int i = 0; i < strs[0].length(); ++i)\n      for (int j = 1; j < strs.size(); ++j)\n        if (i == strs[j].length() || strs[j][i] != strs[0][i])\n          return strs[0].substr(0, i);\n\n    return strs[0];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/14.html",
    "category": "Algorithms",
    "acceptance_rate": 45.290395283800436,
    "topics": [
      "String",
      "Trie"
    ],
    "hints": [],
    "likes": 19118,
    "dislikes": 4720,
    "similar_questions": "[{\"title\": \"Smallest Missing Integer Greater Than Sequential Prefix Sum\", \"titleSlug\": \"smallest-missing-integer-greater-than-sequential-prefix-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Length of the Longest Common Prefix\", \"titleSlug\": \"find-the-length-of-the-longest-common-prefix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Common Suffix Queries\", \"titleSlug\": \"longest-common-suffix-queries\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Common Prefix After at Most One Removal\", \"titleSlug\": \"longest-common-prefix-after-at-most-one-removal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.5M\", \"totalSubmission\": \"9.9M\", \"totalAcceptedRaw\": 4470758, \"totalSubmissionRaw\": 9871320, \"acRate\": \"45.3%\"}",
    "title_pt": "Prefixo Comum Mais Longo",
    "description_pt": "<p>Escreva uma função para encontrar a string de prefixo comum mais longo entre um array de strings.</p>\n\n<p>Se não houver prefixo comum, retorne uma string vazia <code>&quot;&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> strs = [&quot;flower&quot;,&quot;flow&quot;,&quot;flight&quot;]\n<strong>Saída:</strong> &quot;fl&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> strs = [&quot;dog&quot;,&quot;racecar&quot;,&quot;car&quot;]\n<strong>Saída:</strong> &quot;&quot;\n<strong>Explicação:</strong> Não há prefixo comum entre as strings de entrada.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 200</code></li>\n\t<li><code>0 &lt;= strs[i].length &lt;= 200</code></li>\n\t<li><code>strs[i]</code> consiste apenas de letras minúsculas do alfabeto inglês, se não for vazia.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "15",
    "paidOnly": false,
    "title": "3Sum",
    "titleSlug": "3sum",
    "url": "https://leetcode.com/problems/3sum",
    "description_url": "https://leetcode.com/problems/3sum/description/",
    "description": "<p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p>\n\n<p>Notice that the solution set must not contain duplicate triplets.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,0,1,2,-1,-4]\n<strong>Output:</strong> [[-1,-1,2],[-1,0,1]]\n<strong>Explanation:</strong> \nnums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,1]\n<strong>Output:</strong> []\n<strong>Explanation:</strong> The only possible triplet does not sum up to 0.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,0,0]\n<strong>Output:</strong> [[0,0,0]]\n<strong>Explanation:</strong> The only possible triplet sums up to 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 3000</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/3sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def threeSum(self, nums: List[int]) -> List[List[int]]:\n    if len(nums) < 3:\n      return []\n\n    ans = []\n\n    nums.sort()\n\n    for i in range(len(nums) - 2):\n      if i > 0 and nums[i] == nums[i - 1]:\n        continue\n      l = i + 1\n      r = len(nums) - 1\n      while l < r:\n        summ = nums[i] + nums[l] + nums[r]\n        if summ == 0:\n          ans.append((nums[i], nums[l], nums[r]))\n          l += 1\n          r -= 1\n          while nums[l] == nums[l - 1] and l < r:\n            l += 1\n          while nums[r] == nums[r + 1] and l < r:\n            r -= 1\n        elif summ < 0:\n          l += 1\n        else:\n          r -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> threeSum(int[] nums) {\n    if (nums.length < 3)\n      return new ArrayList<>();\n\n    List<List<Integer>> ans = new ArrayList<>();\n\n    Arrays.sort(nums);\n\n    for (int i = 0; i + 2 < nums.length; ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      // Choose nums[i] as the first num in the triplet,\n      // and search the remaining nums in [i + 1, n - 1]\n      int l = i + 1;\n      int r = nums.length - 1;\n      while (l < r) {\n        final int sum = nums[i] + nums[l] + nums[r];\n        if (sum == 0) {\n          ans.add(Arrays.asList(nums[i], nums[l++], nums[r--]));\n          while (l < r && nums[l] == nums[l - 1])\n            ++l;\n          while (l < r && nums[r] == nums[r + 1])\n            --r;\n        } else if (sum < 0) {\n          ++l;\n        } else {\n          --r;\n        }\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> threeSum(vector<int>& nums) {\n    if (nums.size() < 3)\n      return {};\n\n    vector<vector<int>> ans;\n\n    sort(begin(nums), end(nums));\n\n    for (int i = 0; i + 2 < nums.size(); ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      // Choose nums[i] as the first num in the triplet,\n      // and search the remaining nums in [i + 1, n - 1]\n      int l = i + 1;\n      int r = nums.size() - 1;\n      while (l < r) {\n        const int sum = nums[i] + nums[l] + nums[r];\n        if (sum == 0) {\n          ans.push_back({nums[i], nums[l++], nums[r--]});\n          while (l < r && nums[l] == nums[l - 1])\n            ++l;\n          while (l < r && nums[r] == nums[r + 1])\n            --r;\n        } else if (sum < 0) {\n          ++l;\n        } else {\n          --r;\n        }\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/15.html",
    "category": "Algorithms",
    "acceptance_rate": 36.863672582982105,
    "topics": [
      "Array",
      "Two Pointers",
      "Sorting"
    ],
    "hints": [
      "So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand!",
      "For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y, which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster?",
      "The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?"
    ],
    "likes": 32835,
    "dislikes": 3092,
    "similar_questions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"3Sum Closest\", \"titleSlug\": \"3sum-closest\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"4Sum\", \"titleSlug\": \"4sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"3Sum Smaller\", \"titleSlug\": \"3sum-smaller\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Arithmetic Triplets\", \"titleSlug\": \"number-of-arithmetic-triplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Mountain Triplets I\", \"titleSlug\": \"minimum-sum-of-mountain-triplets-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Mountain Triplets II\", \"titleSlug\": \"minimum-sum-of-mountain-triplets-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.7M\", \"totalSubmission\": \"12.6M\", \"totalAcceptedRaw\": 4660539, \"totalSubmissionRaw\": 12642637, \"acRate\": \"36.9%\"}",
    "title_pt": "3Soma",
    "description_pt": "<p>Dado um array de inteiros nums, retorne todas as trincas <code>[nums[i], nums[j], nums[k]]</code> tais que <code>i != j</code>, <code>i != k</code>, e <code>j != k</code>, e <code>nums[i] + nums[j] + nums[k] == 0</code>.</p>\n\n<p>Observe que o conjunto de soluções não deve conter trincas duplicadas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,0,1,2,-1,-4]\n<strong>Saída:</strong> [[-1,-1,2],[-1,0,1]]\n<strong>Explicação:</strong> \nnums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nAs trincas distintas são [-1,0,1] e [-1,-1,2].\nObserve que a ordem da saída e a ordem das trincas não importa.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,1]\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> A única trinca possível não soma 0.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,0,0]\n<strong>Saída:</strong> [[0,0,0]]\n<strong>Explicação:</strong> A única trinca possível soma 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 3000</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Então, essencialmente precisamos encontrar três números x, y e z tais que eles somem o valor dado. Se fixarmos um dos números, digamos x, nos resta o problema de dois números à nossa frente!",
      "Dica 2: Para o problema de dois números, se fixarmos um dos números, digamos x, temos que percorrer todo o array para encontrar o próximo número y, que é value - x, onde value é o parâmetro de entrada. Podemos alterar nosso array de alguma forma para que essa busca se torne mais rápida?",
      "Dica 3: A segunda linha de raciocínio para dois números é: sem alterar o array, podemos usar espaço adicional de alguma forma? Talvez uma tabela hash para acelerar a busca?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "16",
    "paidOnly": false,
    "title": "3Sum Closest",
    "titleSlug": "3sum-closest",
    "url": "https://leetcode.com/problems/3sum-closest",
    "description_url": "https://leetcode.com/problems/3sum-closest/description/",
    "description": "<p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p>\n\n<p>Return <em>the sum of the three integers</em>.</p>\n\n<p>You may assume that each input would have exactly one solution.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,2,1,-4], target = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,0,0], target = 1\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The sum that is closest to the target is 0. (0 + 0 + 0 = 0).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 500</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/3sum-closest/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def threeSumClosest(self, nums: List[int], target: int) -> int:\n    ans = nums[0] + nums[1] + nums[2]\n\n    nums.sort()\n\n    for i in range(len(nums) - 2):\n      if i > 0 and nums[i] == nums[i - 1]:\n        continue\n      l = i + 1\n      r = len(nums) - 1\n      while l < r:\n        summ = nums[i] + nums[l] + nums[r]\n        if summ == target:\n          return summ\n        if abs(summ - target) < abs(ans - target):\n          ans = summ\n        if summ < target:\n          l += 1\n        else:\n          r -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int threeSumClosest(int[] nums, int target) {\n    int ans = nums[0] + nums[1] + nums[2];\n\n    Arrays.sort(nums);\n\n    for (int i = 0; i + 2 < nums.length; ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      // Choose nums[i] as the first num in the triplet,\n      // and search the remaining nums in [i + 1, n - 1]\n      int l = i + 1;\n      int r = nums.length - 1;\n      while (l < r) {\n        final int sum = nums[i] + nums[l] + nums[r];\n        if (sum == target)\n          return sum;\n        if (Math.abs(sum - target) < Math.abs(ans - target))\n          ans = sum;\n        if (sum < target)\n          ++l;\n        else\n          --r;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int threeSumClosest(vector<int>& nums, int target) {\n    int ans = nums[0] + nums[1] + nums[2];\n\n    sort(begin(nums), end(nums));\n\n    for (int i = 0; i + 2 < nums.size(); ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      // Choose nums[i] as the first num in the triplet,\n      // and search the remaining nums in [i + 1, n - 1]\n      int l = i + 1;\n      int r = nums.size() - 1;\n      while (l < r) {\n        const int sum = nums[i] + nums[l] + nums[r];\n        if (sum == target)\n          return sum;\n        if (abs(sum - target) < abs(ans - target))\n          ans = sum;\n        if (sum < target)\n          ++l;\n        else\n          --r;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/16.html",
    "category": "Algorithms",
    "acceptance_rate": 46.810822647260224,
    "topics": [
      "Array",
      "Two Pointers",
      "Sorting"
    ],
    "hints": [],
    "likes": 10959,
    "dislikes": 591,
    "similar_questions": "[{\"title\": \"3Sum\", \"titleSlug\": \"3sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"3Sum Smaller\", \"titleSlug\": \"3sum-smaller\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 1479299, \"totalSubmissionRaw\": 3160175, \"acRate\": \"46.8%\"}",
    "title_pt": "Soma de Três Números Mais Próxima",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> de comprimento <code>n</code> e um inteiro <code>target</code>, encontre três inteiros em <code>nums</code> tais que a soma seja a mais próxima possível de <code>target</code>.</p>\n\n<p>Retorne <em>a soma dos três inteiros</em>.</p>\n\n<p>Você pode assumir que cada entrada terá exatamente uma solução.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,2,1,-4], target = 1\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A soma mais próxima do alvo é 2. (-1 + 2 + 1 = 2).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,0,0], target = 1\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> A soma mais próxima do alvo é 0. (0 + 0 + 0 = 0).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;= 500</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "17",
    "paidOnly": false,
    "title": "Letter Combinations of a Phone Number",
    "titleSlug": "letter-combinations-of-a-phone-number",
    "url": "https://leetcode.com/problems/letter-combinations-of-a-phone-number",
    "description_url": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/",
    "description": "<p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p>\n\n<p>A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/15/1200px-telephone-keypad2svg.png\" style=\"width: 300px; height: 243px;\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = &quot;23&quot;\n<strong>Output:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = &quot;&quot;\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = &quot;2&quot;\n<strong>Output:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= digits.length &lt;= 4</code></li>\n\t<li><code>digits[i]</code> is a digit in the range <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def letterCombinations(self, digits: str) -> List[str]:\n    if not digits:\n      return []\n\n    digitToLetters = ['', '', 'abc', 'def', 'ghi',\n                      'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']\n    ans = []\n\n    def dfs(i: int, path: List[chr]) -> None:\n      if i == len(digits):\n        ans.append(''.join(path))\n        return\n\n      for letter in digitToLetters[ord(digits[i]) - ord('0')]:\n        path.append(letter)\n        dfs(i + 1, path)\n        path.pop()\n\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> letterCombinations(String digits) {\n    if (digits.isEmpty())\n      return new ArrayList<>();\n\n    List<String> ans = new ArrayList<>();\n\n    dfs(digits, 0, new StringBuilder(), ans);\n    return ans;\n  }\n\n  private static final String[] digitToLetters = {\"\",    \"\",    \"abc\",  \"def\", \"ghi\",\n                                                  \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n\n  private void dfs(String digits, int i, StringBuilder sb, List<String> ans) {\n    if (i == digits.length()) {\n      ans.add(sb.toString());\n      return;\n    }\n\n    for (final char c : digitToLetters[digits.charAt(i) - '0'].toCharArray()) {\n      sb.append(c);\n      dfs(digits, i + 1, sb, ans);\n      sb.deleteCharAt(sb.length() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> letterCombinations(string digits) {\n    if (digits.empty())\n      return {};\n\n    vector<string> ans;\n\n    dfs(digits, 0, \"\", ans);\n    return ans;\n  }\n\n private:\n  const vector<string> digitToLetters{\"\",    \"\",    \"abc\",  \"def\", \"ghi\",\n                                      \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n\n  void dfs(const string& digits, int i, string&& path, vector<string>& ans) {\n    if (i == digits.length()) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (const char letter : digitToLetters[digits[i] - '0']) {\n      path.push_back(letter);\n      dfs(digits, i + 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/17.html",
    "category": "Algorithms",
    "acceptance_rate": 63.624858177409315,
    "topics": [
      "Hash Table",
      "String",
      "Backtracking"
    ],
    "hints": [],
    "likes": 19661,
    "dislikes": 1066,
    "similar_questions": "[{\"title\": \"Generate Parentheses\", \"titleSlug\": \"generate-parentheses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Watch\", \"titleSlug\": \"binary-watch\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Number of Texts\", \"titleSlug\": \"count-number-of-texts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Pushes to Type Word I\", \"titleSlug\": \"minimum-number-of-pushes-to-type-word-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Pushes to Type Word II\", \"titleSlug\": \"minimum-number-of-pushes-to-type-word-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 2525182, \"totalSubmissionRaw\": 3968863, \"acRate\": \"63.6%\"}",
    "title_pt": "Combinações de Letras de um Número de Telefone",
    "description_pt": "<p>Dada uma string contendo dígitos de <code>2-9</code> inclusive, retorne todas as possíveis combinações de letras que o número poderia representar. Retorne a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>Um mapeamento de dígitos para letras (assim como nos botões de telefone) é fornecido abaixo. Observe que 1 não mapeia para nenhuma letra.</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/15/1200px-telephone-keypad2svg.png\" style=\"width: 300px; height: 243px;\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = &quot;23&quot;\n<strong>Saída:</strong> [&quot;ad&quot;,&quot;ae&quot;,&quot;af&quot;,&quot;bd&quot;,&quot;be&quot;,&quot;bf&quot;,&quot;cd&quot;,&quot;ce&quot;,&quot;cf&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = &quot;&quot;\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = &quot;2&quot;\n<strong>Saída:</strong> [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= digits.length &lt;= 4</code></li>\n\t<li><code>digits[i]</code> é um dígito no intervalo <code>[&#39;2&#39;, &#39;9&#39;]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "18",
    "paidOnly": false,
    "title": "4Sum",
    "titleSlug": "4sum",
    "url": "https://leetcode.com/problems/4sum",
    "description_url": "https://leetcode.com/problems/4sum/description/",
    "description": "<p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p>\n\n<ul>\n\t<li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li>\n\t<li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li>\n\t<li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li>\n</ul>\n\n<p>You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0\n<strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,2,2,2,2], target = 8\n<strong>Output:</strong> [[2,2,2,2]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/4sum/solutions/",
    "solution": "[TOC]\n\n## Solution\n\nThis problem is a follow-up of [3Sum](https://leetcode.com/articles/3sum/), so take a look at that problem first if you haven't. 4Sum and 3Sum are very similar; the difference is that we are looking for unique quadruplets instead of triplets.\n\nAs you see, 3Sum just wraps Two Sum in an outer loop. As it iterates through each value `v`, it finds all pairs whose sum is equal to `target - v` using one of these approaches:\n\n1. [Two Sum](https://leetcode.com/articles/two-sum/) uses a hash set to check for a matching value.\n2. [Two Sum II](https://leetcode.com/articles/two-sum-ii-input-array-is-sorted/) uses the two pointers pattern in a sorted array.\n\nFollowing a similar logic, we can implement 4Sum by wrapping 3Sum in another loop. But wait - there is a catch. If an interviewer asks you to solve 4Sum, they can follow-up with 5Sum, 6Sum, and so on. What they are really expecting at this point is a kSum solution. Therefore, we will focus on a generalized implementation here.\n\n---\n\n### Approach 1: Two Pointers\n\n**Intuition**\n\nThe two pointers pattern requires the array to be sorted, so we do that first.  Also, it's easier to deal with duplicates if the array is sorted: repeated values are next to each other and easy to skip.\n\nFor 3Sum, we enumerate each value in a single loop, and use the two pointers pattern for the rest of the array. For kSum, we will have `k - 2` nested loops to enumerate all combinations of `k - 2` values.\n\n!?!../Documents/18_4Sum.json:1200,440!?!\n\n**Algorithm**\n\nWe can implement `k - 2` loops using a recursion. We will pass the starting point and `k` as the parameters. When `k == 2`, we will call `twoSum`, terminating the recursion.\n\n1. For the main function:\n    - Sort the input array `nums`.\n    - Call `kSum` with `start = 0`, `k = 4`, and `target`, and return the result.\n\n2. For `kSum` function:\n    - At the start of the `kSum` function, we will check three conditions:\n      1. Have we run out of numbers to choose from?\n      2. Is the smallest number remaining greater than `target / k`? <br>If so, then any `k` numbers we choose will be too large.\n      3. Is the largest number remaining smaller than `target / k`? <br>If so, then any `k` numbers we choose will be too small.\n      - If any of these conditions is true, there is no need to continue as no combination of the remaining elements can sum to `target`.\n    - If `k` equals `2`, call `twoSum` and return the result.\n    - Iterate `i` through the array from `start`:\n        - If the current value is the same as the one before, skip it.\n        - Recursively call `kSum` with `start = i + 1`, `k = k - 1`, and `target - nums[i]`.\n        - For each returned `subset` of values:\n            - Include the current value `nums[i]` into `subset`.\n            - Add `subset` to the result `res`.\n    - Return the result `res`.\n\n3. For `twoSum` function:\n    - Set the low pointer `lo` to `start`, and high pointer `hi` to the last index.\n    - While low pointer is smaller than high:\n        - If the sum of `nums[lo]` and `nums[hi]` is less than `target`, increment `lo`.\n            - Also increment `lo` if the value is the same as for `lo - 1`.\n        - If the sum is greater than `target`, decrement `hi`.\n            - Also decrement `hi` if the value is the same as for `hi + 1`.\n        - Otherwise, we found a pair:\n            - Add it to the result `res`.\n            - Decrement `hi` and increment `lo`.\n    - Return the result `res`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/mQdTCUXD/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"mQdTCUXD\"></iframe>\n\n**Complexity Analysis**\n\n- Time Complexity: $$O(n^{k - 1})$$, or $$O(n^3)$$ for 4Sum. We have $$k - 2$$ loops, and `twoSum` is $$O(n)$$.\n\n    Note that for $$k > 2$$, sorting the array does not change the overall time complexity.\n\n- Space Complexity: $$O(n)$$. We need $$O(k)$$ space for the recursion. $$k$$ can be the same as $$n$$ in the worst case for the generalized algorithm.\n\n    Note that, for the purpose of complexity analysis, we ignore the memory required for the output.\n\n---\n\n### Approach 2: Hash Set\n    \n**Intuition**\n\nSince elements must sum up to the exact target value, we can also use the [Two Sum: One-pass Hash Table](https://leetcode.com/articles/two-sum/#approach-3-one-pass-hash-table) approach.\n\nIn [3Sum: Hash Set](https://leetcode.com/articles/3sum/#approach-2-hash-set), we solved the problem without sorting the array. To do that, we needed to sort values within triplets, and track them in a hash set. Doing the same for k values could be impractical.\n\nSo, for this approach, we will also sort the array and skip duplicates the same way as in the Two Pointers approach above. Thus, the code will only differ in the `twoSum` implementation.\n\n**Algorithm**\n\n`twoSum` implementation here is almost the same as in [Two Sum: One-pass Hash Table](https://leetcode.com/articles/two-sum/#approach-3-one-pass-hash-table). The only difference is the check to avoid duplicates. Since the array is sorted, we can just compare the found pair with the last one in the result `res`.\n    \n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/oAq3g56d/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"oAq3g56d\"></iframe>\n\n**Complexity Analysis**\n\n- Time Complexity: $$O(n^{k - 1})$$, or $$O(n^3)$$ for 4Sum. We have $$k - 2$$ loops iterating over $$n$$ elements, and `twoSum` is $$O(n)$$.\n\n    Note that for $$k > 2$$, sorting the array does not change the overall time complexity.\n\n- Space Complexity: $$O(n)$$ for the hash set. The space needed for the recursion will not exceed $$O(n)$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fourSum(self, nums: List[int], target: int):\n    ans = []\n\n    def nSum(l: int, r: int, target: int, n: int, path: List[int], ans: List[List[int]]) -> None:\n      if r - l + 1 < n or n < 2 or target < nums[l] * n or target > nums[r] * n:\n        return\n      if n == 2:\n        while l < r:\n          summ = nums[l] + nums[r]\n          if summ == target:\n            ans.append(path + [nums[l], nums[r]])\n            l += 1\n            while nums[l] == nums[l - 1] and l < r:\n              l += 1\n          elif summ < target:\n            l += 1\n          else:\n            r -= 1\n        return\n\n      for i in range(l, r + 1):\n        if i > l and nums[i] == nums[i - 1]:\n          continue\n\n        nSum(i + 1, r, target - nums[i], n - 1, path + [nums[i]], ans)\n\n    nums.sort()\n    nSum(0, len(nums) - 1, target, 4, [], ans)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> fourSum(int[] nums, int target) {\n    List<List<Integer>> ans = new ArrayList<>();\n\n    Arrays.sort(nums);\n    nSum(nums, 4, target, 0, nums.length - 1, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  // In [l, r], find n numbers add up to the target\n  private void nSum(int[] nums, long n, long target, int l, int r, List<Integer> path,\n                    List<List<Integer>> ans) {\n    if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)\n      return;\n    if (n == 2) {\n      // Very simliar to the sub procedure in 15. 3Sum\n      while (l < r) {\n        final int sum = nums[l] + nums[r];\n        if (sum == target) {\n          path.add(nums[l]);\n          path.add(nums[r]);\n          ans.add(new ArrayList<>(path));\n          path.remove(path.size() - 1);\n          path.remove(path.size() - 1);\n          ++l;\n          --r;\n          while (l < r && nums[l] == nums[l - 1])\n            ++l;\n          while (l < r && nums[r] == nums[r + 1])\n            --r;\n        } else if (sum < target) {\n          ++l;\n        } else {\n          --r;\n        }\n      }\n      return;\n    }\n\n    for (int i = l; i <= r; ++i) {\n      if (i > l && nums[i] == nums[i - 1])\n        continue;\n      path.add(nums[i]);\n      nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> fourSum(vector<int>& nums, int target) {\n    vector<vector<int>> ans;\n    vector<int> path;\n\n    sort(begin(nums), end(nums));\n    nSum(nums, 4, target, 0, nums.size() - 1, path, ans);\n    return ans;\n  }\n\n private:\n  // In [l, r], find n numbers add up to the target\n  void nSum(const vector<int>& nums, long n, long target, int l, int r,\n            vector<int>& path, vector<vector<int>>& ans) {\n    if (r - l + 1 < n || target < nums[l] * n || target > nums[r] * n)\n      return;\n    if (n == 2) {\n      // Very simliar to the sub procedure in 15. 3Sum\n      while (l < r) {\n        const int sum = nums[l] + nums[r];\n        if (sum == target) {\n          path.push_back(nums[l]);\n          path.push_back(nums[r]);\n          ans.push_back(path);\n          path.pop_back();\n          path.pop_back();\n          ++l;\n          --r;\n          while (l < r && nums[l] == nums[l - 1])\n            ++l;\n          while (l < r && nums[r] == nums[r + 1])\n            --r;\n        } else if (sum < target) {\n          ++l;\n        } else {\n          --r;\n        }\n      }\n      return;\n    }\n\n    for (int i = l; i <= r; ++i) {\n      if (i > l && nums[i] == nums[i - 1])\n        continue;\n      path.push_back(nums[i]);\n      nSum(nums, n - 1, target - nums[i], i + 1, r, path, ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/18.html",
    "category": "Algorithms",
    "acceptance_rate": 38.00106368250969,
    "topics": [
      "Array",
      "Two Pointers",
      "Sorting"
    ],
    "hints": [],
    "likes": 12010,
    "dislikes": 1460,
    "similar_questions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"3Sum\", \"titleSlug\": \"3sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"4Sum II\", \"titleSlug\": \"4sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Special Quadruplets\", \"titleSlug\": \"count-special-quadruplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1265413, \"totalSubmissionRaw\": 3329941, \"acRate\": \"38.0%\"}",
    "title_pt": "4Soma",
    "description_pt": "<p>Dado um array <code>nums</code> de <code>n</code> inteiros, retorne <em>um array de todos os quadruplicos <strong>únicos</strong></em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> tal que:</p>\n\n<ul>\n\t<li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li>\n\t<li><code>a</code>, <code>b</code>, <code>c</code> e <code>d</code> sejam <strong>distintos</strong>.</li>\n\t<li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li>\n</ul>\n\n<p>Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,0,-1,0,-2,2], target = 0\n<strong>Saída:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,2,2,2,2], target = 8\n<strong>Saída:</strong> [[2,2,2,2]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "19",
    "paidOnly": false,
    "title": "Remove Nth Node From End of List",
    "titleSlug": "remove-nth-node-from-end-of-list",
    "url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list",
    "description_url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/",
    "description": "<p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5], n = 2\n<strong>Output:</strong> [1,2,3,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [1], n = 1\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [1,2], n = 1\n<strong>Output:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>sz</code>.</li>\n\t<li><code>1 &lt;= sz &lt;= 30</code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>1 &lt;= n &lt;= sz</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you do this in one pass?</p>\n",
    "solution_url": "https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:\n    slow = head\n    fast = head\n\n    for _ in range(n):\n      fast = fast.next\n    if not fast:\n      return head.next\n\n    while fast.next:\n      slow = slow.next\n      fast = fast.next\n    slow.next = slow.next.next\n\n    return head",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode removeNthFromEnd(ListNode head, int n) {\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (n-- > 0)\n      fast = fast.next;\n    if (fast == null)\n      return head.next;\n\n    while (fast.next != null) {\n      slow = slow.next;\n      fast = fast.next;\n    }\n    slow.next = slow.next.next;\n\n    return head;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* removeNthFromEnd(ListNode* head, int n) {\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (n--)\n      fast = fast->next;\n    if (fast == nullptr)\n      return head->next;\n\n    while (fast->next) {\n      slow = slow->next;\n      fast = fast->next;\n    }\n    slow->next = slow->next->next;\n\n    return head;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/19.html",
    "category": "Algorithms",
    "acceptance_rate": 48.66713209504044,
    "topics": [
      "Linked List",
      "Two Pointers"
    ],
    "hints": [
      "Maintain two pointers and update one with a delay of n steps."
    ],
    "likes": 19922,
    "dislikes": 852,
    "similar_questions": "[{\"title\": \"Swapping Nodes in a Linked List\", \"titleSlug\": \"swapping-nodes-in-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete N Nodes After M Nodes of a Linked List\", \"titleSlug\": \"delete-n-nodes-after-m-nodes-of-a-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Delete the Middle Node of a Linked List\", \"titleSlug\": \"delete-the-middle-node-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.4M\", \"totalSubmission\": \"7.1M\", \"totalAcceptedRaw\": 3431099, \"totalSubmissionRaw\": 7050134, \"acRate\": \"48.7%\"}",
    "title_pt": "Remover o N-ésimo Nó a Partir do Fim da Lista",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada, remova o <code>n<sup>th</sup></code> nó a partir do fim da lista e retorne seu head.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5], n = 2\n<strong>Saída:</strong> [1,2,3,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [1], n = 1\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [1,2], n = 1\n<strong>Saída:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista é <code>sz</code>.</li>\n\t<li><code>1 &lt;= sz &lt;= 30</code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>1 &lt;= n &lt;= sz</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você poderia fazer isso em uma única passada?</p>",
    "hints_pt": [
      "Dica 1: Mantenha dois ponteiros e atualize um deles com um atraso de n passos."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "20",
    "paidOnly": false,
    "title": "Valid Parentheses",
    "titleSlug": "valid-parentheses",
    "url": "https://leetcode.com/problems/valid-parentheses",
    "description_url": "https://leetcode.com/problems/valid-parentheses/description/",
    "description": "<p>Given a string <code>s</code> containing just the characters <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> and <code>&#39;]&#39;</code>, determine if the input string is valid.</p>\n\n<p>An input string is valid if:</p>\n\n<ol>\n\t<li>Open brackets must be closed by the same type of brackets.</li>\n\t<li>Open brackets must be closed in the correct order.</li>\n\t<li>Every close bracket has a corresponding open bracket of the same type.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;()&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;()[]{}&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;(]&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;([])&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of parentheses only <code>&#39;()[]{}&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-parentheses/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isValid(self, s: str) -> bool:\n    stack = []\n\n    for c in s:\n      if c == '(':\n        stack.append(')')\n      elif c == '{':\n        stack.append('}')\n      elif c == '[':\n        stack.append(']')\n      elif not stack or stack.pop() != c:\n        return False\n\n    return not stack",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isValid(String s) {\n    Deque<Character> stack = new ArrayDeque<>();\n\n    for (final char c : s.toCharArray())\n      if (c == '(')\n        stack.push(')');\n      else if (c == '{')\n        stack.push('}');\n      else if (c == '[')\n        stack.push(']');\n      else if (stack.isEmpty() || stack.pop() != c)\n        return false;\n\n    return stack.isEmpty();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isValid(string s) {\n    stack<char> stack;\n\n    for (const char c : s)\n      if (c == '(')\n        stack.push(')');\n      else if (c == '{')\n        stack.push('}');\n      else if (c == '[')\n        stack.push(']');\n      else if (stack.empty() || pop(stack) != c)\n        return false;\n\n    return stack.empty();\n  }\n\n private:\n  int pop(stack<char>& stack) {\n    const int c = stack.top();\n    stack.pop();\n    return c;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/20.html",
    "category": "Algorithms",
    "acceptance_rate": 42.17887507318851,
    "topics": [
      "String",
      "Stack"
    ],
    "hints": [
      "Use a stack of characters.",
      "When you encounter an opening bracket, push it to the top of the stack.",
      "When you encounter a closing bracket, check if the top of the stack was the opening for it. If yes, pop it from the stack. Otherwise, return false."
    ],
    "likes": 25692,
    "dislikes": 1873,
    "similar_questions": "[{\"title\": \"Generate Parentheses\", \"titleSlug\": \"generate-parentheses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Valid Parentheses\", \"titleSlug\": \"longest-valid-parentheses\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Remove Invalid Parentheses\", \"titleSlug\": \"remove-invalid-parentheses\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check If Word Is Valid After Substitutions\", \"titleSlug\": \"check-if-word-is-valid-after-substitutions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check if a Parentheses String Can Be Valid\", \"titleSlug\": \"check-if-a-parentheses-string-can-be-valid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Move Pieces to Obtain a String\", \"titleSlug\": \"move-pieces-to-obtain-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"6M\", \"totalSubmission\": \"14.2M\", \"totalAcceptedRaw\": 6007233, \"totalSubmissionRaw\": 14242293, \"acRate\": \"42.2%\"}",
    "title_pt": "Parênteses Válidos",
    "description_pt": "<p>Dada uma string <code>s</code> contendo apenas os caracteres <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, <code>&#39;{&#39;</code>, <code>&#39;}&#39;</code>, <code>&#39;[&#39;</code> e <code>&#39;]&#39;</code>, determine se a string de entrada é válida.</p>\n\n<p>Uma string de entrada é válida se:</p>\n\n<ol>\n\t<li>Os colchetes de abertura devem ser fechados pelo mesmo tipo de colchetes.</li>\n\t<li>Os colchetes de abertura devem ser fechados na ordem correta.</li>\n\t<li>Cada colchete de fechamento tem um colchete de abertura correspondente do mesmo tipo.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;()&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;()[]{}&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;(]&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;([])&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste apenas em parênteses <code>&#39;()[]{}&#39;</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Use uma pilha de caracteres.",
      "Dica 2: Quando você encontrar um colchete de abertura, empilhe-o no topo da pilha.",
      "Dica 3: Quando você encontrar um colchete de fechamento, verifique se o topo da pilha era a abertura correspondente. Se sim, remova-o da pilha. Caso contrário, retorne false."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "21",
    "paidOnly": false,
    "title": "Merge Two Sorted Lists",
    "titleSlug": "merge-two-sorted-lists",
    "url": "https://leetcode.com/problems/merge-two-sorted-lists",
    "description_url": "https://leetcode.com/problems/merge-two-sorted-lists/description/",
    "description": "<p>You are given the heads of two sorted linked lists <code>list1</code> and <code>list2</code>.</p>\n\n<p>Merge the two lists into one <strong>sorted</strong> list. The list should be made by splicing together the nodes of the first two lists.</p>\n\n<p>Return <em>the head of the merged linked list</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg\" style=\"width: 662px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> list1 = [1,2,4], list2 = [1,3,4]\n<strong>Output:</strong> [1,1,2,3,4,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> list1 = [], list2 = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> list1 = [], list2 = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in both lists is in the range <code>[0, 50]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>Both <code>list1</code> and <code>list2</code> are sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/merge-two-sorted-lists/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n    if not list1 or not list2:\n      return list1 if list1 else list2\n    if list1.val > list2.val:\n      list1, list2 = list2, list1\n    list1.next = self.mergeTwoLists(list1.next, list2)\n    return list1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n    if (list1 == null || list2 == null)\n      return list1 == null ? list2 : list1;\n    if (list1.val > list2.val) {\n      ListNode temp = list1;\n      list1 = list2;\n      list2 = temp;\n    }\n    list1.next = mergeTwoLists(list1.next, list2);\n    return list1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n    if (!list1 || !list2)\n      return list1 ? list1 : list2;\n    if (list1->val > list2->val)\n      swap(list1, list2);\n    list1->next = mergeTwoLists(list1->next, list2);\n    return list1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/21.html",
    "category": "Algorithms",
    "acceptance_rate": 66.67446898514312,
    "topics": [
      "Linked List",
      "Recursion"
    ],
    "hints": [],
    "likes": 23262,
    "dislikes": 2291,
    "similar_questions": "[{\"title\": \"Merge k Sorted Lists\", \"titleSlug\": \"merge-k-sorted-lists\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Merge Sorted Array\", \"titleSlug\": \"merge-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sort List\", \"titleSlug\": \"sort-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Word Distance II\", \"titleSlug\": \"shortest-word-distance-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Two Polynomials Represented as Linked Lists\", \"titleSlug\": \"add-two-polynomials-represented-as-linked-lists\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Common Subsequence Between Sorted Arrays\", \"titleSlug\": \"longest-common-subsequence-between-sorted-arrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Merge Two 2D Arrays by Summing Values\", \"titleSlug\": \"merge-two-2d-arrays-by-summing-values\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"5.2M\", \"totalSubmission\": \"7.8M\", \"totalAcceptedRaw\": 5201329, \"totalSubmissionRaw\": 7801085, \"acRate\": \"66.7%\"}",
    "title_pt": "Mesclar Duas Listas Encadeadas Ordenadas",
    "description_pt": "<p>Você recebe as cabeças de duas listas encadeadas ordenadas <code>list1</code> e <code>list2</code>.</p>\n\n<p>Mescle as duas listas em uma única lista <strong>ordenada</strong>. A lista deve ser construída unindo os nós das duas primeiras listas.</p>\n\n<p>Retorne <em>a cabeça da lista encadeada mesclada</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg\" style=\"width: 662px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> list1 = [1,2,4], list2 = [1,3,4]\n<strong>Saída:</strong> [1,1,2,3,4,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> list1 = [], list2 = []\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> list1 = [], list2 = [0]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em ambas as listas está no intervalo <code>[0, 50]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>Ambas <code>list1</code> e <code>list2</code> estão ordenadas em ordem <strong>não decrescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "22",
    "paidOnly": false,
    "title": "Generate Parentheses",
    "titleSlug": "generate-parentheses",
    "url": "https://leetcode.com/problems/generate-parentheses",
    "description_url": "https://leetcode.com/problems/generate-parentheses/description/",
    "description": "<p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> [\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> [\"()\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/generate-parentheses/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def generateParenthesis(self, n):\n    ans = []\n\n    def dfs(l: int, r: int, s: str) -> None:\n      if l == 0 and r == 0:\n        ans.append(s)\n      if l > 0:\n        dfs(l - 1, r, s + '(')\n      if l < r:\n        dfs(l, r - 1, s + ')')\n\n    dfs(n, n, '')\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> generateParenthesis(int n) {\n    List<String> ans = new ArrayList<>();\n\n    dfs(n, n, new StringBuilder(), ans);\n    return ans;\n  }\n\n  private void dfs(int l, int r, final StringBuilder sb, List<String> ans) {\n    if (l == 0 && r == 0) {\n      ans.add(sb.toString());\n      return;\n    }\n\n    if (l > 0) {\n      sb.append(\"(\");\n      dfs(l - 1, r, sb, ans);\n      sb.deleteCharAt(sb.length() - 1);\n    }\n    if (l < r) {\n      sb.append(\")\");\n      dfs(l, r - 1, sb, ans);\n      sb.deleteCharAt(sb.length() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> generateParenthesis(int n) {\n    vector<string> ans;\n\n    dfs(n, n, \"\", ans);\n    return ans;\n  }\n\n private:\n  void dfs(int l, int r, string&& path, vector<string>& ans) {\n    if (l == 0 && r == 0) {\n      ans.push_back(path);\n      return;\n    }\n\n    if (l > 0) {\n      path.push_back('(');\n      dfs(l - 1, r, move(path), ans);\n      path.pop_back();\n    }\n    if (l < r) {\n      path.push_back(')');\n      dfs(l, r - 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/22.html",
    "category": "Algorithms",
    "acceptance_rate": 76.93766654595672,
    "topics": [
      "String",
      "Dynamic Programming",
      "Backtracking"
    ],
    "hints": [],
    "likes": 22095,
    "dislikes": 1028,
    "similar_questions": "[{\"title\": \"Letter Combinations of a Phone Number\", \"titleSlug\": \"letter-combinations-of-a-phone-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Valid Parentheses\", \"titleSlug\": \"valid-parentheses\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Check if a Parentheses String Can Be Valid\", \"titleSlug\": \"check-if-a-parentheses-string-can-be-valid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"3M\", \"totalAcceptedRaw\": 2334919, \"totalSubmissionRaw\": 3034820, \"acRate\": \"76.9%\"}",
    "title_pt": "Gerar Parênteses",
    "description_pt": "<p>Dado <code>n</code> pares de parênteses, escreva uma função para <em>gerar todas as combinações de parênteses corretamente formadas</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> [\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [\"()\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "23",
    "paidOnly": false,
    "title": "Merge k Sorted Lists",
    "titleSlug": "merge-k-sorted-lists",
    "url": "https://leetcode.com/problems/merge-k-sorted-lists",
    "description_url": "https://leetcode.com/problems/merge-k-sorted-lists/description/",
    "description": "<p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p>\n\n<p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]]\n<strong>Output:</strong> [1,1,2,3,4,4,5,6]\n<strong>Explanation:</strong> The linked-lists are:\n[\n  1-&gt;4-&gt;5,\n  1-&gt;3-&gt;4,\n  2-&gt;6\n]\nmerging them into one sorted list:\n1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> lists = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> lists = [[]]\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>k == lists.length</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= lists[i].length &lt;= 500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li>\n\t<li>The sum of <code>lists[i].length</code> will not exceed <code>10<sup>4</sup></code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/merge-k-sorted-lists/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nfrom queue import PriorityQueue\n\n\nclass Solution:\n  def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n    dummy = ListNode(0)\n    curr = dummy\n    pq = PriorityQueue()\n\n    for i, lst in enumerate(lists):\n      if lst:\n        pq.put((lst.val, i, lst))\n\n    while not pq.empty():\n      _, i, minNode = pq.get()\n      if minNode.next:\n        pq.put((minNode.next.val, i, minNode.next))\n      curr.next = minNode\n      curr = curr.next\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode mergeKLists(ListNode[] lists) {\n    ListNode dummy = new ListNode(0);\n    ListNode curr = dummy;\n    Queue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);\n\n    for (final ListNode list : lists)\n      if (list != null)\n        minHeap.offer(list);\n\n    while (!minHeap.isEmpty()) {\n      ListNode minNode = minHeap.poll();\n      if (minNode.next != null)\n        minHeap.offer(minNode.next);\n      curr.next = minNode;\n      curr = curr.next;\n    }\n\n    return dummy.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* mergeKLists(vector<ListNode*>& lists) {\n    ListNode dummy(0);\n    ListNode* curr = &dummy;\n    auto compare = [](ListNode* a, ListNode* b) { return a->val > b->val; };\n    priority_queue<ListNode*, vector<ListNode*>, decltype(compare)> minHeap(\n        compare);\n\n    for (ListNode* list : lists)\n      if (list != nullptr)\n        minHeap.push(list);\n\n    while (!minHeap.empty()) {\n      ListNode* minNode = minHeap.top();\n      minHeap.pop();\n      if (minNode->next)\n        minHeap.push(minNode->next);\n      curr->next = minNode;\n      curr = curr->next;\n    }\n\n    return dummy.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/23.html",
    "category": "Algorithms",
    "acceptance_rate": 56.47701821042494,
    "topics": [
      "Linked List",
      "Divide and Conquer",
      "Heap (Priority Queue)",
      "Merge Sort"
    ],
    "hints": [],
    "likes": 20311,
    "dislikes": 755,
    "similar_questions": "[{\"title\": \"Merge Two Sorted Lists\", \"titleSlug\": \"merge-two-sorted-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Ugly Number II\", \"titleSlug\": \"ugly-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Subarrays With Maximum Bitwise OR\", \"titleSlug\": \"smallest-subarrays-with-maximum-bitwise-or\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"4.4M\", \"totalAcceptedRaw\": 2473920, \"totalSubmissionRaw\": 4380400, \"acRate\": \"56.5%\"}",
    "title_pt": "Mesclar k Listas Encadeadas Ordenadas",
    "description_pt": "<p>Você recebe um array de <code>k</code> listas encadeadas <code>lists</code>, e cada lista encadeada está ordenada em ordem crescente.</p>\n\n<p><em>Mescle todas as listas encadeadas em uma única lista encadeada ordenada e retorne-a.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> lists = [[1,4,5],[1,3,4],[2,6]]\n<strong>Saída:</strong> [1,1,2,3,4,4,5,6]\n<strong>Explicação:</strong> As listas encadeadas são:\n[\n  1-&gt;4-&gt;5,\n  1-&gt;3-&gt;4,\n  2-&gt;6\n]\nmesclando-as em uma única lista ordenada:\n1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> lists = []\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> lists = [[]]\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>k == lists.length</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= lists[i].length &lt;= 500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= lists[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>lists[i]</code> está ordenado em <strong>ordem crescente</strong>.</li>\n\t<li>A soma de <code>lists[i].length</code> não excederá <code>10<sup>4</sup></code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "24",
    "paidOnly": false,
    "title": "Swap Nodes in Pairs",
    "titleSlug": "swap-nodes-in-pairs",
    "url": "https://leetcode.com/problems/swap-nodes-in-pairs",
    "description_url": "https://leetcode.com/problems/swap-nodes-in-pairs/description/",
    "description": "<p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list&#39;s nodes (i.e., only nodes themselves may be changed.)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">head = [1,2,3,4]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[2,1,4,3]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg\" style=\"width: 422px; height: 222px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">head = []</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">head = [1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">head = [1,2,3]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[2,1,3]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/swap-nodes-in-pairs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def swapPairs(self, head: ListNode) -> ListNode:\n    def getLength(head: ListNode) -> int:\n      length = 0\n      while head:\n        length += 1\n        head = head.next\n      return length\n\n    length = getLength(head)\n    dummy = ListNode(0, head)\n    prev = dummy\n    curr = head\n\n    for _ in range(length // 2):\n      next = curr.next\n      curr.next = next.next\n      next.next = prev.next\n      prev.next = next\n      prev = curr\n      curr = curr.next\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode swapPairs(ListNode head) {\n    final int length = getLength(head);\n    ListNode dummy = new ListNode(0, head);\n    ListNode prev = dummy;\n    ListNode curr = head;\n\n    for (int i = 0; i < length / 2; ++i) {\n      ListNode next = curr.next;\n      curr.next = next.next;\n      next.next = curr;\n      prev.next = next;\n      prev = curr;\n      curr = curr.next;\n    }\n\n    return dummy.next;\n  }\n\n  private int getLength(ListNode head) {\n    int length = 0;\n    for (ListNode curr = head; curr != null; curr = curr.next)\n      ++length;\n    return length;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* swapPairs(ListNode* head) {\n    const int length = getLength(head);\n    ListNode dummy(0, head);\n    ListNode* prev = &dummy;\n    ListNode* curr = head;\n\n    for (int i = 0; i < length / 2; ++i) {\n      ListNode* next = curr->next;\n      curr->next = next->next;\n      next->next = prev->next;\n      prev->next = next;\n      prev = curr;\n      curr = curr->next;\n    }\n\n    return dummy.next;\n  }\n\n private:\n  int getLength(ListNode* head) {\n    int length = 0;\n    for (ListNode* curr = head; curr; curr = curr->next)\n      ++length;\n    return length;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/24.html",
    "category": "Algorithms",
    "acceptance_rate": 66.97877312045225,
    "topics": [
      "Linked List",
      "Recursion"
    ],
    "hints": [],
    "likes": 12472,
    "dislikes": 478,
    "similar_questions": "[{\"title\": \"Reverse Nodes in k-Group\", \"titleSlug\": \"reverse-nodes-in-k-group\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Swapping Nodes in a Linked List\", \"titleSlug\": \"swapping-nodes-in-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1618950, \"totalSubmissionRaw\": 2417113, \"acRate\": \"67.0%\"}",
    "title_pt": "Trocar Nós em Pares",
    "description_pt": "<p>Dada uma&nbsp;lista encadeada, troque cada dois nós adjacentes e retorne sua cabeça. Você deve resolver o problema sem&nbsp;modificar os valores nos nós da lista (isto é, somente os próprios nós podem ser alterados.)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">head = [1,2,3,4]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[2,1,4,3]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg\" style=\"width: 422px; height: 222px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">head = []</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">head = [1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">head = [1,2,3]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[2,1,3]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na&nbsp;lista&nbsp;está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "25",
    "paidOnly": false,
    "title": "Reverse Nodes in k-Group",
    "titleSlug": "reverse-nodes-in-k-group",
    "url": "https://leetcode.com/problems/reverse-nodes-in-k-group",
    "description_url": "https://leetcode.com/problems/reverse-nodes-in-k-group/description/",
    "description": "<p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p>\n\n<p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p>\n\n<p>You may not alter the values in the list&#39;s nodes, only nodes themselves may be changed.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5], k = 2\n<strong>Output:</strong> [2,1,4,3,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5], k = 3\n<strong>Output:</strong> [3,2,1,4,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>n</code>.</li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>\n",
    "solution_url": "https://leetcode.com/problems/reverse-nodes-in-k-group/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n    if not head:\n      return None\n\n    tail = head\n\n    for _ in range(k):\n      if not tail:  # Less than k nodes, do nothing\n        return head\n      tail = tail.next\n\n    newHead = self._reverse(head, tail)\n    head.next = self.reverseKGroup(tail, k)\n    return newHead\n\n  # Reverses [head, tail)\n  def _reverse(self, head: Optional[ListNode], tail: Optional[ListNode]) -> Optional[ListNode]:\n    prev = None\n    curr = head\n\n    while curr != tail:\n      next = curr.next\n      curr.next = prev\n      prev = curr\n      curr = next\n\n    return prev",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode reverseKGroup(ListNode head, int k) {\n    if (head == null)\n      return null;\n\n    ListNode tail = head;\n\n    for (int i = 0; i < k; ++i) {\n      if (tail == null) // Less than k nodes, do nothing\n        return head;\n      tail = tail.next;\n    }\n\n    ListNode newHead = reverse(head, tail);\n    head.next = reverseKGroup(tail, k);\n    return newHead;\n  }\n\n  // Reverses [head, tail)\n  private ListNode reverse(ListNode head, ListNode tail) {\n    ListNode prev = null;\n    ListNode curr = head;\n\n    while (curr != tail) {\n      ListNode next = curr.next;\n      curr.next = prev;\n      prev = curr;\n      curr = next;\n    }\n\n    return prev;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* reverseKGroup(ListNode* head, int k) {\n    if (head == nullptr)\n      return nullptr;\n\n    ListNode* tail = head;\n\n    for (int i = 0; i < k; ++i) {\n      if (tail == nullptr)  // Less than k nodes, do nothing\n        return head;\n      tail = tail->next;\n    }\n\n    ListNode* newHead = reverse(head, tail);\n    head->next = reverseKGroup(tail, k);\n    return newHead;\n  }\n\n private:\n  // Reverses [head, tail)\n  ListNode* reverse(ListNode* head, ListNode* tail) {\n    ListNode* prev = nullptr;\n    ListNode* curr = head;\n\n    while (curr != tail) {\n      ListNode* next = curr->next;\n      curr->next = prev;\n      prev = curr;\n      curr = next;\n    }\n\n    return prev;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/25.html",
    "category": "Algorithms",
    "acceptance_rate": 62.71432274916806,
    "topics": [
      "Linked List",
      "Recursion"
    ],
    "hints": [],
    "likes": 14546,
    "dislikes": 750,
    "similar_questions": "[{\"title\": \"Swap Nodes in Pairs\", \"titleSlug\": \"swap-nodes-in-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Swapping Nodes in a Linked List\", \"titleSlug\": \"swapping-nodes-in-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Reverse Nodes in Even Length Groups\", \"titleSlug\": \"reverse-nodes-in-even-length-groups\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1211963, \"totalSubmissionRaw\": 1932522, \"acRate\": \"62.7%\"}",
    "title_pt": "Reverter Nós em Grupos de k",
    "description_pt": "<p>Dada a <code>head</code> de uma lista encadeada, reverta os nós da lista <code>k</code> por vez e retorne <em>a lista modificada</em>.</p>\n\n<p><code>k</code> é um inteiro positivo e é menor ou igual ao tamanho da lista encadeada. Se o número de nós não for um múltiplo de <code>k</code>, então os nós restantes, no final, devem permanecer como estão.</p>\n\n<p>Você não pode alterar os valores nos nós da lista; apenas os próprios nós podem ser modificados.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5], k = 2\n<strong>Saída:</strong> [2,1,4,3,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5], k = 3\n<strong>Saída:</strong> [3,2,1,4,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista é <code>n</code>.</li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue resolver o problema em espaço de memória extra de <code>O(1)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "26",
    "paidOnly": false,
    "title": "Remove Duplicates from Sorted Array",
    "titleSlug": "remove-duplicates-from-sorted-array",
    "url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array",
    "description_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/",
    "description": "<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove the duplicates <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a> such that each unique element appears only <strong>once</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>. Then return <em>the number of unique elements in </em><code>nums</code>.</p>\n\n<p>Consider the number of unique elements of <code>nums</code> to be <code>k</code>, to get accepted, you need to do the following things:</p>\n\n<ul>\n\t<li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the unique elements in the order they were present in <code>nums</code> initially. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li>\n\t<li>Return <code>k</code>.</li>\n</ul>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The judge will test your solution with the following code:</p>\n\n<pre>\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,2]\n<strong>Output:</strong> 2, nums = [1,2,_]\n<strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,0,1,1,1,2,2,3,3,4]\n<strong>Output:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_]\n<strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeDuplicates(self, nums: List[int]) -> int:\n    i = 0\n\n    for num in nums:\n      if i < 1 or num > nums[i - 1]:\n        nums[i] = num\n        i += 1\n\n    return i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int removeDuplicates(int[] nums) {\n    int i = 0;\n\n    for (final int num : nums)\n      if (i < 1 || num > nums[i - 1])\n        nums[i++] = num;\n\n    return i;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int removeDuplicates(vector<int>& nums) {\n    int i = 0;\n\n    for (const int num : nums)\n      if (i < 1 || num > nums[i - 1])\n        nums[i++] = num;\n\n    return i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/26.html",
    "category": "Algorithms",
    "acceptance_rate": 60.08456768594812,
    "topics": [
      "Array",
      "Two Pointers"
    ],
    "hints": [
      "In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image below for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements?\r\n\r\n<br>\r\n<img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_rem_dup.png\" width=\"500\"/>",
      "We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements.",
      "Essentially, once an element is encountered, you simply need to <b>bypass</b> its duplicates and move on to the next unique element."
    ],
    "likes": 16629,
    "dislikes": 19781,
    "similar_questions": "[{\"title\": \"Remove Element\", \"titleSlug\": \"remove-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Remove Duplicates from Sorted Array II\", \"titleSlug\": \"remove-duplicates-from-sorted-array-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Apply Operations to an Array\", \"titleSlug\": \"apply-operations-to-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Distances\", \"titleSlug\": \"sum-of-distances\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"6.1M\", \"totalSubmission\": \"10.2M\", \"totalAcceptedRaw\": 6131373, \"totalSubmissionRaw\": 10204577, \"acRate\": \"60.1%\"}",
    "title_pt": "Remover Duplicados de um Array Ordenado",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> ordenado em <strong>ordem não decrescente</strong>, remova os duplicados <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a> de modo que cada elemento único apareça apenas <strong>uma vez</strong>. A <strong>ordem relativa</strong> dos elementos deve ser mantida a <strong>mesma</strong>. Em seguida, retorne <em>o número de elementos únicos em </em><code>nums</code>.</p>\n\n<p>Considere que o número de elementos únicos de <code>nums</code> seja <code>k</code>; para ser aceito, você precisa fazer as seguintes coisas:</p>\n\n<ul>\n\t<li>Altere o array <code>nums</code> de modo que os primeiros <code>k</code> elementos de <code>nums</code> contenham os elementos únicos na ordem em que estavam presentes originalmente em <code>nums</code>. Os elementos restantes de <code>nums</code> não são importantes, assim como o tamanho de <code>nums</code>.</li>\n\t<li>Retorne <code>k</code>.</li>\n</ul>\n\n<p><strong>Juiz Customizado:</strong></p>\n\n<p>O juiz testará sua solução com o seguinte código:</p>\n\n<pre>\nint[] nums = [...]; // Array de entrada\nint[] expectedNums = [...]; // A resposta esperada com o comprimento correto\n\nint k = removeDuplicates(nums); // Chama sua implementação\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>Se todas as asserções passarem, então sua solução será <strong>aceita</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,2]\n<strong>Saída:</strong> 2, nums = [1,2,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 2, com os dois primeiros elementos de nums sendo 1 e 2, respectivamente.\nNão importa o que você deixe além do k retornado (por isso eles são sublinhados).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,0,1,1,1,2,2,3,3,4]\n<strong>Saída:</strong> 5, nums = [0,1,2,3,4,_,_,_,_,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 5, com os cinco primeiros elementos de nums sendo 0, 1, 2, 3 e 4, respectivamente.\nNão importa o que você deixe além do k retornado (por isso eles são sublinhados).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>nums</code> está ordenado em <strong>ordem não decrescente</strong>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Neste problema, o ponto-chave em que você deve se concentrar é que o array de entrada está ordenado. No que diz respeito a elementos duplicados, qual é o posicionamento deles no array quando o array fornecido está ordenado? Observe a imagem abaixo para obter a resposta. Se soubermos a posição de um dos elementos, também sabemos o posicionamento de todos os elementos duplicados?\n\n<br>\n<img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_rem_dup.png\" width=\"500\"/>",
      "Dica 2: Precisamos modificar o array in-place e o tamanho do array final potencialmente será menor do que o tamanho do array de entrada. Portanto, devemos usar aqui uma abordagem de dois ponteiros. Um que acompanhe o elemento atual no array original e outro apenas para os elementos únicos.",
      "Dica 3: Essencialmente, assim que um elemento for encontrado, você só precisa <b>ignorar</b> seus duplicados e prosseguir para o próximo elemento único."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "27",
    "paidOnly": false,
    "title": "Remove Element",
    "titleSlug": "remove-element",
    "url": "https://leetcode.com/problems/remove-element",
    "description_url": "https://leetcode.com/problems/remove-element/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>val</code>, remove all occurrences of <code>val</code> in <code>nums</code> <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a>. The order of the elements may be changed. Then return <em>the number of elements in </em><code>nums</code><em> which are not equal to </em><code>val</code>.</p>\n\n<p>Consider the number of elements in <code>nums</code> which are not equal to <code>val</code> be <code>k</code>, to get accepted, you need to do the following things:</p>\n\n<ul>\n\t<li>Change the array <code>nums</code> such that the first <code>k</code> elements of <code>nums</code> contain the elements which are not equal to <code>val</code>. The remaining elements of <code>nums</code> are not important as well as the size of <code>nums</code>.</li>\n\t<li>Return <code>k</code>.</li>\n</ul>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The judge will test your solution with the following code:</p>\n\n<pre>\nint[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n                            // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i &lt; actualLength; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,2,3], val = 3\n<strong>Output:</strong> 2, nums = [2,2,_,_]\n<strong>Explanation:</strong> Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,2,2,3,0,4,2], val = 2\n<strong>Output:</strong> 5, nums = [0,1,4,0,3,_,_,_]\n<strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 50</code></li>\n\t<li><code>0 &lt;= val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-element/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeElement(self, nums: List[int], val: int) -> int:\n    i = 0\n\n    for num in nums:\n      if num != val:\n        nums[i] = num\n        i += 1\n\n    return i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int removeElement(int[] nums, int val) {\n    int i = 0;\n\n    for (final int num : nums)\n      if (num != val)\n        nums[i++] = num;\n\n    return i;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int removeElement(vector<int>& nums, int val) {\n    int i = 0;\n\n    for (const int num : nums)\n      if (num != val)\n        nums[i++] = num;\n\n    return i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/27.html",
    "category": "Algorithms",
    "acceptance_rate": 59.86020878014128,
    "topics": [
      "Array",
      "Two Pointers"
    ],
    "hints": [
      "The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to <b>remove</b> that element per-say, right?",
      "We can move all the occurrences of this element to the end of the array. Use two pointers!\r\n<br><img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_remove_element.png\" width=\"500\"/>",
      "Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us."
    ],
    "likes": 3793,
    "dislikes": 4769,
    "similar_questions": "[{\"title\": \"Remove Duplicates from Sorted Array\", \"titleSlug\": \"remove-duplicates-from-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Remove Linked List Elements\", \"titleSlug\": \"remove-linked-list-elements\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Move Zeroes\", \"titleSlug\": \"move-zeroes\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.2M\", \"totalSubmission\": \"6.9M\", \"totalAcceptedRaw\": 4159294, \"totalSubmissionRaw\": 6948348, \"acRate\": \"59.9%\"}",
    "title_pt": "Remover Elemento",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>val</code>, remova todas as ocorrências de <code>val</code> em <code>nums</code> <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a>. A ordem dos elementos pode ser alterada. Em seguida, retorne <em>o número de elementos em </em><code>nums</code><em> que não são iguais a </em><code>val</code>.</p>\n\n<p>Considere que o número de elementos em <code>nums</code> que não são iguais a <code>val</code> seja <code>k</code>; para ser aceito, você precisa fazer o seguinte:</p>\n\n<ul>\n\t<li>Altere o array <code>nums</code> de forma que os primeiros <code>k</code> elementos de <code>nums</code> contenham os elementos que não são iguais a <code>val</code>. Os elementos restantes de <code>nums</code> não são importantes, assim como o tamanho de <code>nums</code>.</li>\n\t<li>Retorne <code>k</code>.</li>\n</ul>\n\n<p><strong>Juiz personalizado:</strong></p>\n\n<p>O juiz testará sua solução com o seguinte código:</p>\n\n<pre>\nint[] nums = [...]; // Array de entrada\nint val = ...; // Valor a remover\nint[] expectedNums = [...]; // A resposta esperada com comprimento correto.\n                            // Está ordenado e sem valores iguais a val.\n\nint k = removeElement(nums, val); // Chama sua implementação\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Ordena os primeiros k elementos de nums\nfor (int i = 0; i &lt; actualLength; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>Se todas as asserções passarem, então sua solução será <strong>aceita</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,2,3], val = 3\n<strong>Saída:</strong> 2, nums = [2,2,_,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 2, com os dois primeiros elementos de nums sendo 2.\nNão importa o que você deixar além do k retornado (por isso eles são sublinhados).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,2,2,3,0,4,2], val = 2\n<strong>Saída:</strong> 5, nums = [0,1,4,0,3,_,_,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 5, com os cinco primeiros elementos de nums contendo 0, 0, 1, 3 e 4.\nObserve que os cinco elementos podem ser retornados em qualquer ordem.\nNão importa o que você deixar além do k retornado (por isso eles são sublinhados).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 50</code></li>\n\t<li><code>0 &lt;= val &lt;= 100</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: O enunciado deixa claro que devemos modificar o array in-place e também diz que o elemento além do novo comprimento do array pode ser qualquer coisa. Dado um elemento, precisamos remover todas as ocorrências dele do array. Tecnicamente, não precisamos <b>remover</b> esse elemento, propriamente dito, certo?",
      "Dica 2: Podemos mover todas as ocorrências desse elemento para o final do array. Use dois ponteiros!\r\n<br><img src=\"https://assets.leetcode.com/uploads/2019/10/20/hint_remove_element.png\" width=\"500\"/>",
      "Dica 3: Outra linha de raciocínio é considerar os elementos a serem removidos como inexistentes. Em uma única passagem, se mantivermos copiando os elementos visíveis in-place, isso também deve resolver este problema para nós."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "28",
    "paidOnly": false,
    "title": "Find the Index of the First Occurrence in a String",
    "titleSlug": "find-the-index-of-the-first-occurrence-in-a-string",
    "url": "https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string",
    "description_url": "https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/",
    "description": "<p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot;\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> &quot;sad&quot; occurs at index 0 and 6.\nThe first occurrence is at index 0, so we return 0.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot;\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> &quot;leeto&quot; did not occur in &quot;leetcode&quot;, so we return -1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def strStr(self, haystack: str, needle: str) -> int:\n    m = len(haystack)\n    n = len(needle)\n\n    for i in range(m - n + 1):\n      if haystack[i:i + n] == needle:\n        return i\n\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int strStr(String haystack, String needle) {\n    final int m = haystack.length();\n    final int n = needle.length();\n\n    for (int i = 0; i < m - n + 1; ++i)\n      if (haystack.substring(i, i + n).equals(needle))\n        return i;\n\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int strStr(string haystack, string needle) {\n    const int m = haystack.length();\n    const int n = needle.length();\n\n    for (int i = 0; i < m - n + 1; i++)\n      if (haystack.substr(i, n) == needle)\n        return i;\n\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/28.html",
    "category": "Algorithms",
    "acceptance_rate": 44.81305140045061,
    "topics": [
      "Two Pointers",
      "String",
      "String Matching"
    ],
    "hints": [],
    "likes": 6672,
    "dislikes": 495,
    "similar_questions": "[{\"title\": \"Shortest Palindrome\", \"titleSlug\": \"shortest-palindrome\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Repeated Substring Pattern\", \"titleSlug\": \"repeated-substring-pattern\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.3M\", \"totalSubmission\": \"7.3M\", \"totalAcceptedRaw\": 3275682, \"totalSubmissionRaw\": 7309671, \"acRate\": \"44.8%\"}",
    "title_pt": "Encontrar o Índice da Primeira Ocorrência em uma String",
    "description_pt": "<p>Dadas duas strings <code>needle</code> e <code>haystack</code>, retorne o índice da primeira ocorrência de <code>needle</code> em <code>haystack</code>, ou <code>-1</code> se <code>needle</code> não fizer parte de <code>haystack</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> haystack = &quot;sadbutsad&quot;, needle = &quot;sad&quot;\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> &quot;sad&quot; ocorre no índice 0 e 6.\nA primeira ocorrência está no índice 0, então retornamos 0.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> haystack = &quot;leetcode&quot;, needle = &quot;leeto&quot;\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong> &quot;leeto&quot; não ocorreu em &quot;leetcode&quot;, então retornamos -1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "29",
    "paidOnly": false,
    "title": "Divide Two Integers",
    "titleSlug": "divide-two-integers",
    "url": "https://leetcode.com/problems/divide-two-integers",
    "description_url": "https://leetcode.com/problems/divide-two-integers/description/",
    "description": "<p>Given two integers <code>dividend</code> and <code>divisor</code>, divide two integers <strong>without</strong> using multiplication, division, and mod operator.</p>\n\n<p>The integer division should truncate toward zero, which means losing its fractional part. For example, <code>8.345</code> would be truncated to <code>8</code>, and <code>-2.7335</code> would be truncated to <code>-2</code>.</p>\n\n<p>Return <em>the <strong>quotient</strong> after dividing </em><code>dividend</code><em> by </em><code>divisor</code>.</p>\n\n<p><strong>Note: </strong>Assume we are dealing with an environment that could only store integers within the <strong>32-bit</strong> signed integer range: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. For this problem, if the quotient is <strong>strictly greater than</strong> <code>2<sup>31</sup> - 1</code>, then return <code>2<sup>31</sup> - 1</code>, and if the quotient is <strong>strictly less than</strong> <code>-2<sup>31</sup></code>, then return <code>-2<sup>31</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> dividend = 10, divisor = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 10/3 = 3.33333.. which is truncated to 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> dividend = 7, divisor = -3\n<strong>Output:</strong> -2\n<strong>Explanation:</strong> 7/-3 = -2.33333.. which is truncated to -2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>divisor != 0</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/divide-two-integers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def divide(self, dividend: int, divisor: int) -> int:\n    if dividend == -2**31 and divisor == -1:\n      return 2**31 - 1\n\n    sign = -1 if (dividend > 0) ^ (divisor > 0) else 1\n    ans = 0\n    dvd = abs(dividend)\n    dvs = abs(divisor)\n\n    while dvd >= dvs:\n      k = 1\n      while k * 2 * dvs <= dvd:\n        k <<= 1\n      dvd -= k * dvs\n      ans += k\n\n    return sign * ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int divide(long dividend, long divisor) {\n    // -2^{31} / -1 = 2^31 -> overflow so return 2^31 - 1\n    if (dividend == Integer.MIN_VALUE && divisor == -1)\n      return Integer.MAX_VALUE;\n\n    final int sign = dividend > 0 ^ divisor > 0 ? -1 : 1;\n    long ans = 0;\n    long dvd = Math.abs(dividend);\n    long dvs = Math.abs(divisor);\n\n    while (dvd >= dvs) {\n      long k = 1;\n      while (k * 2 * dvs <= dvd)\n        k *= 2;\n      dvd -= k * dvs;\n      ans += k;\n    }\n\n    return sign * (int) ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int divide(int dividend, int divisor) {\n    // -2^{31} / -1 = 2^31 -> overflow so return 2^31 - 1\n    if (dividend == INT_MIN && divisor == -1)\n      return INT_MAX;\n\n    const int sign = dividend > 0 ^ divisor > 0 ? -1 : 1;\n    long ans = 0;\n    long dvd = labs(dividend);\n    long dvs = labs(divisor);\n\n    while (dvd >= dvs) {\n      long k = 1;\n      while (k * 2 * dvs <= dvd)\n        k *= 2;\n      dvd -= k * dvs;\n      ans += k;\n    }\n\n    return sign * ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/29.html",
    "category": "Algorithms",
    "acceptance_rate": 18.318993177328156,
    "topics": [
      "Math",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 5579,
    "dislikes": 15092,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"929.2K\", \"totalSubmission\": \"5.1M\", \"totalAcceptedRaw\": 929192, \"totalSubmissionRaw\": 5072298, \"acRate\": \"18.3%\"}",
    "title_pt": "Dividir Dois Inteiros",
    "description_pt": "<p>Dado dois inteiros <code>dividend</code> e <code>divisor</code>, divida dois inteiros <strong>sem</strong> usar os operadores de multiplicação, divisão e módulo.</p>\n\n<p>A divisão de inteiros deve truncar em direção a zero, o que significa perder sua parte fracionária. Por exemplo, <code>8.345</code> seria truncado para <code>8</code>, e <code>-2.7335</code> seria truncado para <code>-2</code>.</p>\n\n<p>Retorne <em>o <strong>quociente</strong> após dividir </em><code>dividend</code><em> por </em><code>divisor</code>.</p>\n\n<p><strong>Nota: </strong>Assuma que estamos lidando com um ambiente que só pode armazenar inteiros dentro do intervalo de inteiros com sinal de <strong>32 bits</strong>: <code>[&minus;2<sup>31</sup>, 2<sup>31</sup> &minus; 1]</code>. Para este problema, se o quociente for <strong>estritamente maior que</strong> <code>2<sup>31</sup> - 1</code>, então retorne <code>2<sup>31</sup> - 1</code>, e se o quociente for <strong>estritamente menor que</strong> <code>-2<sup>31</sup></code>, então retorne <code>-2<sup>31</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> dividend = 10, divisor = 3\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> 10/3 = 3.33333.. que é truncado para 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> dividend = 7, divisor = -3\n<strong>Saída:</strong> -2\n<strong>Explicação:</strong> 7/-3 = -2.33333.. que é truncado para -2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= dividend, divisor &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>divisor != 0</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "30",
    "paidOnly": false,
    "title": "Substring with Concatenation of All Words",
    "titleSlug": "substring-with-concatenation-of-all-words",
    "url": "https://leetcode.com/problems/substring-with-concatenation-of-all-words",
    "description_url": "https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/",
    "description": "<p>You are given a string <code>s</code> and an array of strings <code>words</code>. All the strings of <code>words</code> are of <strong>the same length</strong>.</p>\n\n<p>A <strong>concatenated string</strong> is a string that exactly contains all the strings of any permutation of <code>words</code> concatenated.</p>\n\n<ul>\n\t<li>For example, if <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, then <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code>, and <code>&quot;efcdab&quot;</code> are all concatenated strings. <code>&quot;acdbef&quot;</code> is not a concatenated string because it is not the concatenation of any permutation of <code>words</code>.</li>\n</ul>\n\n<p>Return an array of <em>the starting indices</em> of all the concatenated substrings in <code>s</code>. You can return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[0,9]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The substring starting at 0 is <code>&quot;barfoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;foo&quot;]</code> which is a permutation of <code>words</code>.<br />\nThe substring starting at 9 is <code>&quot;foobar&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;]</code> which is a permutation of <code>words</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>There is no concatenated substring.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[6,9,12]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The substring starting at 6 is <code>&quot;foobarthe&quot;</code>. It is the concatenation of <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br />\nThe substring starting at 9 is <code>&quot;barthefoo&quot;</code>. It is the concatenation of <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br />\nThe substring starting at 12 is <code>&quot;thefoobar&quot;</code>. It is the concatenation of <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>s</code> and <code>words[i]</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/substring-with-concatenation-of-all-words/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findSubstring(self, s: str, words: List[str]) -> List[int]:\n    if len(s) == 0 or words == []:\n      return []\n\n    k = len(words)\n    n = len(words[0])\n    ans = []\n    count = Counter(words)\n\n    for i in range(len(s) - k * n + 1):\n      seen = defaultdict(int)\n      j = 0\n      while j < k:\n        word = s[i + j * n: i + j * n + n]\n        seen[word] += 1\n        if seen[word] > count[word]:\n          break\n        j += 1\n      if j == k:\n        ans.append(i)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findSubstring(String s, String[] words) {\n    if (s.isEmpty() || words.length == 0)\n      return new ArrayList<>();\n\n    final int k = words.length;\n    final int n = words[0].length();\n    List<Integer> ans = new ArrayList<>();\n    Map<String, Integer> count = new HashMap<>();\n\n    for (final String word : words)\n      count.put(word, count.getOrDefault(word, 0) + 1);\n\n    for (int i = 0; i <= s.length() - k * n; ++i) {\n      Map<String, Integer> seen = new HashMap<>();\n      int j = 0;\n      for (; j < k; ++j) {\n        final String word = s.substring(i + j * n, i + j * n + n);\n        seen.put(word, seen.getOrDefault(word, 0) + 1);\n        if (seen.get(word) > count.getOrDefault(word, 0))\n          break;\n      }\n      if (j == k)\n        ans.add(i);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findSubstring(string s, vector<string>& words) {\n    if (s.empty() || words.empty())\n      return {};\n\n    const int k = words.size();\n    const int n = words[0].length();\n    vector<int> ans;\n    unordered_map<string, int> count;\n\n    for (const string& word : words)\n      ++count[word];\n\n    for (int i = 0; i < s.length() - k * n + 1; ++i) {\n      unordered_map<string, int> seen;\n      int j;\n      for (j = 0; j < k; ++j) {\n        const string& word = s.substr(i + j * n, n);\n        if (++seen[word] > count[word])\n          break;\n      }\n      if (j == k)\n        ans.push_back(i);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/30.html",
    "category": "Algorithms",
    "acceptance_rate": 32.94825752863993,
    "topics": [
      "Hash Table",
      "String",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 2208,
    "dislikes": 354,
    "similar_questions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"574.8K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 574774, \"totalSubmissionRaw\": 1744485, \"acRate\": \"32.9%\"}",
    "title_pt": "Substring com Concatenação de Todas as Palavras",
    "description_pt": "<p>Você recebe uma string <code>s</code> e um array de strings <code>words</code>. Todas as strings de <code>words</code> têm <strong>o mesmo comprimento</strong>.</p>\n\n<p>Uma <strong>string concatenada</strong> é uma string que contém exatamente todas as strings de qualquer permutação de <code>words</code> concatenadas.</p>\n\n<ul>\n\t<li>Por exemplo, se <code>words = [&quot;ab&quot;,&quot;cd&quot;,&quot;ef&quot;]</code>, então <code>&quot;abcdef&quot;</code>, <code>&quot;abefcd&quot;</code>, <code>&quot;cdabef&quot;</code>, <code>&quot;cdefab&quot;</code>, <code>&quot;efabcd&quot;</code> e <code>&quot;efcdab&quot;</code> são todas strings concatenadas. <code>&quot;acdbef&quot;</code> não é uma string concatenada porque não é a concatenação de nenhuma permutação de <code>words</code>.</li>\n</ul>\n\n<p>Retorne um array com os <em>índices iniciais</em> de todas as substrings concatenadas em <code>s</code>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;barfoothefoobarman&quot;, words = [&quot;foo&quot;,&quot;bar&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[0,9]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A substring que começa em 0 é <code>&quot;barfoo&quot;</code>. Ela é a concatenação de <code>[&quot;bar&quot;,&quot;foo&quot;]</code>, que é uma permutação de <code>words</code>.<br />\nA substring que começa em 9 é <code>&quot;foobar&quot;</code>. Ela é a concatenação de <code>[&quot;foo&quot;,&quot;bar&quot;]</code>, que é uma permutação de <code>words</code>.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;wordgoodgoodgoodbestword&quot;, words = [&quot;word&quot;,&quot;good&quot;,&quot;best&quot;,&quot;word&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Não há nenhuma substring concatenada.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;barfoofoobarthefoobarman&quot;, words = [&quot;bar&quot;,&quot;foo&quot;,&quot;the&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[6,9,12]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A substring que começa em 6 é <code>&quot;foobarthe&quot;</code>. Ela é a concatenação de <code>[&quot;foo&quot;,&quot;bar&quot;,&quot;the&quot;]</code>.<br />\nA substring que começa em 9 é <code>&quot;barthefoo&quot;</code>. Ela é a concatenação de <code>[&quot;bar&quot;,&quot;the&quot;,&quot;foo&quot;]</code>.<br />\nA substring que começa em 12 é <code>&quot;thefoobar&quot;</code>. Ela é a concatenação de <code>[&quot;the&quot;,&quot;foo&quot;,&quot;bar&quot;]</code>.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>s</code> e <code>words[i]</code> consistem de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "31",
    "paidOnly": false,
    "title": "Next Permutation",
    "titleSlug": "next-permutation",
    "url": "https://leetcode.com/problems/next-permutation",
    "description_url": "https://leetcode.com/problems/next-permutation/description/",
    "description": "<p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p>\n\n<ul>\n\t<li>For example, for <code>arr = [1,2,3]</code>, the following are all the permutations of <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li>\n</ul>\n\n<p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p>\n\n<ul>\n\t<li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li>\n\t<li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li>\n\t<li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li>\n</ul>\n\n<p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p>\n\n<p>The replacement must be <strong><a href=\"http://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in place</a></strong> and use only constant extra memory.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [1,3,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,1]\n<strong>Output:</strong> [1,2,3]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,5]\n<strong>Output:</strong> [1,5,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/next-permutation/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Brute Force\n\n**Algorithm**\n\nIn this approach, we find out every possible permutation of list formed by the elements of the given array and find out the permutation which is\njust larger than the given one. But this one will be a very naive approach, since it requires us to find out every possible permutation\n which will take really long time and the implementation is complex.\n Thus, this approach is not acceptable at all. Hence, we move on directly to the correct approach.\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n!)$$. Total possible permutations is $$n!$$.\n* Space complexity : $$O(n)$$. Since an array will be used to store the permutations.\n<br />\n<br />\n\n---\n\n### Approach 2: Single Pass Approach\n\n**Algorithm**\n\nFirst, we observe that for any given sequence that is in descending order, no next larger permutation is possible.\n For example, no next permutation is possible for the following array:\n ```\n [9, 5, 4, 3, 1]\n ```\n\nWe need to find the first pair of two successive numbers $$a[i]$$ and $$a[i-1]$$, from the right, which satisfy\n $$a[i] > a[i-1]$$. Now, no rearrangements to the right of $$a[i-1]$$ can create a larger permutation since that subarray consists of numbers in descending order.\n Thus, we need to rearrange the numbers to the right of $$a[i-1]$$ including itself.\n\nNow, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number $$a[i-1]$$ with the number which is just larger than itself among the numbers lying to its right section, say $$a[j]$$.\n\n![ Next Permutation ](https://leetcode.com/media/original_images/31_nums_graph.png)\n\nWe swap the numbers $$a[i-1]$$ and $$a[j]$$. We now have the correct number at index $$i-1$$. But still the current permutation isn't the permutation\n    that we are looking for. We need the smallest permutation that can be formed by using the numbers only to the right of $$a[i-1]$$. Therefore, we need to place those\n     numbers in ascending order to get their smallest permutation.\n\nBut, recall that while scanning the numbers from the right, we simply kept decrementing the index\n      until we found the pair $$a[i]$$ and $$a[i-1]$$ where,  $$a[i] > a[i-1]$$. Thus, all numbers to the right of $$a[i-1]$$ were already sorted in descending order.\n      Furthermore, swapping $$a[i-1]$$ and $$a[j]$$ didn't change that order.\n      Therefore, we simply need to reverse the numbers following $$a[i-1]$$ to get the next smallest lexicographic permutation.\n\nThe following animation will make things clearer:\n\n![Next Permutation](https://leetcode.com/media/original_images/31_Next_Permutation.gif)\n\n<iframe src=\"https://leetcode.com/playground/Dm6PeACq/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Dm6PeACq\"></iframe>\n\n**Complexity Analysis**\n\nLet $n$ be the size of the `nums` array.\n\n- Time complexity: $O(n)$\n\n   The first `while` loop runs at most $n$ iterations, decrementing the variable `i` as it searches for the first decreasing element from the right. In the worst case, it checks all elements, so it takes $O(n)$ time.\n    \n   The second `while` loop also runs at most $n$ iterations, decrementing the variable `j` as it searches for the smallest element larger than `nums[i]`. Similarly, it can take $O(n)$ time.\n    \n   The `reverse` function is called on a portion of the array, from index `i + 1` to the end. In the worst case, this can cover the entire array, leading to a time complexity of $O(n)$.\n    \n   The `swap` function runs in constant time, $O(1)$, since it only exchanges two elements.\n    \n    Therefore, the overall time complexity is $O(n)$.\n\n- Space complexity: $O(1)$\n\n   The function operates in-place on the `nums` array, meaning no extra space is used for storing additional data.\n    \n   Only a few constant space variables (`i`, `j`, and `temp`) are used.\n    \n   The built-in `swap` and `reverse` functions do not require additional space beyond what is already present in the input array.\n\n    Hence, the space complexity is $O(1)$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nextPermutation(self, nums: List[int]) -> None:\n    n = len(nums)\n\n    # From back to front, find the first num < nums[i + 1]\n    i = n - 2\n    while i >= 0:\n      if nums[i] < nums[i + 1]:\n        break\n      i -= 1\n\n    # From back to front, find the first num > nums[i], swap it with nums[i]\n    if i >= 0:\n      for j in range(n - 1, i, -1):\n        if nums[j] > nums[i]:\n          nums[i], nums[j] = nums[j], nums[i]\n          break\n\n    def reverse(nums: List[int], l: int, r: int) -> None:\n      while l < r:\n        nums[l], nums[r] = nums[r], nums[l]\n        l += 1\n        r -= 1\n\n    # Reverse nums[i + 1..n - 1]\n    reverse(nums, i + 1, len(nums) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void nextPermutation(int[] nums) {\n    final int n = nums.length;\n\n    // From back to front, find the first num < nums[i + 1]\n    int i;\n    for (i = n - 2; i >= 0; --i)\n      if (nums[i] < nums[i + 1])\n        break;\n\n    // From back to front, find the first num > nums[i], swap it with nums[i]\n    if (i >= 0)\n      for (int j = n - 1; j > i; --j)\n        if (nums[j] > nums[i]) {\n          swap(nums, i, j);\n          break;\n        }\n\n    // Reverse nums[i + 1..n - 1]\n    reverse(nums, i + 1, n - 1);\n  }\n\n  private void reverse(int[] nums, int l, int r) {\n    while (l < r)\n      swap(nums, l++, r--);\n  }\n\n  private void swap(int[] nums, int i, int j) {\n    final int temp = nums[i];\n    nums[i] = nums[j];\n    nums[j] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void nextPermutation(vector<int>& nums) {\n    const int n = nums.size();\n\n    // From back to front, find the first num < nums[i + 1]\n    int i;\n    for (i = n - 2; i >= 0; --i)\n      if (nums[i] < nums[i + 1])\n        break;\n\n    // From back to front, find the first num > nums[i], swap it with nums[i]\n    if (i >= 0)\n      for (int j = n - 1; j > i; --j)\n        if (nums[j] > nums[i]) {\n          swap(nums[i], nums[j]);\n          break;\n        }\n\n    // Reverse nums[i + 1..n - 1]\n    reverse(nums, i + 1, n - 1);\n  }\n\n private:\n  void reverse(vector<int>& nums, int l, int r) {\n    while (l < r)\n      swap(nums[l++], nums[r--]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/31.html",
    "category": "Algorithms",
    "acceptance_rate": 42.81940122013106,
    "topics": [
      "Array",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 19774,
    "dislikes": 4917,
    "similar_questions": "[{\"title\": \"Permutations\", \"titleSlug\": \"permutations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutations II\", \"titleSlug\": \"permutations-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutation Sequence\", \"titleSlug\": \"permutation-sequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Palindrome Permutation II\", \"titleSlug\": \"palindrome-permutation-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Adjacent Swaps to Reach the Kth Smallest Number\", \"titleSlug\": \"minimum-adjacent-swaps-to-reach-the-kth-smallest-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 1793866, \"totalSubmissionRaw\": 4189379, \"acRate\": \"42.8%\"}",
    "title_pt": "Próxima Permutação",
    "description_pt": "<p>Uma <strong>permutação</strong> de um array de inteiros é um arranjo de seus membros em uma sequência ou ordem linear.</p>\n\n<ul>\n\t<li>Por exemplo, para <code>arr = [1,2,3]</code>, as seguintes são todas as permutações de <code>arr</code>: <code>[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]</code>.</li>\n</ul>\n\n<p>A <strong>próxima permutação</strong> de um array de inteiros é a próxima permutação lexicograficamente maior de seus inteiros. Mais formalmente, se todas as permutações do array forem ordenadas em um único contêiner de acordo com sua ordem lexicográfica, então a <strong>próxima permutação</strong> desse array é a permutação que a sucede no contêiner ordenado. Se tal arranjo não for possível, o array deve ser rearranjado na menor ordem possível (isto é, ordenado em ordem crescente).</p>\n\n<ul>\n\t<li>Por exemplo, a próxima permutação de <code>arr = [1,2,3]</code> é <code>[1,3,2]</code>.</li>\n\t<li>Da mesma forma, a próxima permutação de <code>arr = [2,3,1]</code> é <code>[3,1,2]</code>.</li>\n\t<li>Enquanto a próxima permutação de <code>arr = [3,2,1]</code> é <code>[1,2,3]</code> porque <code>[3,2,1]</code> não possui um rearranjo lexicograficamente maior.</li>\n</ul>\n\n<p>Dado um array de inteiros <code>nums</code>, <em>encontre a próxima permutação de</em> <code>nums</code>.</p>\n\n<p>A substituição deve ser <strong><a href=\"http://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in place</a></strong> e usar apenas memória extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> [1,3,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,1]\n<strong>Saída:</strong> [1,2,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,5]\n<strong>Saída:</strong> [1,5,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "32",
    "paidOnly": false,
    "title": "Longest Valid Parentheses",
    "titleSlug": "longest-valid-parentheses",
    "url": "https://leetcode.com/problems/longest-valid-parentheses",
    "description_url": "https://leetcode.com/problems/longest-valid-parentheses/description/",
    "description": "<p>Given a string containing just the characters <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>, return <em>the length of the longest valid (well-formed) parentheses </em><span data-keyword=\"substring-nonempty\"><em>substring</em></span>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;(()&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The longest valid parentheses substring is &quot;()&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;)()())&quot;\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest valid parentheses substring is &quot;()()&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;&quot;\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>s[i]</code> is <code>&#39;(&#39;</code>, or <code>&#39;)&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-valid-parentheses/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestValidParentheses(self, s: str) -> int:\n    s2 = ')' + s\n    # dp[i] := Length of longest valid parentheses substring of s2[1..i]\n    dp = [0] * len(s2)\n\n    for i in range(1, len(s2)):\n      if s2[i] == ')' and s2[i - dp[i - 1] - 1] == '(':\n        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2\n\n    return max(dp)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestValidParentheses(String s) {\n    final String s2 = \")\" + s;\n    // dp[i] := Length of longest valid parentheses substring of s2[1..i]\n    int dp[] = new int[s2.length()];\n\n    for (int i = 1; i < s2.length(); ++i)\n      if (s2.charAt(i) == ')' && s2.charAt(i - dp[i - 1] - 1) == '(')\n        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;\n\n    return Arrays.stream(dp).max().getAsInt();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestValidParentheses(string s) {\n    const string s2 = \")\" + s;\n    // dp[i] := Length of longest valid parentheses substring of s2[1..i]\n    vector<int> dp(s2.length());\n\n    for (int i = 1; i < s2.length(); ++i)\n      if (s2[i] == ')' && s2[i - dp[i - 1] - 1] == '(')\n        dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;\n\n    return *max_element(begin(dp), end(dp));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/32.html",
    "category": "Algorithms",
    "acceptance_rate": 36.12647915926324,
    "topics": [
      "String",
      "Dynamic Programming",
      "Stack"
    ],
    "hints": [],
    "likes": 12792,
    "dislikes": 432,
    "similar_questions": "[{\"title\": \"Valid Parentheses\", \"titleSlug\": \"valid-parentheses\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"897.7K\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 897654, \"totalSubmissionRaw\": 2484758, \"acRate\": \"36.1%\"}",
    "title_pt": "Parênteses Válidos Mais Longos",
    "description_pt": "<p>Dada uma string contendo apenas os caracteres <code>&#39;(&#39;</code> e <code>&#39;)&#39;</code>, retorne <em>o comprimento da mais longa substring de parênteses válidos (bem formada)</em><span data-keyword=\"substring-nonempty\"><em>substring</em></span>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;(()&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A mais longa substring de parênteses válidos é &quot;()&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;)()())&quot;\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> A mais longa substring de parênteses válidos é &quot;()()&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;&quot;\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>s[i]</code> é <code>&#39;(&#39;</code>, ou <code>&#39;)&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "33",
    "paidOnly": false,
    "title": "Search in Rotated Sorted Array",
    "titleSlug": "search-in-rotated-sorted-array",
    "url": "https://leetcode.com/problems/search-in-rotated-sorted-array",
    "description_url": "https://leetcode.com/problems/search-in-rotated-sorted-array/description/",
    "description": "<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p>\n\n<p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p>\n\n<p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p>\n\n<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0\n<strong>Output:</strong> 4\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3\n<strong>Output:</strong> -1\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [1], target = 0\n<strong>Output:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>All values of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is an ascending array that is possibly rotated.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/search-in-rotated-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def search(self, nums: List[int], target: int) -> int:\n    l = 0\n    r = len(nums) - 1\n\n    while l <= r:\n      m = (l + r) // 2\n      if nums[m] == target:\n        return m\n      if nums[l] <= nums[m]:  # nums[l..m] are sorted\n        if nums[l] <= target < nums[m]:\n          r = m - 1\n        else:\n          l = m + 1\n      else:  # nums[m..n - 1] are sorted\n        if nums[m] < target <= nums[r]:\n          l = m + 1\n        else:\n          r = m - 1\n\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int search(int[] nums, int target) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l <= r) {\n      final int m = (l + r) / 2;\n      if (nums[m] == target)\n        return m;\n      if (nums[l] <= nums[m]) { // nums[l..m] are sorted\n        if (nums[l] <= target && target < nums[m])\n          r = m - 1;\n        else\n          l = m + 1;\n      } else { // nums[m..n - 1] are sorted\n        if (nums[m] < target && target <= nums[r])\n          l = m + 1;\n        else\n          r = m - 1;\n      }\n    }\n\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int search(vector<int>& nums, int target) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l <= r) {\n      const int m = (l + r) / 2;\n      if (nums[m] == target)\n        return m;\n      if (nums[l] <= nums[m]) {  // nums[l..m] are sorted\n        if (nums[l] <= target && target < nums[m])\n          r = m - 1;\n        else\n          l = m + 1;\n      } else {  // nums[m..n - 1] are sorted\n        if (nums[m] < target && target <= nums[r])\n          l = m + 1;\n        else\n          r = m - 1;\n      }\n    }\n\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/33.html",
    "category": "Algorithms",
    "acceptance_rate": 42.66732039804531,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 27915,
    "dislikes": 1698,
    "similar_questions": "[{\"title\": \"Search in Rotated Sorted Array II\", \"titleSlug\": \"search-in-rotated-sorted-array-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum in Rotated Sorted Array\", \"titleSlug\": \"find-minimum-in-rotated-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Pour Water Between Buckets to Make Water Levels Equal\", \"titleSlug\": \"pour-water-between-buckets-to-make-water-levels-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.5M\", \"totalSubmission\": \"8.3M\", \"totalAcceptedRaw\": 3541834, \"totalSubmissionRaw\": 8301054, \"acRate\": \"42.7%\"}",
    "title_pt": "Buscar em Array Ordenado Rotacionado",
    "description_pt": "<p>Há um array de inteiros <code>nums</code> ordenado em ordem crescente (com valores <strong>distintos</strong>).</p>\n\n<p>Antes de ser passado para sua função, <code>nums</code> é <strong>possivelmente rotacionado</strong> em um índice de pivô desconhecido <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) de forma que o array resultante é <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>indexado em 0</strong>). Por exemplo, <code>[0,1,2,4,5,6,7]</code> pode ser rotacionado no índice de pivô <code>3</code> e se tornar <code>[4,5,6,7,0,1,2]</code>.</p>\n\n<p>Dado o array <code>nums</code> <strong>após</strong> a possível rotação e um inteiro <code>target</code>, retorne <em>o índice de </em><code>target</code><em> se ele estiver em </em><code>nums</code><em>, ou </em><code>-1</code><em> se ele não estiver em </em><code>nums</code>.</p>\n\n<p>Você deve escrever um algoritmo com complexidade de tempo <code>O(log n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [4,5,6,7,0,1,2], target = 0\n<strong>Saída:</strong> 4\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [4,5,6,7,0,1,2], target = 3\n<strong>Saída:</strong> -1\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1], target = 0\n<strong>Saída:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os valores de <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li><code>nums</code> é um array crescente que pode estar rotacionado.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "34",
    "paidOnly": false,
    "title": "Find First and Last Position of Element in Sorted Array",
    "titleSlug": "find-first-and-last-position-of-element-in-sorted-array",
    "url": "https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array",
    "description_url": "https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/",
    "description": "<p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p>\n\n<p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p>\n\n<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8\n<strong>Output:</strong> [3,4]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6\n<strong>Output:</strong> [-1,-1]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [], target = 0\n<strong>Output:</strong> [-1,-1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li>\n\t<li><code>nums</code> is a non-decreasing array.</li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def searchRange(self, nums: List[int], target: int) -> List[int]:\n    l = bisect_left(nums, target)\n    if l == len(nums) or nums[l] != target:\n      return -1, -1\n    r = bisect_right(nums, target) - 1\n    return l, r",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] searchRange(int[] nums, int target) {\n    final int l = firstGreaterEqual(nums, target);\n    if (l == nums.length || nums[l] != target)\n      return new int[] {-1, -1};\n    final int r = firstGreaterEqual(nums, target + 1) - 1;\n    return new int[] {l, r};\n  }\n\n  // Finds the first index l s.t A[l] >= target\n  // Returns A.length if can't find\n  private int firstGreaterEqual(int[] A, int target) {\n    int l = 0;\n    int r = A.length;\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (A[m] >= target)\n        r = m;\n      else\n        l = m + 1;\n    }\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> searchRange(vector<int>& nums, int target) {\n    const int l = lower_bound(begin(nums), end(nums), target) - begin(nums);\n    if (l == nums.size() || nums[l] != target)\n      return {-1, -1};\n    const int r = upper_bound(begin(nums), end(nums), target) - begin(nums) - 1;\n    return {l, r};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/34.html",
    "category": "Algorithms",
    "acceptance_rate": 46.592772104202076,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 21762,
    "dislikes": 572,
    "similar_questions": "[{\"title\": \"First Bad Version\", \"titleSlug\": \"first-bad-version\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Plates Between Candles\", \"titleSlug\": \"plates-between-candles\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Target Indices After Sorting Array\", \"titleSlug\": \"find-target-indices-after-sorting-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.6M\", \"totalSubmission\": \"5.7M\", \"totalAcceptedRaw\": 2637603, \"totalSubmissionRaw\": 5660985, \"acRate\": \"46.6%\"}",
    "title_pt": "Encontrar a Primeira e a Última Posição de um Elemento em um Array Ordenado",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> ordenado em ordem não decrescente, encontre a posição inicial e final de um determinado valor <code>target</code>.</p>\n\n<p>Se <code>target</code> não for encontrado no array, retorne <code>[-1, -1]</code>.</p>\n\n<p>Você deve&nbsp;escrever um algoritmo com complexidade de tempo <code>O(log n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [5,7,7,8,8,10], target = 8\n<strong>Saída:</strong> [3,4]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [5,7,7,8,8,10], target = 6\n<strong>Saída:</strong> [-1,-1]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> nums = [], target = 0\n<strong>Saída:</strong> [-1,-1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li>\n\t<li><code>nums</code> is a non-decreasing array.</li>\n\t<li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "35",
    "paidOnly": false,
    "title": "Search Insert Position",
    "titleSlug": "search-insert-position",
    "url": "https://leetcode.com/problems/search-insert-position",
    "description_url": "https://leetcode.com/problems/search-insert-position/description/",
    "description": "<p>Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p>\n\n<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,5,6], target = 5\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,5,6], target = 2\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,5,6], target = 7\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> contains <strong>distinct</strong> values sorted in <strong>ascending</strong> order.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/search-insert-position/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def searchInsert(self, nums: List[int], target: int) -> int:\n    l = 0\n    r = len(nums)\n\n    while l < r:\n      m = (l + r) // 2\n      if nums[m] == target:\n        return m\n      if nums[m] < target:\n        l = m + 1\n      else:\n        r = m\n\n    return l",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int searchInsert(int[] nums, int target) {\n    int l = 0;\n    int r = nums.length;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (nums[m] == target)\n        return m;\n      if (nums[m] < target)\n        l = m + 1;\n      else\n        r = m;\n    }\n\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int searchInsert(vector<int>& nums, int target) {\n    int l = 0;\n    int r = nums.size();\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (nums[m] == target)\n        return m;\n      if (nums[m] < target)\n        l = m + 1;\n      else\n        r = m;\n    }\n\n    return l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/35.html",
    "category": "Algorithms",
    "acceptance_rate": 48.78678338560816,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 17366,
    "dislikes": 814,
    "similar_questions": "[{\"title\": \"First Bad Version\", \"titleSlug\": \"first-bad-version\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Exceed Threshold Value I\", \"titleSlug\": \"minimum-operations-to-exceed-threshold-value-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.8M\", \"totalSubmission\": \"7.7M\", \"totalAcceptedRaw\": 3771667, \"totalSubmissionRaw\": 7730924, \"acRate\": \"48.8%\"}",
    "title_pt": "Posição de Inserção para Busca",
    "description_pt": "<p>Dado um array ordenado de inteiros distintos e um valor alvo, retorne o índice se o alvo for encontrado. Caso contrário, retorne o índice onde ele estaria se fosse inserido em ordem.</p>\n\n<p>Você deve&nbsp;escrever um algoritmo com complexidade de tempo <code>O(log n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,5,6], target = 5\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,5,6], target = 2\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,5,6], target = 7\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> contém valores <strong>distintos</strong> ordenados em ordem <strong>crescente</strong>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "36",
    "paidOnly": false,
    "title": "Valid Sudoku",
    "titleSlug": "valid-sudoku",
    "url": "https://leetcode.com/problems/valid-sudoku",
    "description_url": "https://leetcode.com/problems/valid-sudoku/description/",
    "description": "<p>Determine if a&nbsp;<code>9 x 9</code> Sudoku board&nbsp;is valid.&nbsp;Only the filled cells need to be validated&nbsp;<strong>according to the following rules</strong>:</p>\n\n<ol>\n\t<li>Each row&nbsp;must contain the&nbsp;digits&nbsp;<code>1-9</code> without repetition.</li>\n\t<li>Each column must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li>\n\t<li>Each of the nine&nbsp;<code>3 x 3</code> sub-boxes of the grid must contain the digits&nbsp;<code>1-9</code>&nbsp;without repetition.</li>\n</ol>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>A Sudoku board (partially filled) could be valid but is not necessarily solvable.</li>\n\t<li>Only the filled cells need to be validated according to the mentioned&nbsp;rules.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\" />\n<pre>\n<strong>Input:</strong> board = \n[[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]\n,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]\n,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]\n,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]\n,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> board = \n[[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]\n,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]\n,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]\n,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]\n,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Same as Example 1, except with the <strong>5</strong> in the top left corner being modified to <strong>8</strong>. Since there are two 8&#39;s in the top left 3x3 sub-box, it is invalid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit <code>1-9</code> or <code>&#39;.&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-sudoku/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isValidSudoku(self, board: List[List[str]]) -> bool:\n    seen = set()\n\n    for i in range(9):\n      for j in range(9):\n        c = board[i][j]\n        if c == '.':\n          continue\n        if c + '@row ' + str(i) in seen or \\\n           c + '@col ' + str(j) in seen or \\\n           c + '@box ' + str(i // 3) + str(j // 3) in seen:\n          return False\n        seen.add(c + '@row ' + str(i))\n        seen.add(c + '@col ' + str(j))\n        seen.add(c + '@box ' + str(i // 3) + str(j // 3))\n\n    return True",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isValidSudoku(char[][] board) {\n    Set<String> seen = new HashSet<>();\n\n    for (int i = 0; i < 9; ++i)\n      for (int j = 0; j < 9; ++j) {\n        if (board[i][j] == '.')\n          continue;\n        final char c = board[i][j];\n        if (!seen.add(c + \"@row\" + i) ||\n            !seen.add(c + \"@col\" + j) ||\n            !seen.add(c + \"@box\" + i / 3 + j / 3))\n          return false;\n      }\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isValidSudoku(vector<vector<char>>& board) {\n    unordered_set<string> seen;\n\n    for (int i = 0; i < 9; ++i)\n      for (int j = 0; j < 9; ++j) {\n        if (board[i][j] == '.')\n          continue;\n        const string c(1, board[i][j]);\n        if (!seen.insert(c + \"@row\" + to_string(i)).second ||\n            !seen.insert(c + \"@col\" + to_string(j)).second ||\n            !seen.insert(c + \"@box\" + to_string(i / 3) + to_string(j / 3))\n                 .second)\n          return false;\n      }\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/36.html",
    "category": "Algorithms",
    "acceptance_rate": 62.085950898707075,
    "topics": [
      "Array",
      "Hash Table",
      "Matrix"
    ],
    "hints": [],
    "likes": 11471,
    "dislikes": 1197,
    "similar_questions": "[{\"title\": \"Sudoku Solver\", \"titleSlug\": \"sudoku-solver\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check if Every Row and Column Contains All Numbers\", \"titleSlug\": \"check-if-every-row-and-column-contains-all-numbers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 1970057, \"totalSubmissionRaw\": 3173113, \"acRate\": \"62.1%\"}",
    "title_pt": "Sudoku Válido",
    "description_pt": "<p>Determine se um tabuleiro de Sudoku&nbsp;<code>9 x 9</code> é válido.&nbsp;Apenas as células preenchidas precisam ser validadas&nbsp;<strong>de acordo com as seguintes regras</strong>:</p>\n\n<ol>\n\t<li>Cada linha&nbsp;deve conter os dígitos&nbsp;<code>1-9</code> sem repetição.</li>\n\t<li>Cada coluna deve conter os dígitos&nbsp;<code>1-9</code>&nbsp;sem repetição.</li>\n\t<li>Cada uma das nove subcaixas&nbsp;<code>3 x 3</code> da grade deve conter os dígitos&nbsp;<code>1-9</code>&nbsp;sem repetição.</li>\n</ol>\n\n<p><strong>Nota:</strong></p>\n\n<ul>\n\t<li>Um tabuleiro de Sudoku (parcialmente preenchido) pode ser válido, mas não é necessariamente solucionável.</li>\n\t<li>Apenas as células preenchidas precisam ser validadas de acordo com as regras mencionadas.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\" />\n<pre>\n<strong>Entrada:</strong> board = \n[[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]\n,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]\n,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]\n,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]\n,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> board = \n[[&quot;8&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;]\n,[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;]\n,[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;]\n,[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;]\n,[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;]\n,[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Igual ao Exemplo 1, exceto que o <strong>5</strong> no canto superior esquerdo foi modificado para <strong>8</strong>. Como há dois 8&#39;s na subcaixa superior esquerda de 3x3, ele é inválido.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> é um dígito <code>1-9</code> ou <code>&#39;.&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "37",
    "paidOnly": false,
    "title": "Sudoku Solver",
    "titleSlug": "sudoku-solver",
    "url": "https://leetcode.com/problems/sudoku-solver",
    "description_url": "https://leetcode.com/problems/sudoku-solver/description/",
    "description": "<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p>\n\n<p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p>\n\n<ol>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li>\n\t<li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li>\n</ol>\n\n<p>The <code>&#39;.&#39;</code> character indicates empty cells.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Output:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Explanation:</strong>&nbsp;The input board is shown above and the only valid solution is shown below:\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png\" style=\"height:250px; width:250px\" />\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li>\n\t<li>It is <strong>guaranteed</strong> that the input board has only one solution.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sudoku-solver/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def solveSudoku(self, board: List[List[str]]) -> None:\n    def isValid(row: int, col: int, c: chr) -> bool:\n      for i in range(9):\n        if board[i][col] == c or \\\n           board[row][i] == c or \\\n           board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c:\n          return False\n      return True\n\n    def solve(s: int) -> bool:\n      if s == 81:\n        return True\n\n      i = s // 9\n      j = s % 9\n\n      if board[i][j] != '.':\n        return solve(s + 1)\n\n      for c in string.digits[1:]:\n        if isValid(i, j, c):\n          board[i][j] = c\n          if solve(s + 1):\n            return True\n          board[i][j] = '.'\n\n      return False\n\n    solve(0)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void solveSudoku(char[][] board) {\n    dfs(board, 0);\n  }\n\n  private boolean dfs(char[][] board, int s) {\n    if (s == 81)\n      return true;\n\n    final int i = s / 9;\n    final int j = s % 9;\n\n    if (board[i][j] != '.')\n      return dfs(board, s + 1);\n\n    for (char c = '1'; c <= '9'; ++c)\n      if (isValid(board, i, j, c)) {\n        board[i][j] = c;\n        if (dfs(board, s + 1))\n          return true;\n        board[i][j] = '.';\n      }\n\n    return false;\n  }\n\n  private boolean isValid(char[][] board, int row, int col, char c) {\n    for (int i = 0; i < 9; ++i)\n      if (board[i][col] == c || board[row][i] == c ||\n          board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)\n        return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void solveSudoku(vector<vector<char>>& board) {\n    solve(board, 0);\n  }\n\n private:\n  bool solve(vector<vector<char>>& board, int s) {\n    if (s == 81)\n      return true;\n\n    const int i = s / 9;\n    const int j = s % 9;\n\n    if (board[i][j] != '.')\n      return solve(board, s + 1);\n\n    for (char c = '1'; c <= '9'; ++c)\n      if (isValid(board, i, j, c)) {\n        board[i][j] = c;\n        if (solve(board, s + 1))\n          return true;\n        board[i][j] = '.';\n      }\n\n    return false;\n  }\n\n  bool isValid(vector<vector<char>>& board, int row, int col, char c) {\n    for (int i = 0; i < 9; ++i)\n      if (board[i][col] == c || board[row][i] == c ||\n          board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/37.html",
    "category": "Algorithms",
    "acceptance_rate": 63.76410818148523,
    "topics": [
      "Array",
      "Hash Table",
      "Backtracking",
      "Matrix"
    ],
    "hints": [],
    "likes": 10137,
    "dislikes": 292,
    "similar_questions": "[{\"title\": \"Valid Sudoku\", \"titleSlug\": \"valid-sudoku\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Unique Paths III\", \"titleSlug\": \"unique-paths-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"759.1K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 759063, \"totalSubmissionRaw\": 1190429, \"acRate\": \"63.8%\"}",
    "title_pt": "Resolutor de Sudoku",
    "description_pt": "<p>Escreva um programa para resolver um quebra-cabeça de Sudoku preenchendo as células vazias.</p>\n\n<p>Uma solução de sudoku deve satisfazer <strong>todas as seguintes regras</strong>:</p>\n\n<ol>\n\t<li>Cada um dos dígitos <code>1-9</code> deve ocorrer exatamente uma vez em cada linha.</li>\n\t<li>Cada um dos dígitos <code>1-9</code> deve ocorrer exatamente uma vez em cada coluna.</li>\n\t<li>Cada um dos dígitos <code>1-9</code> deve ocorrer exatamente uma vez em cada uma das 9 subcaixas <code>3x3</code> da grade.</li>\n</ol>\n\n<p>O caractere <code>&#39;.&#39;</code> indica células vazias.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png\" style=\"height:250px; width:250px\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;5&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;9&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;],[&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;3&quot;,&quot;.&quot;,&quot;.&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;6&quot;],[&quot;.&quot;,&quot;6&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;2&quot;,&quot;8&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;.&quot;,&quot;.&quot;,&quot;5&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;8&quot;,&quot;.&quot;,&quot;.&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Saída:</strong> [[&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;1&quot;,&quot;2&quot;],[&quot;6&quot;,&quot;7&quot;,&quot;2&quot;,&quot;1&quot;,&quot;9&quot;,&quot;5&quot;,&quot;3&quot;,&quot;4&quot;,&quot;8&quot;],[&quot;1&quot;,&quot;9&quot;,&quot;8&quot;,&quot;3&quot;,&quot;4&quot;,&quot;2&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;],[&quot;8&quot;,&quot;5&quot;,&quot;9&quot;,&quot;7&quot;,&quot;6&quot;,&quot;1&quot;,&quot;4&quot;,&quot;2&quot;,&quot;3&quot;],[&quot;4&quot;,&quot;2&quot;,&quot;6&quot;,&quot;8&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;9&quot;,&quot;1&quot;],[&quot;7&quot;,&quot;1&quot;,&quot;3&quot;,&quot;9&quot;,&quot;2&quot;,&quot;4&quot;,&quot;8&quot;,&quot;5&quot;,&quot;6&quot;],[&quot;9&quot;,&quot;6&quot;,&quot;1&quot;,&quot;5&quot;,&quot;3&quot;,&quot;7&quot;,&quot;2&quot;,&quot;8&quot;,&quot;4&quot;],[&quot;2&quot;,&quot;8&quot;,&quot;7&quot;,&quot;4&quot;,&quot;1&quot;,&quot;9&quot;,&quot;6&quot;,&quot;3&quot;,&quot;5&quot;],[&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;2&quot;,&quot;8&quot;,&quot;6&quot;,&quot;1&quot;,&quot;7&quot;,&quot;9&quot;]]\n<strong>Explicação:</strong>&nbsp;O tabuleiro de entrada é mostrado acima e a única solução válida é mostrada abaixo:\n\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png\" style=\"height:250px; width:250px\" />\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>board.length == 9</code></li>\n\t<li><code>board[i].length == 9</code></li>\n\t<li><code>board[i][j]</code> is a digit or <code>&#39;.&#39;</code>.</li>\n\t<li>É <strong>garantido</strong> que o tabuleiro de entrada tem apenas uma solução.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "38",
    "paidOnly": false,
    "title": "Count and Say",
    "titleSlug": "count-and-say",
    "url": "https://leetcode.com/problems/count-and-say",
    "description_url": "https://leetcode.com/problems/count-and-say/description/",
    "description": "<p>The <strong>count-and-say</strong> sequence is a sequence of digit strings defined by the recursive formula:</p>\n\n<ul>\n\t<li><code>countAndSay(1) = &quot;1&quot;</code></li>\n\t<li><code>countAndSay(n)</code> is the run-length encoding of <code>countAndSay(n - 1)</code>.</li>\n</ul>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" target=\"_blank\">Run-length encoding</a> (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string <code>&quot;3322251&quot;</code> we replace <code>&quot;33&quot;</code> with <code>&quot;23&quot;</code>, replace <code>&quot;222&quot;</code> with <code>&quot;32&quot;</code>, replace <code>&quot;5&quot;</code> with <code>&quot;15&quot;</code> and replace <code>&quot;1&quot;</code> with <code>&quot;11&quot;</code>. Thus the compressed string becomes <code>&quot;23321511&quot;</code>.</p>\n\n<p>Given a positive integer <code>n</code>, return <em>the </em><code>n<sup>th</sup></code><em> element of the <strong>count-and-say</strong> sequence</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">n = 4</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;1211&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<pre>\ncountAndSay(1) = &quot;1&quot;\ncountAndSay(2) = RLE of &quot;1&quot; = &quot;11&quot;\ncountAndSay(3) = RLE of &quot;11&quot; = &quot;21&quot;\ncountAndSay(4) = RLE of &quot;21&quot; = &quot;1211&quot;\n</pre>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">n = 1</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;1&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>This is the base case.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 30</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it iteratively?",
    "solution_url": "https://leetcode.com/problems/count-and-say/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countAndSay(self, n: int) -> str:\n    ans = '1'\n\n    for _ in range(n - 1):\n      nxt = ''\n      i = 0\n      while i < len(ans):\n        count = 1\n        while i + 1 < len(ans) and ans[i] == ans[i + 1]:\n          count += 1\n          i += 1\n        nxt += str(count) + ans[i]\n        i += 1\n      ans = nxt\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String countAndSay(int n) {\n    StringBuilder sb = new StringBuilder(\"1\");\n\n    while (--n > 0) {\n      StringBuilder next = new StringBuilder();\n      for (int i = 0; i < sb.length(); ++i) {\n        int count = 1;\n        while (i + 1 < sb.length() && sb.charAt(i) == sb.charAt(i + 1)) {\n          ++count;\n          ++i;\n        }\n        next.append(count).append(sb.charAt(i));\n      }\n      sb = next;\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string countAndSay(int n) {\n    string ans = \"1\";\n\n    while (--n) {\n      string next;\n      for (int i = 0; i < ans.length(); ++i) {\n        int count = 1;\n        while (i + 1 < ans.length() && ans[i] == ans[i + 1]) {\n          ++count;\n          ++i;\n        }\n        next += to_string(count) + ans[i];\n      }\n      ans = move(next);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/38.html",
    "category": "Algorithms",
    "acceptance_rate": 60.2661808361712,
    "topics": [
      "String"
    ],
    "hints": [
      "Create a helper function that maps an integer to pairs of its digits and their frequencies. For example, if you call this function with \"223314444411\", then it maps it to an array of pairs [[2,2], [3,2], [1,1], [4,5], [1, 2]].",
      "Create another helper function that takes the array of pairs and creates a new integer. For example, if you call this function with [[2,2], [3,2], [1,1], [4,5], [1, 2]], it should create \"22\"+\"23\"+\"11\"+\"54\"+\"21\" = \"2223115421\".",
      "Now, with the two helper functions, you can start with \"1\" and call the two functions alternatively n-1 times. The answer is the last integer you will obtain."
    ],
    "likes": 4714,
    "dislikes": 8824,
    "similar_questions": "[{\"title\": \"Encode and Decode Strings\", \"titleSlug\": \"encode-and-decode-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"String Compression\", \"titleSlug\": \"string-compression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1214001, \"totalSubmissionRaw\": 2014407, \"acRate\": \"60.3%\"}",
    "title_pt": "Conte e Diga",
    "description_pt": "<p>A sequência <strong>count-and-say</strong> é uma sequência de strings de dígitos definida pela fórmula recursiva:</p>\n\n<ul>\n\t<li><code>countAndSay(1) = &quot;1&quot;</code></li>\n\t<li><code>countAndSay(n)</code> é a codificação por comprimento de execução de <code>countAndSay(n - 1)</code>.</li>\n</ul>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Run-length_encoding\" target=\"_blank\">Codificação por comprimento de execução</a> (RLE) é um método de compressão de strings que funciona substituindo caracteres idênticos consecutivos (repetidos 2 ou mais vezes) pela concatenação do caractere e do número que marca a contagem dos caracteres (comprimento da execução). Por exemplo, para comprimir a string <code>&quot;3322251&quot;</code> substituímos <code>&quot;33&quot;</code> por <code>&quot;23&quot;</code>, substituímos <code>&quot;222&quot;</code> por <code>&quot;32&quot;</code>, substituímos <code>&quot;5&quot;</code> por <code>&quot;15&quot;</code> e substituímos <code>&quot;1&quot;</code> por <code>&quot;11&quot;</code>. Assim, a string comprimida se torna <code>&quot;23321511&quot;</code>.</p>\n\n<p>Dado um inteiro positivo <code>n</code>, retorne <em>o </em><code>n<sup>th</sup></code><em> elemento da sequência <strong>count-and-say</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">n = 4</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;1211&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<pre>\ncountAndSay(1) = &quot;1&quot;\ncountAndSay(2) = RLE de &quot;1&quot; = &quot;11&quot;\ncountAndSay(3) = RLE de &quot;11&quot; = &quot;21&quot;\ncountAndSay(4) = RLE de &quot;21&quot; = &quot;1211&quot;\n</pre>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">n = 1</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;1&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Este é o caso base.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 30</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria resolvê-lo iterativamente?",
    "hints_pt": [
      "Dica 1: Crie uma função auxiliar que mapeie um inteiro para pares de seus dígitos e suas frequências. Por exemplo, se você chamar essa função com \"223314444411\", então ela o mapeia para um array de pares [[2,2], [3,2], [1,1], [4,5], [1, 2]].",
      "Dica 2: Crie outra função auxiliar que receba o array de pares e crie um novo inteiro. Por exemplo, se você chamar essa função com [[2,2], [3,2], [1,1], [4,5], [1, 2]], ela deve criar \"22\"+\"23\"+\"11\"+\"54\"+\"21\" = \"2223115421\".",
      "Dica 3: Agora, com as duas funções auxiliares, você pode começar com \"1\" e chamar as duas funções alternadamente n-1 vezes. A resposta é o último inteiro que você obterá."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "39",
    "paidOnly": false,
    "title": "Combination Sum",
    "titleSlug": "combination-sum",
    "url": "https://leetcode.com/problems/combination-sum",
    "description_url": "https://leetcode.com/problems/combination-sum/description/",
    "description": "<p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p>\n\n<p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the <span data-keyword=\"frequency-array\">frequency</span> of at least one of the chosen numbers is different.</p>\n\n<p>The test cases are generated such that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> candidates = [2,3,6,7], target = 7\n<strong>Output:</strong> [[2,2,3],[7]]\n<strong>Explanation:</strong>\n2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> candidates = [2,3,5], target = 8\n<strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> candidates = [2], target = 1\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= candidates.length &lt;= 30</code></li>\n\t<li><code>2 &lt;= candidates[i] &lt;= 40</code></li>\n\t<li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li>\n\t<li><code>1 &lt;= target &lt;= 40</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/combination-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, target: int, path: List[int]) -> None:\n      if target < 0:\n        return\n      if target == 0:\n        ans.append(path.clone())\n        return\n\n      for i in range(s, len(candidates)):\n        path.append(candidates[i])\n        dfs(i, target - candidates[i], path)\n        path.pop()\n\n    candidates.sort()\n    dfs(0, target, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> combinationSum(int[] candidates, int target) {\n    List<List<Integer>> ans = new ArrayList<>();\n\n    Arrays.sort(candidates);\n    dfs(0, candidates, target, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int s, int[] candidates, int target, List<Integer> path,\n                   List<List<Integer>> ans) {\n    if (target < 0)\n      return;\n    if (target == 0) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = s; i < candidates.length; ++i) {\n      path.add(candidates[i]);\n      dfs(i, candidates, target - candidates[i], path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> combinationSum(vector<int>& candidates, int target) {\n    vector<vector<int>> ans;\n\n    sort(begin(candidates), end(candidates));\n    dfs(candidates, 0, target, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& A, int s, int target, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (target < 0)\n      return;\n    if (target == 0) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = s; i < A.size(); ++i) {\n      path.push_back(A[i]);\n      dfs(A, i, target - A[i], move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/39.html",
    "category": "Algorithms",
    "acceptance_rate": 74.42300236762577,
    "topics": [
      "Array",
      "Backtracking"
    ],
    "hints": [],
    "likes": 19782,
    "dislikes": 466,
    "similar_questions": "[{\"title\": \"Letter Combinations of a Phone Number\", \"titleSlug\": \"letter-combinations-of-a-phone-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Combination Sum II\", \"titleSlug\": \"combination-sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Combinations\", \"titleSlug\": \"combinations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Combination Sum III\", \"titleSlug\": \"combination-sum-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Factor Combinations\", \"titleSlug\": \"factor-combinations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Combination Sum IV\", \"titleSlug\": \"combination-sum-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Number of Ways to Make the Sum\", \"titleSlug\": \"the-number-of-ways-to-make-the-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"3.4M\", \"totalAcceptedRaw\": 2510874, \"totalSubmissionRaw\": 3373800, \"acRate\": \"74.4%\"}",
    "title_pt": "Soma de Combinação",
    "description_pt": "<p>Dado um array de inteiros <strong>distintos</strong> <code>candidates</code> e um inteiro alvo <code>target</code>, retorne <em>uma lista de todas as <strong>combinações únicas</strong> de </em><code>candidates</code><em> em que os números escolhidos somam </em><code>target</code><em>.</em> Você pode retornar as combinações em <strong>qualquer ordem</strong>.</p>\n\n<p>O <strong>mesmo</strong> número pode ser escolhido de <code>candidates</code> um <strong>número ilimitado de vezes</strong>. Duas combinações são únicas se a <span data-keyword=\"frequency-array\">frequência</span> de pelo menos um dos números escolhidos for diferente.</p>\n\n<p>Os casos de teste são gerados de modo que o número de combinações únicas que somam <code>target</code> seja menor que <code>150</code> combinações para a entrada fornecida.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candidates = [2,3,6,7], target = 7\n<strong>Saída:</strong> [[2,2,3],[7]]\n<strong>Explicação:</strong>\n2 e 3 são candidatos, e 2 + 2 + 3 = 7. Observe que 2 pode ser usado várias vezes.\n7 é um candidato, e 7 = 7.\nEstas são as únicas duas combinações.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candidates = [2,3,5], target = 8\n<strong>Saída:</strong> [[2,2,2,2],[2,3,3],[3,5]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candidates = [2], target = 1\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= candidates.length &lt;= 30</code></li>\n\t<li><code>2 &lt;= candidates[i] &lt;= 40</code></li>\n\t<li>Todos os elementos de <code>candidates</code> são <strong>distintos</strong>.</li>\n\t<li><code>1 &lt;= target &lt;= 40</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "40",
    "paidOnly": false,
    "title": "Combination Sum II",
    "titleSlug": "combination-sum-ii",
    "url": "https://leetcode.com/problems/combination-sum-ii",
    "description_url": "https://leetcode.com/problems/combination-sum-ii/description/",
    "description": "<p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p>\n\n<p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p>\n\n<p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8\n<strong>Output:</strong> \n[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> candidates = [2,5,2,1,2], target = 5\n<strong>Output:</strong> \n[\n[1,2,2],\n[5]\n]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li>\n\t<li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li>\n\t<li><code>1 &lt;= target &lt;= 30</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/combination-sum-ii/solutions/",
    "solution": "[TOC]  \n\n## Solution\n\n---\n\n### Overview\n\nThis is one of the problems in the series of combination sums. All these problems can be solved with the same backtracking algorithm.\n\nWe recommend trying these similar problems before tackling this one: [Combination Sum](https://leetcode.com/problems/combination-sum/description/) and [Combination Sum III](https://leetcode.com/problems/combination-sum-iii/description/), which are arguably easier and one can tweak the solution a bit to solve this problem.\n\nWe also listed some follow-up problems at the end of the article if you are interested in exploring the bactracking algorithm further.\n\n---\n\n### Approach: Backtracking\n\n#### Intuition\n\nIn this problem, we need to generate unique combinations with the given sum value. In the worst case, we might need to generate the sum of all combinations in the array. Backtracking can be effectively used to generate all the possible combinations recursively. Backtracking incrementally builds candidates to the solutions and abandons a candidate (backtracks) as soon as it determines that this candidate can't lead to a final solution. For example, in the given problem, we can discard the candidate solution when it exceeds the sum value, provided the array contains non-negative values. Refer to this [backtracking explore card](https://leetcode.com/explore/learn/card/recursion-ii/472/backtracking/2654/) to read more about backtracking.\n\nUsing backtracking, we could incrementally build the combinations. When we find the current combination is not valid, we backtrack and try another option. For the first option, we add the current array element to the current combination array and move this combination to the next index recursively. Similarly, for the second option, we remove the element from the current combination array and move this combination to the next index. Therefore, for every index, we explored two possibilities of including and excluding that value and calculated the combination sum of the maintained combination array. If the desired sum is reached, we can append the list to the answer list. To demonstrate the idea, we showcase how it works with a concrete example in the following tree:\n\n![fig](../Figures/40/40.png)\n\nAre there any optimizations to reduce the backtracking calls? Since we need to return unique combinations, we can group equal values of the array together. The simplest way to group all elements together is by sorting them. Now, suppose the frequency of an element is `freq`, and you need to make backtracking calls for all its possible frequencies between `0` and `freq`, then we can simply pick them from the beginning of its group in the sorted array.\n\n#### Algorithm\n\n- Create a list `list` to store all the unique combinations that sum up to the target.\n- Sort the `candidates` array to handle duplicates and facilitate the backtracking process.\n- Call the `backtrack` function with the following parameters:\n  - `answer`: List to store the final combinations.\n  - `tempList`: Temporary list to store the current combination.\n  - `candidates`: Input array of numbers.\n  - `totalLeft`: Remaining sum to reach the target.\n  - `index`: Starting index for the current recursion.\n\n- Within the `backtrack` function:\n  - If `totalLeft` is less than 0, return immediately (invalid path).\n  - If `totalLeft` equals 0:\n    - Add a copy of `tempList` to `answer` (valid combination found).\n  - Otherwise:\n    - Iterate over `candidates` starting from `index`:\n      - Skip duplicate numbers by checking if `candidates[i] == candidates[i - 1]` for `i > index`.\n      - Add `candidates[i]` to `tempList`.\n      - Recursively call `backtrack` with:\n        - Updated `totalLeft` reduced by `candidates[i]`.\n        - Updated `index` as `i + 1` to avoid reusing the same element.\n      - Remove the last element from `tempList` to backtrack and explore other possibilities.\n\n- Return `list` containing all unique combinations after the recursive calls complete.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/SGfPMJBF/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"SGfPMJBF\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of $candidates$ in the array.\n\n- Time complexity: $O(2^N)$\n\n    In the worst case, our algorithm will exhaust all possible combinations from the input array. Again, in the worst case, let us assume that each number is unique. The number of combinations for an array of size $N$ would be $2^N$, i.e. each number is included or excluded in a combination. \n    \n    Additionally, it takes $O(N)$ time to build a counter table out of the input array.\n    \n    Therefore, the overall time complexity of the algorithm is dominated by the backtracking process, which is $O(2^N)$.\n\n    You must think about how the solution passes the test cases when the value of $N$ goes up to 100. [Pruning](https://en.wikipedia.org/wiki/Decision_tree_pruning) is the process of writing some additional conditions within our recursion code that help us to reduce the size of our recursion trees by removing redundant sections. For example, in this problem, the maximum value of any `candidates` element is given by 50, whereas the maximum `target` value is 30. So, we can stop the recursion when the value of candidates exceeds the `target` value. Sorting the array is another way to prune the recursion tree. Checkout the image for an explanation:\n\n    ![fig](../Figures/40/image.png)\n   \n- Space complexity: $O(N)$\n   \n    We first create a `tempList`, which in the worst case will consume $O(N)$ space to keep track of the combinations. In addition, we apply recursion in the algorithm, which will incur additional memory consumption in the function call stack. In the worst case, the stack will pile up to $O(N)$ space.\n\n    To sum up, the overall space complexity of the algorithm is $O(N)$.\n\n    Note: we did not take into account the space needed to hold the final results of the combination in the above analysis.\n\n---\n\nHere are a series of problems you can solve, with some tweaks of the backtracking algorithm presented in this article.\n\n[Subsets](https://leetcode.com/problems/subsets/description/)\n[Subsets II](https://leetcode.com/problems/subsets-ii/description/)\n[Permutations](https://leetcode.com/problems/permutations/description/)\n[Permutations II](https://leetcode.com/problems/permutations-ii/description/)\n[Combinations](https://leetcode.com/problems/combinations/description/)\n[Combination Sum](https://leetcode.com/problems/combination-sum/description/)\n[Combination Sum III](https://leetcode.com/problems/combination-sum-iii/description/)\n[Palindrome Partition](https://leetcode.com/problems/palindrome-partitioning/description/)\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, target: int, path: List[int]) -> None:\n      if target < 0:\n        return\n      if target == 0:\n        ans.append(path.copy())\n        return\n\n      for i in range(s, len(candidates)):\n        if i > s and candidates[i] == candidates[i - 1]:\n          continue\n        path.append(candidates[i])\n        dfs(i + 1, target - candidates[i], path)\n        path.pop()\n\n    candidates.sort()\n    dfs(0, target, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> combinationSum2(int[] candidates, int target) {\n    List<List<Integer>> ans = new ArrayList<>();\n\n    Arrays.sort(candidates);\n    dfs(0, candidates, target, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int s, int[] candidates, int target, List<Integer> path,\n                   List<List<Integer>> ans) {\n    if (target < 0)\n      return;\n    if (target == 0) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = s; i < candidates.length; ++i) {\n      if (i > s && candidates[i] == candidates[i - 1])\n        continue;\n      path.add(candidates[i]);\n      dfs(i + 1, candidates, target - candidates[i], path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {\n    vector<vector<int>> ans;\n\n    sort(begin(candidates), end(candidates));\n    dfs(candidates, 0, target, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& A, int s, int target, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (target < 0)\n      return;\n    if (target == 0) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = s; i < A.size(); ++i) {\n      if (i > s && A[i] == A[i - 1])\n        continue;\n      path.push_back(A[i]);\n      dfs(A, i + 1, target - A[i], move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/40.html",
    "category": "Algorithms",
    "acceptance_rate": 57.50024604208708,
    "topics": [
      "Array",
      "Backtracking"
    ],
    "hints": [],
    "likes": 11533,
    "dislikes": 341,
    "similar_questions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1367127, \"totalSubmissionRaw\": 2377599, \"acRate\": \"57.5%\"}",
    "title_pt": "Soma de Combinações II",
    "description_pt": "<p>Dada uma coleção de números candidatos (<code>candidates</code>) e um número alvo (<code>target</code>), encontre todas as combinações únicas em <code>candidates</code>&nbsp;em que a soma dos números candidatos seja igual a <code>target</code>.</p>\n\n<p>Cada número em <code>candidates</code>&nbsp;pode ser usado apenas <strong>uma vez</strong> na combinação.</p>\n\n<p><strong>Nota:</strong>&nbsp;O conjunto de soluções não deve conter combinações duplicadas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candidates = [10,1,2,7,6,1,5], target = 8\n<strong>Saída:</strong> \n[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candidates = [2,5,2,1,2], target = 5\n<strong>Saída:</strong> \n[\n[1,2,2],\n[5]\n]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li>\n\t<li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li>\n\t<li><code>1 &lt;= target &lt;= 30</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "41",
    "paidOnly": false,
    "title": "First Missing Positive",
    "titleSlug": "first-missing-positive",
    "url": "https://leetcode.com/problems/first-missing-positive",
    "description_url": "https://leetcode.com/problems/first-missing-positive/description/",
    "description": "<p>Given an unsorted integer array <code>nums</code>. Return the <em>smallest positive integer</em> that is <em>not present</em> in <code>nums</code>.</p>\n\n<p>You must implement an algorithm that runs in <code>O(n)</code> time and uses <code>O(1)</code> auxiliary space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,0]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The numbers in the range [1,2] are all in the array.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,4,-1,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 1 is in the array but 2 is missing.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [7,8,9,11,12]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The smallest positive integer 1 is missing.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/first-missing-positive/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nThe task is to find the smallest positive integer that is not present in `nums`.\n\nNote that positive integers are greater than zero.\n\nLet's discuss the two main cases:\n\n**1. No Missing Integer in `nums`:**\n\n| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |\n|---|---|---|---|---|---|---|---|---|\n\n`nums` contains `9` elements. The smallest missing positive integer is `10`.\n\nFor an array of length `n`, if the array contains all of the integers in the range `1` to `n`, the smallest missing positive integer is `n + 1`.\n\n**2. Missing Integer in `nums`:**\n\n|-10 | 1 | 2 | 2 | 3 | 4 | 6 | 6 | 8 |\n|----|---|---|---|---|---|---|---|---|\n\n`nums` contains `9` elements. The smallest missing positive integer is `5`.\n\nFor an array of length `n`, if the array does not contain all of the integers in the range `1` to `n`, the smallest missing positive integer is the first integer missing from that range.\n\nLet's also discuss the constraints:\n\n> You must implement an algorithm that runs in $O(n)$ time and uses $O(1)$ auxiliary space.\n\n**1. Time Complexity:**\n\nHint number three reminds us that $O(2n) = O(n)$. While we know that one does not equal two, $O$ notation describes an algorithm's limiting behavior as the input size grows toward infinity.\n\n**2. Space Complexity:**\n\nThe optimized approaches in this article use in-place solutions. Does in-place mean a constant space complexity? By [definition](https://en.wikipedia.org/wiki/In-place_algorithm), an in-place algorithm transforms the input using no auxiliary data structures proportional to the input size. An in-place algorithm does not necessarily mean constant space complexity; for example, an in-place recursive algorithm uses the recursion stack, so the space is not constant.\n\nThe problem specifically asks us to use constant *auxiliary* space, so in-place solutions meet this criterion.\n\n---\n\n### Approach 1: Boolean Array\n\n#### Intuition\n\nWe can solve the problem by iterating through the numbers `1` to `n`, and use linear search to determine whether each number is in the array. The first number we cannot find is the smallest missing integer. This approach would result in a quadratic time complexity.\n\nWe need to determine whether an element is in the array in constant time. Array indexing provides constant lookup time. We need to check the existence of a relatively small range of values, positive numbers between `1` and `n`, so we can use an array like a hash table by using the index as a key and the value as a presence indicator. The default value is `false`, which represents a missing number, and we set the value to `true` for keys that exist in `nums`. Numbers not in the range `1` to `n` are not relevant in the search for the first missing positive, so we do not mark them in the `seen` array.\n\nTo solve the problem, we can create an array of size `n + 1`. For each positive number less than `n` in `nums`, we set `seen[num]` to `true`. Then, we iterate through the integers `1` to `n` and return the first number that is not marked as seen in the array. If the array contains all of the elements `1` to `n`, we return `n + 1`.\n\n> **Note:** This approach does not meet the problem constraint of solving the problem using constant auxiliary space. It is included to make the solution accessible, and it can provide valuable background for solving the problem within the space constraints. Other approaches that do not meet the time and/or space constraints are not included as they are less relevant to understanding the following approaches.\n\n#### Algorithm\n\n1. Initialize a variable `n` to the length of `nums`.\n\n2. Initialize an array `seen` to size `n + 1`.\n\n3. Mark the elements in `nums` as seen in the array `seen`.\n\n    - For each `num` in `nums`, if `num` is greater than `0` and less than or equal to `n`, set `seen[num]` to `true`.\n\n4. Find the smallest missing positive number:\n\n    - For `i` from `1` to `n`, If `seen[i]` is not `true`, return `i`, the smallest missing integer.\n\n5. If `seen` contains all elements `1` to `n`, return `n + 1` as the smallest missing positive number.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ASLfPBW8/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"ASLfPBW8\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of `nums`.\n\n* Time complexity: $O(n)$\n\n    Marking the values from `nums` in `seen` takes $O(n)$.\n\n    We check for values `1` to `n` in `seen`, which takes $O(n)$.\n\n    The total time complexity will be $O(2n)$, which we can simplify to $O(n)$.\n\n* Space complexity: $O(n)$\n\n    We initialize the array `seen`, which is size `n + 1`, so the space complexity is $O(n)$.\n\n---\n\n### Approach 2: Index as a Hash Key\n\n#### Intuition\n\n**Data Clean Up**\n\nOur search for the first missing positive focuses on the elements with values `1` through `n`. Negative numbers, zeros, and numbers larger than `n` are not relevant. Let's replace all these with `1`s. \n\n![max_first](../Figures/41/41_replace.png)\n\nTo ensure that the first missing positive is not `1`, we also have to track whether `1` exists in the original array.\n\n**Solving In-Place**\n\nNow we have an array that contains only positive numbers in a range from `1` to `n`, and the goal is to find the first missing positive in linear time and constant auxiliary space. \n\nIn the above approach, using the `seen` array introduced extra space. We can utilize `nums` itself to track which positive integers occur in the array since the range of numbers we have now is the same as the length of the array. We can use the index as a hash key for a positive number, and the sign of the element as a presence indicator.\n\nFor example, the negative sign of `nums[5]` means that the number `5` is present in `nums`. The positive sign of `nums[6]` means that the number `6` is not present (missing) in `nums`.\n\n![max_first](../Figures/41/41_true_solution.png)\n\nTo determine the smallest missing positive, we traverse the array, check each element value `value`, and change the sign of element `nums[value]` to negative to mark the number `value` as present in `nums`. We must be careful with duplicates and ensure that the sign is changed only once.\n\n> **Interview Tip: In-place Algorithms**\n>\n> This approach modifies the input by changing values of `nums`. In-place algorithms overwrite the input to save space, but sometimes this can cause problems.\n>\n> Here are a couple of situations where an in-place algorithm might not be suitable.\n>\n> 1. The algorithm needs to run in a multi-threaded environment, without exclusive access to the array. Other threads might need to read the array too, and might not expect it to be modified.\n>\n> 2. Even if there is only a single thread, or the algorithm has exclusive access to the array while running, the array might need to be reused later or by another thread once the lock has been released.\n>\n> In an interview, you should always check whether the interviewer minds you overwriting the input. Be ready to explain the pros and cons of doing so if asked!\n\n#### Algorithm\n\n1. Initialize a variable `n` to the length of `nums`, and a boolean `contains1` to `false`.\n\n2. Traverse `nums`, check whether `1` occurs, and replace negative numbers, zeros, and numbers larger than `n` with `1`. For each element in nums:\n\n    - If the element equals `1`, set `contains1` to `true`.\n    - If the element is less than or equal to `0` or greater than `n`, replace it with `1`.\n\n3. If the original `nums` array does not contain `1`, return `1`.\n\n4. Traverse `nums` using a `for` loop from `i` equals `0` to `n`. When `value` is encountered, flip the sign of the number at index `value` to negative to indicate that it is present in the array. Use absolute value to prevent duplicate occurrences of `value` from flipping the sign back to positive.\n    - Set an integer `value` to the absolute value of `nums[i]`.\n    - If `value` equals `n`, we use index `0` to save information about the presence of the number `n` since index `n` is not available. Set `nums[0]` to the negative of the absolute value of `nums[0]`.\n    - Otherwise, we use index `value` to store information about the presence of the number `value`. Set `nums[value]` to the negative of the absolute value of `nums[value]`.\n\n5. Find the smallest missing positive number:\n\n    - Iterate through the integers `1` to `n` using iterator `i`. If `nums[i]` is positive, return `i`.\n\n6. If `nums[0]` is greater than `0` return `n`.\n\n7. If `nums` contains all elements `1` to `n`, return `n + 1` as the smallest missing positive number.\n\n!?!../Documents/41_LIS.json:1000,589!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/PppX77uq/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"PppX77uq\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of `nums`,\n\n* Time complexity: $O(n)$\n\n    We traverse `nums` using a `for` loop three separate times, so the time complexity is $O(n)$.\n\n* Space complexity: $O(n)$\n\n    We modify the array `nums` and use it to determine the answer, so the space complexity is $O(n)$.\n\n    `nums` is the input array, so the *auxiliary* space used is $O(1)$.\n\n---\n\n### Approach 3: Cycle Sort\n\n#### Intuition\n\nIn the first approach, we discussed that we can solve the problem by iterating through the numbers `1` to `n` and searching for each in the array. If `nums` were sorted, this search process could be done in linear time. The built-in sorting functions in most major languages use linear or logarithmic auxiliary space. We need a way to sort the array in-place, in constant time.\n\nThe numbers we need to check for are in the range `1` to `n`, so we can utilize [cycle sort](https://en.wikipedia.org/wiki/Cycle_sort). Cycle sort is a sorting algorithm that can sort a given sequence in a range from `a` to `n` by putting each element at the index that corresponds to its value.\n\n`nums` is a zero-indexed array, so an element with the value `x` will be located at index `x - 1`. For example, `1` goes at index `0` in the array, `2` goes at index `1`, and `100` goes at index `99`. \n\nFor each element `x` in `nums`, if it is a positive integer between `1` and `n`, we place it at index `nums[x - 1]`. Elements smaller than `1` or larger than `n` will reside at indexes that do not have a corresponding value in `nums`.\n\nThen, to determine the smallest positive integer, we iterate through `nums`, and return the first element that is not equal to its index plus one.\n\nIf we iterate through the whole sorted array without returning a value, the array consists of the sequence of numbers `1` through `n`, so we return `n + 1`.\n\n> **Notes:** \n>   - This approach modifies the input. It changes the order of `nums`, but not the values of `nums`. In-place algorithms overwrite the input to save space, but sometimes this can cause problems. Always check with your interviewer before modifying the input.\n>\n>   - We use a simplified version of cycle sort because it is not a problem if the duplicate of a value is not in the correct position.\n\n#### Algorithm\n\n1. Initialize a variable `n` to the length of `nums`.\n\n2. Use cycle sort to place positive elements smaller than `n` at the correct index.\n\n    - Initialize a variable `i` to `0`.\n    - Iterate through the elements in `nums`:\n        - Set a variable `correctIdx` to `nums[i] - 1`.\n        - If the `nums[i]` is greater than zero, less than or equal to `n`, and does not equal `nums[correctIdx]`, swap the element at `nums[i]` with the element at `nums[correctIdx]`.\n        - Otherwise, increment `i`.\n\n3. Iterate through sorted `nums` and return the smallest missing positive number.\n\n    - For each element in `nums`, if `nums[i]` does not equal `i + 1`, return `i + 1`, the smallest missing positive number.\n\n4. Return `n + 1`, the smallest missing positive number when each number in `nums` is in the correct position.\n\n!?!../Documents/41/41_slideshow.json:960,540!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/efsbaqYc/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"efsbaqYc\"></iframe>\n\n> **Note:** The variable `correctIdx` is included in the Python3 and Java implementations for readability. The C++ version directly uses `nums[i] - 1` to prevent integer overflow.\n\n#### Complexity Analysis\n\nLet $n$ be the length of `nums`.\n\n* Time complexity: $O(n)$\n\n    We loop through the elements in `nums` once, swapping elements to sort the array. Swapping takes constant time. Sorting `nums` using cycle sort takes $O(n)$ time. \n    \n    Iterating through the sorted array and finding the first missing positive can take up to $O(n)$. \n    \n    The total time complexity is $O(2n)$, which simplifies to $O(n)$.\n\n\n* Space complexity: $O(n)$\n\n    We modify the array `nums` and use it to determine the answer, so the space complexity is $O(n)$.\n\n    `nums` is the input array, so the *auxiliary* space used is $O(1)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def firstMissingPositive(self, nums: List[int]) -> int:\n    n = len(nums)\n\n    # Correct slot:\n    # nums[i] = i + 1\n    # nums[i] - 1 = i\n    # nums[nums[i] - 1] = nums[i]\n    for i in range(n):\n      while nums[i] > 0 and nums[i] <= n and nums[nums[i] - 1] != nums[i]:\n        nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]\n\n    for i, num in enumerate(nums):\n      if num != i + 1:\n        return i + 1\n\n    return n + 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int firstMissingPositive(int[] nums) {\n    final int n = nums.length;\n\n    // Correct slot:\n    // nums[i] = i + 1\n    // nums[i] - 1 = i\n    // nums[nums[i] - 1] = nums[i]\n    for (int i = 0; i < n; ++i)\n      while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1])\n        swap(nums, i, nums[i] - 1);\n\n    for (int i = 0; i < n; ++i)\n      if (nums[i] != i + 1)\n        return i + 1;\n\n    return n + 1;\n  }\n\n  private void swap(int[] nums, int i, int j) {\n    final int temp = nums[i];\n    nums[i] = nums[j];\n    nums[j] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int firstMissingPositive(vector<int>& nums) {\n    const int n = nums.size();\n\n    // Correct slot:\n    // nums[i] = i + 1\n    // nums[i] - 1 = i\n    // nums[nums[i] - 1] = nums[i]\n    for (int i = 0; i < n; ++i)\n      while (nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1])\n        swap(nums[i], nums[nums[i] - 1]);\n\n    for (int i = 0; i < n; ++i)\n      if (nums[i] != i + 1)\n        return i + 1;\n\n    return n + 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/41.html",
    "category": "Algorithms",
    "acceptance_rate": 40.94907070242401,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [
      "Think about how you would solve the problem in non-constant space.  Can you apply that logic to the existing space?",
      "We don't care about duplicates or non-positive integers",
      "Remember that O(2n) = O(n)"
    ],
    "likes": 17509,
    "dislikes": 1920,
    "similar_questions": "[{\"title\": \"Missing Number\", \"titleSlug\": \"missing-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Duplicate Number\", \"titleSlug\": \"find-the-duplicate-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All Numbers Disappeared in an Array\", \"titleSlug\": \"find-all-numbers-disappeared-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Couples Holding Hands\", \"titleSlug\": \"couples-holding-hands\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Smallest Number in Infinite Set\", \"titleSlug\": \"smallest-number-in-infinite-set\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Integers to Choose From a Range I\", \"titleSlug\": \"maximum-number-of-integers-to-choose-from-a-range-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Missing Non-negative Integer After Operations\", \"titleSlug\": \"smallest-missing-non-negative-integer-after-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Integers to Choose From a Range II\", \"titleSlug\": \"maximum-number-of-integers-to-choose-from-a-range-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Missing Integer Greater Than Sequential Prefix Sum\", \"titleSlug\": \"smallest-missing-integer-greater-than-sequential-prefix-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"3.6M\", \"totalAcceptedRaw\": 1456270, \"totalSubmissionRaw\": 3556312, \"acRate\": \"40.9%\"}",
    "title_pt": "Primeiro Positivo Ausente",
    "description_pt": "<p>Dado um array de inteiros não ordenado <code>nums</code>. Retorne o <em>menor inteiro positivo</em> que <em>não está presente</em> em <code>nums</code>.</p>\n\n<p>Você deve implementar um algoritmo que execute em tempo <code>O(n)</code> e use espaço auxiliar <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,0]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os números no intervalo [1,2] estão todos no array.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,4,-1,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> 1 está no array, mas 2 está ausente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [7,8,9,11,12]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> O menor inteiro positivo 1 está ausente.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Pense em como você resolveria o problema com espaço não constante. Você consegue aplicar essa lógica ao espaço existente?",
      "Dica 2: Não nos importamos com duplicatas ou inteiros não positivos",
      "Dica 3: Lembre-se de que O(2n) = O(n)"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "42",
    "paidOnly": false,
    "title": "Trapping Rain Water",
    "titleSlug": "trapping-rain-water",
    "url": "https://leetcode.com/problems/trapping-rain-water",
    "description_url": "https://leetcode.com/problems/trapping-rain-water/description/",
    "description": "<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png\" style=\"width: 412px; height: 161px;\" />\n<pre>\n<strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> height = [4,2,0,3,2,5]\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/trapping-rain-water/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def trap(self, height: List[int]) -> int:\n    n = len(height)\n    l = [0] * n  # l[i] := max(height[0..i])\n    r = [0] * n  # r[i] := max(height[i..n))\n\n    for i, h in enumerate(height):\n      l[i] = h if i == 0 else max(h, l[i - 1])\n\n    for i, h in reversed(list(enumerate(height))):\n      r[i] = h if i == n - 1 else max(h, r[i + 1])\n\n    return sum(min(l[i], r[i]) - h\n               for i, h in enumerate(height))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int trap(int[] height) {\n    final int n = height.length;\n    int ans = 0;\n    int[] l = new int[n]; // l[i] := max(height[0..i])\n    int[] r = new int[n]; // r[i] := max(height[i..n))\n\n    for (int i = 0; i < n; ++i)\n      l[i] = i == 0 ? height[i] : Math.max(height[i], l[i - 1]);\n\n    for (int i = n - 1; i >= 0; --i)\n      r[i] = i == n - 1 ? height[i] : Math.max(height[i], r[i + 1]);\n\n    for (int i = 0; i < n; ++i)\n      ans += Math.min(l[i], r[i]) - height[i];\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int trap(vector<int>& height) {\n    const int n = height.size();\n    int ans = 0;\n    vector<int> l(n);  // l[i] := max(height[0..i])\n    vector<int> r(n);  // r[i] := max(height[i..n))\n\n    for (int i = 0; i < n; ++i)\n      l[i] = i == 0 ? height[i] : max(height[i], l[i - 1]);\n\n    for (int i = n - 1; i >= 0; --i)\n      r[i] = i == n - 1 ? height[i] : max(height[i], r[i + 1]);\n\n    for (int i = 0; i < n; ++i)\n      ans += min(l[i], r[i]) - height[i];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/42.html",
    "category": "Algorithms",
    "acceptance_rate": 64.83931520865477,
    "topics": [
      "Array",
      "Two Pointers",
      "Dynamic Programming",
      "Stack",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 33973,
    "dislikes": 595,
    "similar_questions": "[{\"title\": \"Container With Most Water\", \"titleSlug\": \"container-with-most-water\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product of Array Except Self\", \"titleSlug\": \"product-of-array-except-self\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Trapping Rain Water II\", \"titleSlug\": \"trapping-rain-water-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Pour Water\", \"titleSlug\": \"pour-water\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Value of an Ordered Triplet II\", \"titleSlug\": \"maximum-value-of-an-ordered-triplet-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 2789519, \"totalSubmissionRaw\": 4302221, \"acRate\": \"64.8%\"}",
    "title_pt": "Água da Chuva Presa",
    "description_pt": "<p>Dado <code>n</code> inteiros não negativos representando um mapa de elevação em que a largura de cada barra é <code>1</code>, calcule quanta água ele pode reter após chover.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png\" style=\"width: 412px; height: 161px;\" />\n<pre>\n<strong>Entrada:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O mapa de elevação acima (seção preta) é representado pelo array [0,1,0,2,1,0,1,3,2,1,2,1]. Neste caso, 6 unidades de água da chuva (seção azul) estão sendo retidas.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> height = [4,2,0,3,2,5]\n<strong>Saída:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == height.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "43",
    "paidOnly": false,
    "title": "Multiply Strings",
    "titleSlug": "multiply-strings",
    "url": "https://leetcode.com/problems/multiply-strings",
    "description_url": "https://leetcode.com/problems/multiply-strings/description/",
    "description": "<p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p>\n\n<p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> num1 = \"2\", num2 = \"3\"\n<strong>Output:</strong> \"6\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> num1 = \"123\", num2 = \"456\"\n<strong>Output:</strong> \"56088\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li>\n\t<li><code>num1</code> and <code>num2</code> consist of digits only.</li>\n\t<li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/multiply-strings/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nWe are given two non-negative integers that are represented as strings and asked to return the product of the two integers, also in the form of a string. There are a few subtle challenges and edge cases that we must consider to solve this problem.  So, before determining how to multiply two numbers in string format, let's first consider a simpler variation of the problem: adding two numbers in string format.  \nWe can add two numbers represented as strings by adding digits from the given numbers in each place.  The sum of two digits must be between 0 and 18. The ones place is added to the result while the tens place is carried and summed with the next pair of digits. When summing two numbers, the carried digit will always be zero or one. This process can be repeated for each digit, as shown below.\n\n![image](../Figures/43/Slide31.JPG)\n\nWhy does learning how to add two integers represented as strings help us solve this problem? As we will soon see, addition is a subproblem of multiplication. Thus we will need to be able to solve the problem of adding two numbers as strings before we can solve the problem of multiplying two numbers as strings.\n\nIf this type of problem is new to you and you would like to practice by solving similar problems, we have provided the list below: \n1. [66. Plus One](https://leetcode.com/problems/plus-one/)      \n2. [67. Add Binary](https://leetcode.com/problems/add-binary/)      \n3. [415. Add Strings](https://leetcode.com/problems/add-strings/)  \n4. [989. Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/)     \n\n\n---\n\n### Approach 1: Elementary Math\n\n#### Intuition\n\nOur goal is to multiply two integer numbers that are represented as strings. However, we are not allowed to use a built-in BigInteger library or convert the inputs to integers directly. So how can we multiply the two input strings? We can try to break the problem down into manageable chunks, as is done in elementary mathematics.  Thus, we will focus on one digit at a time, just like in the addition example, except here we will be multiplying both numbers digit by digit.  \n\n**Now, let's recall the process for multiplying two numbers.**      \nWe take the ones place digit of the second number, then multiply it with all digits of the first number consequently going backward, and write the result. We need to remember about carry as well. Note that for multiplication, carry may be any digit between 0 and 8.\n\n![image](../Figures/43/Slide1.JPG)\n\n<br />\n\nThen we take the tens place digit of the second number and multiply it with all digits of the first number.  Since we used the tens place digit, we will multiply this result by 10.  Then we write this result below the previous result, signifying that we will **add** it to the previous result later.\n\n![image](../Figures/43/Slide2.JPG)\n\n<br />\n\nThen we continue the same way with hundreds place digit, then with thousands place digit of the second number, and so on, until we have visited every digit in the second number.\n\n![image](../Figures/43/Slide3.JPG)\n\n<br />\n\nAs is evident from the above diagram, this process is equivalent to multiplying each digit of the second number by the entire first number and appending zeros at the end of each intermediate result based on the place in the second number that the digit came from.\nThen we add all the results together to get the final product of the first and second numbers.\n\n![image](../Figures/43/Slide4.JPG)\n\n<br />\n\nLet's look at an example. Consider $$123 * 456$$, it can be written as,\n\n$$\\implies (123 * (6 + 50 + 400))$$      \n$$\\implies (123 * 6) + (123 * 50) + (123 * 400)$$     \n$$\\implies (123 * 6) + (123 * 5 * 10) + (123 * 4 * 100)$$     \n \n$$\\implies \\Sigma \\space ( firstNumber * j^{th} \\space digit \\space of \\space secondNumber * 10^{(index \\space j \\space of \\space digit \\space counting \\space from \\space the \\space end)} )$$      \n\nThe results of the multiplication of each digit of the second number with the first number can be stored in an array of strings, and then we can add all these strings to get the final product.     \n\n#### Algorithm\n\nMultiplication of both numbers starts from the ones place digit (the right-most digit), so we should start our multiplication from index `num2.size() - 1` and go to index `0`.  Alternatively, we can reverse both inputs and iterate from index `0` to index `num2.size() - 1`.\n\nFor each digit in `num2` that we multiply by `num1` we will get a new intermediate result.  This intermediate result (`currentResult`) will be stored in a list, string, or StringBuilder, depending on the language of choice.  To calculate each intermediate result, we will start by inserting the appropriate number of zeros according to the current digit's place in the second number (i.e. if it is the hundreds place, we append 2 zeros).  Then we will perform the multiplication step as demonstrated in the above diagrams. During this step, we will insert the lower place digits into the `currentResult` before the higher place digits.  Because we are pushing the lower place digits first and always appending to the end, our result will be in reverse order, so once the multiplication and addition steps are complete, we will need to reverse `answer` before returning.\n\nLet's walk through the steps one by one:\n\n1. Reverse both numbers.\n2. For each digit in `secondNumber`:\n    - Keep a `carry` variable, initially equal to `0`.\n    - Initialize `currentResult` array beginning with the appropriate number of zeros according to the place of the `secondNumber` digit.\n    - For each digit in `firstNumber`:\n        - Multiply the `secondNumber`'s digit and the `firstNumber`'s digit and add `carry` to the `multiplication`.\n        - Take the remainder of `multiplication` with `10` to get the last digit.\n        - Append the last digit to the `currentResult`.\n        - Divide `multiplication` by `10` to get the new value for `carry`.\n    - Append the remaining value for `carry` (if any) to the `currentResult`.\n    - Push the `currentResult` into the `results` array.\n3. Compute the cumulative sum over all the obtained arrays using the `ans` as an answer.\n4. Reverse `ans` and return it.\n\n!?!../Documents/43/slideshow1.json:960,540!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ecJN2cdc/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ecJN2cdc\"></iframe>\n\n\n#### Complexity Analysis\n\nHere $$N$$ and $$M$$ are the number of digits in `num1` and `num2` respectively.\n\n* Time complexity: $$O(M^2 + M \\cdot N)$$.\n\n  During multiplication, we perform $$N$$ operations for each of the $$M$$ digits of the second number; this requires $$O(M \\cdot N)$$ time. Then we add each of the $$M$$ multiplication results (of length $$O(N + M)$$) to the answer string; this requires $$O(M \\cdot (M + N))$$ time.\n   \n  > When we multiply a number with one digit, the result's maximum length can be at most one more than the number's length _(We can see that when we multiply the max integer of `d` digits, i.e., `9...99` with `9`)_ and there can be at most (M-1) zeroes initially appended to the result. Hence, each result is of order $$O(N + M)$$.\n   \n  Summing the results requires iterating over the length of the current answer for each result.  Since the length of two numbers multiplied together cannot be longer than the sum of the lengths of the two numbers, iterating over each digit in the answer will take $$O(M + N)$$ time and we will do so $$M - 1$$ times (for all but one of the $$M$$ results). So this step takes $$O(M \\cdot (M + N))$$ time.  \n   \n  Finally, reversing the answer will require $$O(M + N)$$ time. Taking all steps into consideration, the total time complexity is $$O(M^2 + M \\cdot N)$$.\n\n* Space complexity: $$O(M^2 + M \\cdot N)$$.     \n\n  We store each result of multiplication for each digit of `num2` with `num1` in the results array. Each multiplication result can have at most $$N + M$$ length, and there will be $$M$$ such results. Thus the space complexity is $$O(M \\cdot (M + N))$$.\n    \n\n<br/>\n\n---\n\n### Approach 2: Elementary math using less intermediate space\n\n#### Intuition\n\nNotice that we are storing the multiplication result for every digit in `num2`. If we know the maximum size of the answer array ahead of time, we can add each multiplication result directly to the final answer. Thus, we can avoid using the extra space required by the `results` array.\n\nFirst, let's determine what the maximum size of the answer array would be.\n\nTry a few test cases on your own, multiply two numbers, count how many digits are in the result, and compare that to the number of digits in each number.  Notice that whenever two numbers with the number of digits $$N$$ and $$M$$ are multiplied, the result never exceeds $$(N+M)$$ digits. \n\nWe could readily accept that <strong>num1.length + num2.length ≥ (num1 · num2).length</strong> without rigorous proof. However, it never hurts to verify a relationship that was derived from observation before accepting it as a fact. Don't worry, you will not be expected to provide a proof like this during the interview, hence you can skip it if you want.\n\n<details>\n\n<summary> The proof that the length of the product of two numbers is always less than or equal to the sum of lengths of the two numbers is as follows: (click to show/hide) </summary>\n\n<br>\n\n> A number $$n$$ has digits, $$ d = 1 + \\lfloor log_{10}(n) \\rfloor $$.  \n   \nIts proof is:   \n> Suppose that $$n$$ has $$d$$ digits, then $$ 10^{d-1} \\leq n < 10^{d} $$, because $$ 10^{d} $$ is the smallest integer with $$d+1$$ digits.       \nNow take log base 10, then the inequality becomes $$ (d-1) \\leq \\log_{10}(n) < d $$.      \nNow everything between the range $$(d-1, \\space d)$$ is decimal part, so taking floor of $$ \\log_{10}(n) $$ we can eliminate all the decimal part and get, $$ (d-1) = \\lfloor \\log_{10}(n) \\rfloor $$. \n<br />           \nThus, $$d = \\lfloor \\log_{10}(n) \\rfloor + 1$$.\n\n<br />\n\nLet $$firstNumber$$ have $$N$$ digits and $$secondNumber$$ have $$M$$ digits.      \n\nLet $$product = firstNumber \\cdot secondNumber$$ have $$X$$ digits. So, number of digits in $$product$$ is,      \n           \n$$  \\implies X = 1 + \\lfloor log_{10}(result) \\rfloor   $$         \n$$  \\implies X = 1 + \\lfloor log_{10}(firstNumber \\cdot secondNumber) \\rfloor   $$         \n$$  \\implies X = 1 + \\lfloor log_{10}(firstNumber) + log_{10}(secondNumber) \\rfloor $$ <br />         \n                 \n\n> A real number $$a$$ can have two parts in it, integral $$(I)$$ and fractional $$(F)$$. $$a = I_{a} + F_{a}$$.    \n\nNow, let's say we have two real numbers $$a = I_{a} + F_{a} $$ and $$b = I_{b} + F_{b}$$. \n<br />     \n\n$$ \\lfloor a + b \\rfloor = \\lfloor I_{a} + F_{a} + I_{b} + F_{b} \\rfloor = I_{a} + I_{b} + \\lfloor F_{a} + F_{b} \\rfloor $$     \n$$ F_{a}, F_{b} $$ are fractional parts both always less than 1.           \n$$ 0 \\leq F_{a} + F_{b} < 2 $$.      \n$$ 0 \\leq \\lfloor F_{a} + F_{b} \\rfloor <= 1 $$. <br />       \n> So, $$ I_{a} + I_{b} \\leq \\lfloor a + b \\rfloor \\leq  I_{a} + I_{b} + 1$$. \n<br />     \n\nBut, $$ \\lfloor a \\rfloor + \\lfloor b \\rfloor = \\lfloor I_{a} + F_{a} \\rfloor + \\lfloor I_{b} + F_{b} \\rfloor = I_{a} + I_{b} + \\lfloor F_{a} \\rfloor + \\lfloor F_{b} \\rfloor $$     \n$$ F_{a}, F_{b} $$ are fractional parts both always less than $$ 1 $$.        \n$$ 0 \\leq F_{a}, \\space F_{b} < 1 $$.          \nHence, $$ \\lfloor F_{a} \\rfloor + \\lfloor F_{b} \\rfloor = 0 $$. <br />       \n> So, $$ \\lfloor a \\rfloor + \\lfloor b \\rfloor = I_{a} + I_{b} $$. \n\n> Hence we can conclude here that, <br />     \n> $$ \\lfloor a \\rfloor + \\lfloor b \\rfloor \\leq \\lfloor a + b \\rfloor \\leq \\lfloor a \\rfloor + \\lfloor b \\rfloor + 1 $$  \n\n<br />\n\nNumber of digits in,\n$$ firstNumber = N, \\space secondNumber = M, \\space product = X $$ <br />  \nIf $$ a = log_{10}(firstNumber) $$ and $$ b = log_{10}(secondNumber) $$.     \n\n$$ N = \\lfloor log_{10} (firstNumber) \\rfloor + 1 = \\lfloor a \\rfloor + 1$$     \n$$ M = \\lfloor log_{10} (secondNumber) \\rfloor + 1 = \\lfloor b \\rfloor + 1$$     \n$$ X = \\lfloor log_{10} (firstNumber) + log_{10} (secondNumber) \\rfloor + 1 = \\lfloor a + b \\rfloor + 1$$      \n<br />\n\n$$ \\lfloor a \\rfloor = N - 1, \\space  \\lfloor b \\rfloor = M - 1, \\space  \\lfloor a + b \\rfloor = X - 1,  $$ <br />        \n\nas, $$ \\lfloor a \\rfloor + \\lfloor b \\rfloor \\leq \\lfloor a + b \\rfloor \\leq \\lfloor a \\rfloor + \\lfloor b \\rfloor + 1 $$  \n\n$$ \\implies (N-1) + (M-1) \\leq (X - 1) \\leq (N-1) + (M-1) + 1 $$       \n$$ \\implies (N + M - 1) \\leq X \\leq (N + M) $$ \n\n> Hence, $$X$$ can never exceed $$ (N + M) $$. \n\n</details>\n\n<br />\n\nSo an answer string of size $$N + M$$ is guaranteed to be large enough to hold our final result.  Let's create one and initialize all of its values as zero.\nInstead of storing all results of multiplication of each digit of $$num2$$ with $$num1$$ like we did in Approach 1, we can directly add the current result to the answer string.      \n\n#### Algorithm\n\n1. Reverse both numbers.\n2. Initialize `ans` array with $$(N+M)$$ zeros.\n3. For each digit in `secondNumber`:\n    - Keep a `carry` variable, initially equal to `0`.\n    - Initialize an array (`currentResult`) that begins with some zeros based on the place of the digit in `secondNumber`.\n    - For each digit of `firstNumber`:\n        - Multiply `secondNumber's` digit and `firstNumber's` digit and add previous `carry` to the `multiplication`.\n        - Take the remainder of `multiplication` with `10` to get the last digit.\n        - Append the last digit to `currentResult` array.\n        - Divide the `multiplication` by `10` to obtain the new value for `carry`.\n    - After iterating over each digit in the first number, if `carry` is not zero, append `carry` to the `currentResult`.\n    - Add `currentResult` to the `ans`.\n4. If the last digit in `ans` is zero, before reversing `ans`, we must pop the zero from `ans`. Otherwise, there would be a leading zero in the final answer.\n5. Reverse `ans` and return it.\n\n!?!../Documents/43/slideshow2.json:960,540!?!\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/aiu9hUhq/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"aiu9hUhq\"></iframe>\n\n\n#### Complexity Analysis\n\nHere $$N$$ and $$M$$ are the number of elements in num 1 and num 2 strings.\n\n* Time complexity: $$O(M \\cdot (N+M))$$.     \n   - During multiplication, we perform `N` operations for each of the `M` digits of the second number, so we need $$O(M \\cdot N)$$ time for it.     \n   - We add the multiplication result to the `ans` string that has a length of $$N+M$$. There will be $$M$$ such additions since we have $$M$$ multiplication results. Therefore, the time consumed here will be $$O(M \\cdot (N+M))$$.\n   - It takes linear time to reverse the strings.\n   - Overall, this solution takes $$O(M \\cdot N + M \\cdot (N+M) + M + N) = O(M \\cdot (N+M))$$ time.\n\n* Space complexity: $$O(N + M)$$.     \n   - The answer string and multiplication results will have at most $$N + M$$ length.\n\n<br/>\n\n---\n\n### Approach 3: Sum the products from all pairs of digits\n\n#### Intuition\n\nAs we have seen in the previous approaches, when we multiply two digits, one from the first number and one from the second number, then their product will have some zeros appended at the end. The number of zeros depends on the place of each digit, and (as demonstrated in the image below) when the result is added to the answer, the trailing zeros do not affect the answer (because any number plus zero is itself).\nSo it is not necessary for us to append zeros at the end of each result before adding the result to the final answer. Instead, we can directly add the multiplication result at the place where the least significant digit will shift to after to appending some zeros.  \n\nAs an example, when we multiply two tens place digits, two zeros are appended at the end of the multiplication result, and the result will be added at the hundreds place in the final answer. One more example for clarity, if we multiplied a digit in the thousands place (3 trailing zeros) by a digit in the hundreds place (2 trailing zeros), the product will have 5 trailing zeros (the sum of trailing zeros of each digit) so the result will only affect the hundred thousands place and the millions place in the final answer.  \n\n![image](../Figures/43/Slide32.JPG)     \n\n<br />\n\nIn the previous solution, including the extra zeros was quite costly.  For instance, `multiplyOneDigit` stored these extra zeros for every intermediate result which required an additional $$O(N)$$ space and time for each multiplication, where $$N$$ is the number of digits in `num2`.  Furthermore, every time we called `multiplyOneDigit` we added the result to the current `answer`.  This involved iterating over all $$M + N$$ digits in answer each time we added a new result to the current answer. So let's get a better idea of how we can solve this problem without iterating over all the extra zeros.\n\nTake a moment to study the above example.  Notice that we multiply each digit in `num2` by each digit in `num1` just like before. Each time we will get a 2-digit result with some zeros after it. Since we know how many zeros will follow the product of the two digits based on their places, we know which two places in `answer` to update.  So, instead of updating all $$M + N$$ elements in `answer` for each of the $$N$$ digits in `num2`, we only need to update $$2$$ digits in `answer` for each of the $$M \\cdot N$$ pairs of digits.  The above example highlights the two digits from each result that we will add to the answer and the below example shows precisely how this will be done.\n\nThus, for each pair of digits, we multiply them together to get a 2-digit result. The ones place of the result will be added at the correct position in `answer` (based on the place of each of the digits). The tens place of the result will be added to the next place in `answer`. This step is effectively the same as carrying the tens place digit in the previous approaches.\n\nNote that the `answer` array will be reversed just like before. So when we multiply a digit in the $$i^{th}$$ place of the first number by a digit in the $$j^{th}$$ place of the second number, then the ones place of the result will add to the $$(i+j)^{th}$$ place in the final answer and the tens place of the result (carry) will be added to the $$(i+j+1)^{th}$$ place in the final answer. \n\n\n#### Algorithm\n\n1. Reverse both numbers.\n2. Initialize `answer` with $$N + M$$ zeros.\n3. For each digit at position `i` in `secondNumber`:\n    - For each digit at position `j` in `firstNumber`:\n        - Multiply the digit from `secondNumber` by the digit from `firstNumber` and add previously carried value to the `multiplication` result.  The previously carried value can be found at position `i + j` in the `answer`.\n        - Take the remainder of `multiplication` with `10` to get the ones place digit of the `multiplication` result.\n        - Put the last digit at current position (position `i + j`) in `answer`.\n        - Divide the `multiplication` by `10` to get the new value for carry and add it to `answer` at the next position.  Note, the next position is located at `(i + j + 1)`.\n4. If the last digit in `answer` is zero, before reversing `answer`, we must pop the zero from `answer`. Otherwise, there would be a leading zero in the final answer.\n5. Reverse `answer` and return it.\n\n!?!../Documents/43/slideshow3.json:960,540!?!\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/ktauubWh/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ktauubWh\"></iframe>\n\n\n#### Complexity Analysis\n\nHere $$N$$ and $$M$$ are the number of digits in `num1` and `num2` respectively.\n\n* Time complexity: $$O(M \\cdot N)$$.     \n\n  During multiplication, we perform `N` operations for each of the `M` digits of the second number, so we need $$M \\cdot N$$ time for it.\n\n* Space complexity: $$O(M + N)$$.     \n\n  The space used to store the output is not included in the space complexity. However, because strings are immutable in Python, Java, and Javascript, a temporary data structure, using $$O(M + N)$$ space, is required to store the answer while it is updated.\n  \n  On the other hand, in C++, strings are mutable, so we do not need a temporary data structure to store answer and can update answer directly.  Thus, the C++ approach is a constant space solution.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def multiply(self, num1: str, num2: str) -> str:\n    s = [0] * (len(num1) + len(num2))\n\n    for i in reversed(range(len(num1))):\n      for j in reversed(range(len(num2))):\n        mult = int(num1[i]) * int(num2[j])\n        summ = mult + s[i + j + 1]\n        s[i + j] += summ // 10\n        s[i + j + 1] = summ % 10\n\n    for i, c in enumerate(s):\n      if c != 0:\n        break\n\n    return ''.join(map(str, s[i:]))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String multiply(String num1, String num2) {\n    final int m = num1.length();\n    final int n = num2.length();\n\n    StringBuilder sb = new StringBuilder();\n    int[] pos = new int[m + n];\n\n    for (int i = m - 1; i >= 0; --i)\n      for (int j = n - 1; j >= 0; --j) {\n        final int multiply = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');\n        final int sum = multiply + pos[i + j + 1];\n        pos[i + j] += sum / 10;\n        pos[i + j + 1] = sum % 10;\n      }\n\n    for (final int p : pos)\n      if (p > 0 || sb.length() > 0)\n        sb.append(p);\n\n    return sb.length() == 0 ? \"0\" : sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string multiply(string num1, string num2) {\n    string s(num1.length() + num2.length(), '0');\n\n    for (int i = num1.length() - 1; i >= 0; --i)\n      for (int j = num2.length() - 1; j >= 0; --j) {\n        const int mult = (num1[i] - '0') * (num2[j] - '0');\n        const int sum = mult + (s[i + j + 1] - '0');\n        s[i + j] += sum / 10;\n        s[i + j + 1] = '0' + sum % 10;\n      }\n\n    const int i = s.find_first_not_of('0');\n    return i == -1 ? \"0\" : s.substr(i);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/43.html",
    "category": "Algorithms",
    "acceptance_rate": 42.16570974095494,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 7373,
    "dislikes": 3529,
    "similar_questions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Plus One\", \"titleSlug\": \"plus-one\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Binary\", \"titleSlug\": \"add-binary\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Strings\", \"titleSlug\": \"add-strings\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Apply Discount to Prices\", \"titleSlug\": \"apply-discount-to-prices\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"968.1K\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 968073, \"totalSubmissionRaw\": 2295881, \"acRate\": \"42.2%\"}",
    "title_pt": "Multiplicar Strings",
    "description_pt": "<p>Dado dois inteiros não negativos <code>num1</code> e <code>num2</code> representados como strings, retorne o produto de <code>num1</code> e <code>num2</code>, também representado como uma string.</p>\n\n<p><strong>Nota:</strong>&nbsp;Você não deve usar nenhuma biblioteca BigInteger embutida nem converter as entradas diretamente para inteiro.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> num1 = \"2\", num2 = \"3\"\n<strong>Saída:</strong> \"6\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> num1 = \"123\", num2 = \"456\"\n<strong>Saída:</strong> \"56088\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li>\n\t<li><code>num1</code> e <code>num2</code> consistem apenas de dígitos.</li>\n\t<li>Ambos <code>num1</code> e <code>num2</code>&nbsp;não contêm nenhum zero à esquerda, exceto o número <code>0</code> em si.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "44",
    "paidOnly": false,
    "title": "Wildcard Matching",
    "titleSlug": "wildcard-matching",
    "url": "https://leetcode.com/problems/wildcard-matching",
    "description_url": "https://leetcode.com/problems/wildcard-matching/description/",
    "description": "<p>Given an input string (<code>s</code>) and a pattern (<code>p</code>), implement wildcard pattern matching with support for <code>&#39;?&#39;</code> and <code>&#39;*&#39;</code> where:</p>\n\n<ul>\n\t<li><code>&#39;?&#39;</code> Matches any single character.</li>\n\t<li><code>&#39;*&#39;</code> Matches any sequence of characters (including the empty sequence).</li>\n</ul>\n\n<p>The matching should cover the <strong>entire</strong> input string (not partial).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aa&quot;, p = &quot;a&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> &quot;a&quot; does not match the entire string &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aa&quot;, p = &quot;*&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong>&nbsp;&#39;*&#39; matches any sequence.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cb&quot;, p = &quot;?a&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong>&nbsp;&#39;?&#39; matches &#39;c&#39;, but the second letter is &#39;a&#39;, which does not match &#39;b&#39;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li>\n\t<li><code>s</code> contains only lowercase English letters.</li>\n\t<li><code>p</code> contains only lowercase English letters, <code>&#39;?&#39;</code> or <code>&#39;*&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/wildcard-matching/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isMatch(self, s: str, p: str) -> bool:\n    m = len(s)\n    n = len(p)\n    # dp[i][j] := True if s[0..i) matches p[0..j)\n    dp = [[False] * (n + 1) for _ in range(m + 1)]\n    dp[0][0] = True\n\n    def isMatch(i: int, j: int) -> bool:\n      return i >= 0 and p[j] == '?' or s[i] == p[j]\n\n    for j, c in enumerate(p):\n      if c == '*':\n        dp[0][j + 1] = dp[0][j]\n\n    for i in range(m):\n      for j in range(n):\n        if p[j] == '*':\n          matchEmpty = dp[i + 1][j]\n          matchSome = dp[i][j + 1]\n          dp[i + 1][j + 1] = matchEmpty or matchSome\n        elif isMatch(i, j):\n          dp[i + 1][j + 1] = dp[i][j]\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isMatch(String s, String p) {\n    final int m = s.length();\n    final int n = p.length();\n    // dp[i][j] := true if s[0..i) matches p[0..j)\n    boolean[][] dp = new boolean[m + 1][n + 1];\n    dp[0][0] = true;\n\n    for (int j = 0; j < p.length(); ++j)\n      if (p.charAt(j) == '*')\n        dp[0][j + 1] = dp[0][j];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (p.charAt(j) == '*') {\n          final boolean matchEmpty = dp[i + 1][j];\n          final boolean matchSome = dp[i][j + 1];\n          dp[i + 1][j + 1] = matchEmpty || matchSome;\n        } else if (isMatch(s, i, p, j)) {\n          dp[i + 1][j + 1] = dp[i][j];\n        }\n\n    return dp[m][n];\n  }\n\n  private boolean isMatch(final String s, int i, final String p, int j) {\n    return j >= 0 && p.charAt(j) == '?' || s.charAt(i) == p.charAt(j);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isMatch(string s, string p) {\n    const int m = s.length();\n    const int n = p.length();\n    // dp[i][j] := true if s[0..i) matches p[0..j)\n    vector<vector<bool>> dp(m + 1, vector<bool>(n + 1));\n    dp[0][0] = true;\n\n    auto isMatch = [&](int i, int j) -> bool {\n      return j >= 0 && p[j] == '?' || s[i] == p[j];\n    };\n\n    for (int j = 0; j < p.length(); ++j)\n      if (p[j] == '*')\n        dp[0][j + 1] = dp[0][j];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (p[j] == '*') {\n          const bool matchEmpty = dp[i + 1][j];\n          const bool matchSome = dp[i][j + 1];\n          dp[i + 1][j + 1] = matchEmpty || matchSome;\n        } else if (isMatch(i, j)) {\n          dp[i + 1][j + 1] = dp[i][j];\n        }\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/44.html",
    "category": "Algorithms",
    "acceptance_rate": 29.702884748877906,
    "topics": [
      "String",
      "Dynamic Programming",
      "Greedy",
      "Recursion"
    ],
    "hints": [],
    "likes": 8638,
    "dislikes": 387,
    "similar_questions": "[{\"title\": \"Regular Expression Matching\", \"titleSlug\": \"regular-expression-matching\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Substring Matching Pattern\", \"titleSlug\": \"substring-matching-pattern\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"708.2K\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 708162, \"totalSubmissionRaw\": 2384155, \"acRate\": \"29.7%\"}",
    "title_pt": "Correspondência com Caracteres Coringa",
    "description_pt": "<p>Dada uma string de entrada (<code>s</code>) e um padrão (<code>p</code>), implemente a correspondência de padrão com coringa com suporte para <code>&#39;?&#39;</code> e <code>&#39;*&#39;</code>, em que:</p>\n\n<ul>\n\t<li><code>&#39;?&#39;</code> corresponde a qualquer caractere único.</li>\n\t<li><code>&#39;*&#39;</code> corresponde a qualquer sequência de caracteres (incluindo a sequência vazia).</li>\n</ul>\n\n<p>A correspondência deve abranger a <strong>string de entrada inteira</strong> (não apenas parte dela).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aa&quot;, p = &quot;a&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> &quot;a&quot; não corresponde à string inteira &quot;aa&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aa&quot;, p = &quot;*&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong>&nbsp;&#39;*&#39; corresponde a qualquer sequência.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cb&quot;, p = &quot;?a&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong>&nbsp;&#39;?&#39; corresponde a &#39;c&#39;, mas a segunda letra é &#39;a&#39;, que não corresponde a &#39;b&#39;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length, p.length &lt;= 2000</code></li>\n\t<li><code>s</code> contém apenas letras minúsculas do alfabeto ინგლის? no</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "45",
    "paidOnly": false,
    "title": "Jump Game II",
    "titleSlug": "jump-game-ii",
    "url": "https://leetcode.com/problems/jump-game-ii",
    "description_url": "https://leetcode.com/problems/jump-game-ii/description/",
    "description": "<p>You are given a <strong>0-indexed</strong> array of integers <code>nums</code> of length <code>n</code>. You are initially positioned at <code>nums[0]</code>.</p>\n\n<p>Each element <code>nums[i]</code> represents the maximum length of a forward jump from index <code>i</code>. In other words, if you are at <code>nums[i]</code>, you can jump to any <code>nums[i + j]</code> where:</p>\n\n<ul>\n\t<li><code>0 &lt;= j &lt;= nums[i]</code> and</li>\n\t<li><code>i + j &lt; n</code></li>\n</ul>\n\n<p>Return <em>the minimum number of jumps to reach </em><code>nums[n - 1]</code>. The test cases are generated such that you can reach <code>nums[n - 1]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,1,1,4]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,0,1,4]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>It&#39;s guaranteed that you can reach <code>nums[n - 1]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/jump-game-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def jump(self, nums: List[int]) -> int:\n    ans = 0\n    end = 0\n    farthest = 0\n\n    # Implicit BFS\n    for i in range(len(nums) - 1):\n      farthest = max(farthest, i + nums[i])\n      if farthest >= len(nums) - 1:\n        ans += 1\n        break\n      if i == end:      # Visited all the items on the current level\n        ans += 1        # Increment the level\n        end = farthest  # Make the queue size for the next level\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int jump(int[] nums) {\n    int ans = 0;\n    int end = 0;\n    int farthest = 0;\n\n    // Implicit BFS\n    for (int i = 0; i < nums.length - 1; ++i) {\n      farthest = Math.max(farthest, i + nums[i]);\n      if (farthest >= nums.length - 1) {\n        ++ans;\n        break;\n      }\n      if (i == end) {   // Visited all the items on the current level\n        ++ans;          // Increment the level\n        end = farthest; // Make the queue size for the next level\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int jump(vector<int>& nums) {\n    int ans = 0;\n    int end = 0;\n    int farthest = 0;\n\n    // Implicit BFS\n    for (int i = 0; i < nums.size() - 1; ++i) {\n      farthest = max(farthest, i + nums[i]);\n      if (farthest >= nums.size() - 1) {\n        ++ans;\n        break;\n      }\n      if (i == end) {    // Visited all the items on the current level\n        ++ans;           // Increment the level\n        end = farthest;  // Make the queue size for the next level\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/45.html",
    "category": "Algorithms",
    "acceptance_rate": 41.36600597800618,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy"
    ],
    "hints": [],
    "likes": 15476,
    "dislikes": 652,
    "similar_questions": "[{\"title\": \"Jump Game\", \"titleSlug\": \"jump-game\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game III\", \"titleSlug\": \"jump-game-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game VII\", \"titleSlug\": \"jump-game-vii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game VIII\", \"titleSlug\": \"jump-game-viii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Visited Cells in a Grid\", \"titleSlug\": \"minimum-number-of-visited-cells-in-a-grid\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Jumps to Reach the Last Index\", \"titleSlug\": \"maximum-number-of-jumps-to-reach-the-last-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Visit Array Positions to Maximize Score\", \"titleSlug\": \"visit-array-positions-to-maximize-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"4.1M\", \"totalAcceptedRaw\": 1703630, \"totalSubmissionRaw\": 4118430, \"acRate\": \"41.4%\"}",
    "title_pt": "Jogo do Salto II",
    "description_pt": "<p>Você recebe um array <strong>indexado em 0</strong> de inteiros <code>nums</code> de comprimento <code>n</code>. Você está inicialmente posicionado em <code>nums[0]</code>.</p>\n\n<p>Cada elemento <code>nums[i]</code> representa o comprimento máximo de um salto para a frente a partir do índice <code>i</code>. Em outras palavras, se você estiver em <code>nums[i]</code>, você pode saltar para qualquer <code>nums[i + j]</code> em que:</p>\n\n<ul>\n\t<li><code>0 &lt;= j &lt;= nums[i]</code> e</li>\n\t<li><code>i + j &lt; n</code></li>\n</ul>\n\n<p>Retorne <em>o número mínimo de saltos para alcançar </em><code>nums[n - 1]</code>. Os casos de teste são gerados de modo que você consegue alcançar <code>nums[n - 1]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,1,1,4]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> O número mínimo de saltos para alcançar o último índice é 2. Salte 1 passo do índice 0 para 1, depois 3 passos até o último índice.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,0,1,4]\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>É garantido que você consegue alcançar <code>nums[n - 1]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "46",
    "paidOnly": false,
    "title": "Permutations",
    "titleSlug": "permutations",
    "url": "https://leetcode.com/problems/permutations",
    "description_url": "https://leetcode.com/problems/permutations/description/",
    "description": "<p>Given an array <code>nums</code> of distinct integers, return all the possible <span data-keyword=\"permutation-array\">permutations</span>. You can return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [0,1]\n<strong>Output:</strong> [[0,1],[1,0]]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [1]\n<strong>Output:</strong> [[1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 6</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>All the integers of <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/permutations/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def permute(self, nums: List[int]) -> List[List[int]]:\n    ans = []\n    used = [False] * len(nums)\n\n    def dfs(path: List[int]) -> None:\n      if len(path) == len(nums):\n        ans.append(path.copy())\n        return\n\n      for i, num in enumerate(nums):\n        if used[i]:\n          continue\n        used[i] = True\n        path.append(num)\n        dfs(path)\n        path.pop()\n        used[i] = False\n\n    dfs([])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> permute(int[] nums) {\n    List<List<Integer>> ans = new ArrayList<>();\n\n    dfs(nums, new boolean[nums.length], new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> ans) {\n    if (path.size() == nums.length) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (used[i])\n        continue;\n      used[i] = true;\n      path.add(nums[i]);\n      dfs(nums, used, path, ans);\n      path.remove(path.size() - 1);\n      used[i] = false;\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> permute(vector<int>& nums) {\n    vector<vector<int>> ans;\n\n    dfs(nums, vector<bool>(nums.size()), {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& nums, vector<bool>&& used, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (path.size() == nums.size()) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (used[i])\n        continue;\n      used[i] = true;\n      path.push_back(nums[i]);\n      dfs(nums, move(used), move(path), ans);\n      path.pop_back();\n      used[i] = false;\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/46.html",
    "category": "Algorithms",
    "acceptance_rate": 80.50343814465212,
    "topics": [
      "Array",
      "Backtracking"
    ],
    "hints": [],
    "likes": 19890,
    "dislikes": 355,
    "similar_questions": "[{\"title\": \"Next Permutation\", \"titleSlug\": \"next-permutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutations II\", \"titleSlug\": \"permutations-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutation Sequence\", \"titleSlug\": \"permutation-sequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Combinations\", \"titleSlug\": \"combinations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.6M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 2575626, \"totalSubmissionRaw\": 3199398, \"acRate\": \"80.5%\"}",
    "title_pt": "Permutações",
    "description_pt": "<p>Dado um array <code>nums</code> de inteiros distintos, retorne todas as <span data-keyword=\"permutation-array\">permutações</span> possíveis. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [0,1]\n<strong>Saída:</strong> [[0,1],[1,0]]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> [[1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 6</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>Todos os inteiros de <code>nums</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "47",
    "paidOnly": false,
    "title": "Permutations II",
    "titleSlug": "permutations-ii",
    "url": "https://leetcode.com/problems/permutations-ii",
    "description_url": "https://leetcode.com/problems/permutations-ii/description/",
    "description": "<p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,2]\n<strong>Output:</strong>\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 8</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/permutations-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Overview\n\nAs the name of the problem suggests, this problem is an extension of the [Permutation](https://leetcode.com/problems/permutations/) problem.\nThe problem is different from the previous permutation problem on the condition that the input array can contain **_duplicates_**.\n\nThe key to solve the problem is still the **_backtracking_** algorithm.\nHowever, we need some adaptation to ensure that the _enumerated_ solutions generated from our backtracking exploration do not have any duplicates.\n\n>As a reminder, **[backtracking](https://leetcode.com/explore/learn/card/recursion-ii/472/backtracking/)** is a general algorithm for finding all (or some) solutions to some problems with constraints.\nIt incrementally builds candidates to the solutions, and abandons a candidate as soon as it determines that the candidate cannot possibly lead to a solution.\n\nIn this article, we will present a yet another backtracking solution to solve the problem.\n\n---\n### Approach 1: Backtracking with Groups of Numbers\n\n**Intuition**\n\nFirst of all, let us review the general idea of permutation with an example.\n\nGiven the input array `[1, 1, 2]`, to generate a permutation of the array, we could follow the _Depth-First Search_ (DFS) approach, or more precisely the backtracking technique as one will see later.\n\n>The idea is that we pick the numbers one by one. For a permutation of length $$N$$, we would then need $$N$$ stages to generate a valid permutation.\nAt each stage, we need to pick one number into the permutation, out of the remaining available numbers.\nLater at the same stage, we will try out all available choices.\nBy trying out, we progressively build up candidates to the solution, and revert each choice with another alternative until there is no more choice.\n\nLet us walk through the example with paper and pencil, as follows:\n\n- Given the input of `[1, 1, 2]`, at the first stage, we have 2 choices to pick a number as the first number in the final permutation, _i.e._ `1` and `2`.\nSuppose that we pick the number `1`, now the remaining numbers would become `[1, 2]`.\n**Note:** The reason that we have only 2 choices instead of 3, is that there is a duplicate in the given input.\nPicking any of the duplicate numbers as the first number of the permutation would lead us to the same permutation at the end.\nShould the numbers in the array be all unique, we would then have the same number of choices as the length of the array. \n\n- At the second stage, we now then have again 2 choices, _i.e._ `[1, 2]`. \nLet us pick again the number `1`, which leaves us the only remaining number `2`.\n\n- Now at the third stage, we have only one candidate number left, _i.e._ `[2]`. We then pick the last remaining number, which leads to a final permutation sequence of `[1, 1, 2]`.\n\n- Moreover, we need to **_revisit_** each of the above stages, and make a different choice in order to try out all possibilities.\nThe reversion of the choices is what we call __*backtracking*__.\n\nWe illustrate all potential exploration in the following graph where each node represents a choice at a specific stage:\n\n![permutation tree](../Figures/47/47_permutations.png)\n\n>A key insight to avoid generating any **_redundant_** permutation is that at each step rather than viewing each number as a candidate, we consider each **_unique_** number as the true candidate.\nFor instance, at the very beginning, given in the input of `[1, 1, 2]`, we have only two true candidates instead of three.\n\n\n**Algorithm**\n\nGiven the above insight, in order to find out all the unique numbers at each stage, we can build a **_hash table_** (denoted as `counter`), with each unique number as the key and its occurrence as the corresponding value.\n\nTo implement the algorithm, first we define a function called `backtrack(comb, counter)` which generates all permutations, starting from the current combination (`comb`) and the remaining numbers (`counter`).\n\nOnce the function is implemented, it suffices to invoke the function with the initial empty combination and the hash table we built out of the input array, to solve the problem.\n\nHere are some sample implementations.\n\n<iframe src=\"https://leetcode.com/playground/gmT2V4Q3/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gmT2V4Q3\"></iframe>\n\n**Note:** for a backtracking algorithm, usually there are some explorations that would lead to a *dead end*, and we have to abandon those explorations in the middle.\n\nHowever, due to the specificity of this problem and our exploration strategy, each exploration will result in a valid permutation, _i.e._ none of the efforts is in vain.\nThis insight would prove to be useful in the following complexity analysis.\n\n**Complexity Analysis**\n\nLet $$N$$ be the length of the input array.\nHence, the number of permutations would be at maximum $$N!$$, _i.e._ $$N \\cdot (N-1) \\cdot (N-2) ... 1$$, when each number in the array is unique.\n\n- Time Complexity: $$\\mathcal{O}\\big(\\sum_{k = 1}^{N}{P(N, k)}\\big)$$ where $$P(N, k) = \\frac{N!}{(N - k)!} = N (N - 1) ... (N - k + 1)$$\nis so-called [_k-permutations_of_N_ or _partial permutation_](https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n). \n\n    - As one can see in the exploration graph we have shown earlier, the execution of the backtracking algorithm will unfold itself as a tree, where each node is an invocation of the recursive function `backtrack(comb, counter)`.\n    The total number of steps to complete the exploration is _exactly_ the number of nodes in the tree.\n    Therefore, the time complexity of the algorithm is linked directly with the size of the tree.\n\n    - It now boils down to estimating the number of nodes in the tree.\n    As we know now, each level of the tree corresponds to a specific _stage_ of the exploration.\n    At each stage, the number of candidates to explore is **bounded**.\n    For instance, at the first stage, _at most_ we would have $$N$$ candidates to explore, _i.e._ the number of nodes at this level would be $$N$$.\n    Moving on to the next stage, for each of the nodes in the first stage, we would have $$N-1$$ child nodes. Therefore, the number of nodes at this stage would be $$N \\cdot (N-1)$$.\n    So on and so forwards.\n\n    ![number of nodes](../Figures/47/47_number_of_nodes.png)\n\n    - By summing up all the nodes across the stages, we would then obtain the total number of nodes as $$\\sum_{k = 1}^{N}{P(N, k)}$$ where $$P(N, k) = \\frac{N!}{(N - k)!} = N (N - 1) ... (N - k + 1)$$.\n    As a result, the exact time complexity of the algorithm is $$\\mathcal{O}\\big(\\sum_{k = 1}^{N}{P(N, k)}\\big)$$.\n\n    - The above complexity might appear a bit too abstract to comprehend.\n    Here we could provide another __*loose upper bound*__ on the complexity.\n\n    - It takes $$N$$ steps to generate a single permutation. Since there are in total $$N!$$ possible permutations, at most it would take us $$N \\cdot N!$$ steps to generate all permutations, simply assuming that there is no overlapping effort (which is not true).\n\n\n- Space Complexity: $$\\mathcal{O}(N)$$\n\n    - First of all, we build a hash table out of the input numbers. In the worst case where each number is unique, we would need $$\\mathcal{O}(N)$$ space for the table.\n\n    - Since we applied recursion in the algorithm which consumes some extra space in the function call stack, we would need another $$\\mathcal{O}(N)$$ space for the recursion.\n\n    - During the exploration, we keep a candidate of permutation along the way, which takes yet another $$\\mathcal{O}(N)$$.\n\n    - To sum up, the total space complexity would be $$\\mathcal{O}(N) + \\mathcal{O}(N) + \\mathcal{O}(N) = \\mathcal{O}(N)$$.\n\n    - **Note**, we did not take into account the space needed to hold the results. Otherwise, the space complexity would become $$\\mathcal{O}(N \\cdot N!)$$.\n\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n    ans = []\n    used = [False] * len(nums)\n\n    def dfs(path: List[int]) -> None:\n      if len(path) == len(nums):\n        ans.append(path.copy())\n        return\n\n      for i, num in enumerate(nums):\n        if used[i]:\n          continue\n        if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:\n          continue\n        used[i] = True\n        path.append(num)\n        dfs(path)\n        path.pop()\n        used[i] = False\n\n    nums.sort()\n    dfs([])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> permuteUnique(int[] nums) {\n    List<List<Integer>> ans = new ArrayList<>();\n    Arrays.sort(nums);\n    dfs(nums, new boolean[nums.length], new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> ans) {\n    if (path.size() == nums.length) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (used[i])\n        continue;\n      if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])\n        continue;\n      used[i] = true;\n      path.add(nums[i]);\n      dfs(nums, used, path, ans);\n      path.remove(path.size() - 1);\n      used[i] = false;\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> permuteUnique(vector<int>& nums) {\n    vector<vector<int>> ans;\n    sort(begin(nums), end(nums));\n    dfs(nums, vector<bool>(nums.size()), {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& nums, vector<bool>&& used, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (path.size() == nums.size()) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (used[i])\n        continue;\n      if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1])\n        continue;\n      used[i] = true;\n      path.push_back(nums[i]);\n      dfs(nums, move(used), move(path), ans);\n      path.pop_back();\n      used[i] = false;\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/47.html",
    "category": "Algorithms",
    "acceptance_rate": 61.40725137461186,
    "topics": [
      "Array",
      "Backtracking",
      "Sorting"
    ],
    "hints": [],
    "likes": 8794,
    "dislikes": 154,
    "similar_questions": "[{\"title\": \"Next Permutation\", \"titleSlug\": \"next-permutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutations\", \"titleSlug\": \"permutations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Permutation II\", \"titleSlug\": \"palindrome-permutation-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Squareful Arrays\", \"titleSlug\": \"number-of-squareful-arrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 1098155, \"totalSubmissionRaw\": 1788315, \"acRate\": \"61.4%\"}",
    "title_pt": "Permutações II",
    "description_pt": "<p>Dada uma coleção de números, <code>nums</code>,&nbsp;que pode conter duplicatas, retorne <em>todas as possíveis permutações únicas <strong>em qualquer ordem</strong>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,2]\n<strong>Saída:</strong>\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 8</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "48",
    "paidOnly": false,
    "title": "Rotate Image",
    "titleSlug": "rotate-image",
    "url": "https://leetcode.com/problems/rotate-image",
    "description_url": "https://leetcode.com/problems/rotate-image/description/",
    "description": "<p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p>\n\n<p>You have to rotate the image <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg\" style=\"width: 500px; height: 188px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg\" style=\"width: 500px; height: 201px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\n<strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == matrix.length == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/rotate-image/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rotate(self, matrix: List[List[int]]) -> None:\n    matrix.reverse()\n\n    for i in range(len(matrix)):\n      for j in range(i + 1, len(matrix)):\n        matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void rotate(int[][] matrix) {\n    for (int i = 0, j = matrix.length - 1; i < j; ++i, --j) {\n      int[] temp = matrix[i];\n      matrix[i] = matrix[j];\n      matrix[j] = temp;\n    }\n\n    for (int i = 0; i < matrix.length; ++i)\n      for (int j = i + 1; j < matrix.length; ++j) {\n        final int temp = matrix[i][j];\n        matrix[i][j] = matrix[j][i];\n        matrix[j][i] = temp;\n      }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void rotate(vector<vector<int>>& matrix) {\n    reverse(begin(matrix), end(matrix));\n    for (int i = 0; i < matrix.size(); ++i)\n      for (int j = i + 1; j < matrix.size(); ++j)\n        swap(matrix[i][j], matrix[j][i]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/48.html",
    "category": "Algorithms",
    "acceptance_rate": 77.64814722637496,
    "topics": [
      "Array",
      "Math",
      "Matrix"
    ],
    "hints": [],
    "likes": 18634,
    "dislikes": 894,
    "similar_questions": "[{\"title\": \"Determine Whether Matrix Can Be Obtained By Rotation\", \"titleSlug\": \"determine-whether-matrix-can-be-obtained-by-rotation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"2.9M\", \"totalAcceptedRaw\": 2261940, \"totalSubmissionRaw\": 2913064, \"acRate\": \"77.6%\"}",
    "title_pt": "Rotacionar Imagem",
    "description_pt": "<p>Você recebe uma <code>matrix</code> 2D <code>n x n</code> representando uma imagem; rotacione a imagem em <strong>90</strong> graus (no sentido horário).</p>\n\n<p>Você deve rotacionar a imagem <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a>, o que significa que você deve modificar diretamente a matriz 2D de entrada. <strong>NÃO</strong> aloque outra matriz 2D e faça a rotação.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg\" style=\"width: 500px; height: 188px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Saída:</strong> [[7,4,1],[8,5,2],[9,6,3]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg\" style=\"width: 500px; height: 201px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\n<strong>Saída:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == matrix.length == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "49",
    "paidOnly": false,
    "title": "Group Anagrams",
    "titleSlug": "group-anagrams",
    "url": "https://leetcode.com/problems/group-anagrams",
    "description_url": "https://leetcode.com/problems/group-anagrams/description/",
    "description": "<p>Given an array of strings <code>strs</code>, group the <span data-keyword=\"anagram\">anagrams</span> together. You can return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n\t<li>There is no string in strs that can be rearranged to form <code>&quot;bat&quot;</code>.</li>\n\t<li>The strings <code>&quot;nat&quot;</code> and <code>&quot;tan&quot;</code> are anagrams as they can be rearranged to form each other.</li>\n\t<li>The strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code>, and <code>&quot;tea&quot;</code> are anagrams as they can be rearranged to form each other.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">strs = [&quot;&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[[&quot;&quot;]]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">strs = [&quot;a&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[[&quot;a&quot;]]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/group-anagrams/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n    dict = defaultdict(list)\n\n    for str in strs:\n      key = ''.join(sorted(str))\n      dict[key].append(str)\n\n    return dict.values()",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> groupAnagrams(String[] strs) {\n    Map<String, List<String>> keyToAnagrams = new HashMap<>();\n\n    for (final String str : strs) {\n      char[] chars = str.toCharArray();\n      Arrays.sort(chars);\n      String key = String.valueOf(chars);\n      keyToAnagrams.computeIfAbsent(key, k -> new ArrayList<>()).add(str);\n    }\n\n    return new ArrayList<>(keyToAnagrams.values());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> groupAnagrams(vector<string>& strs) {\n    vector<vector<string>> ans;\n    unordered_map<string, vector<string>> keyToAnagrams;\n\n    for (const string& str : strs) {\n      string key = str;\n      sort(begin(key), end(key));\n      keyToAnagrams[key].push_back(str);\n    }\n\n    for (const auto& [_, anagrams] : keyToAnagrams)\n      ans.push_back(anagrams);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/49.html",
    "category": "Algorithms",
    "acceptance_rate": 70.74386047271634,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Sorting"
    ],
    "hints": [],
    "likes": 20430,
    "dislikes": 684,
    "similar_questions": "[{\"title\": \"Valid Anagram\", \"titleSlug\": \"valid-anagram\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Group Shifted Strings\", \"titleSlug\": \"group-shifted-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Resultant Array After Removing Anagrams\", \"titleSlug\": \"find-resultant-array-after-removing-anagrams\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Anagrams\", \"titleSlug\": \"count-anagrams\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.7M\", \"totalSubmission\": \"5.3M\", \"totalAcceptedRaw\": 3749305, \"totalSubmissionRaw\": 5299829, \"acRate\": \"70.7%\"}",
    "title_pt": "Agrupar Anagramas",
    "description_pt": "<p>Dado um array de strings <code>strs</code>, agrupe os <span data-keyword=\"anagram\">anagramas</span> juntos. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">strs = [&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<ul>\n\t<li>Não há nenhuma string em strs que possa ser rearranjada para formar <code>&quot;bat&quot;</code>.</li>\n\t<li>As strings <code>&quot;nat&quot;</code> e <code>&quot;tan&quot;</code> são anagramas, pois podem ser rearranjadas para formar uma à outra.</li>\n\t<li>As strings <code>&quot;ate&quot;</code>, <code>&quot;eat&quot;</code> e <code>&quot;tea&quot;</code> são anagramas, pois podem ser rearranjadas para formar uma à outra.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">strs = [&quot;&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[[&quot;&quot;]]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">strs = [&quot;a&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[[&quot;a&quot;]]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consiste de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "50",
    "paidOnly": false,
    "title": "Pow(x, n)",
    "titleSlug": "powx-n",
    "url": "https://leetcode.com/problems/powx-n",
    "description_url": "https://leetcode.com/problems/powx-n/description/",
    "description": "<p>Implement <a href=\"http://www.cplusplus.com/reference/valarray/pow/\" target=\"_blank\">pow(x, n)</a>, which calculates <code>x</code> raised to the power <code>n</code> (i.e., <code>x<sup>n</sup></code>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 2.00000, n = 10\n<strong>Output:</strong> 1024.00000\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 2.10000, n = 3\n<strong>Output:</strong> 9.26100\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 2.00000, n = -2\n<strong>Output:</strong> 0.25000\n<strong>Explanation:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-100.0 &lt; x &lt; 100.0</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li>\n\t<li><code>n</code> is an integer.</li>\n\t<li>Either <code>x</code> is not zero or <code>n &gt; 0</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/powx-n/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def myPow(self, x: float, n: int) -> float:\n    if n == 0:\n      return 1\n    if n < 0:\n      return 1 / self.myPow(x, -n)\n    if n & 1:\n      return x * self.myPow(x, n - 1)\n    return self.myPow(x * x, n // 2)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public double myPow(double x, long n) {\n    if (n == 0)\n      return 1;\n    if (n < 0)\n      return 1 / myPow(x, -n);\n    if (n % 2 == 1)\n      return x * myPow(x, n - 1);\n    return myPow(x * x, n / 2);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  double myPow(double x, long n) {\n    if (n == 0)\n      return 1;\n    if (n < 0)\n      return 1 / myPow(x, -n);\n    if (n & 1)\n      return x * myPow(x, n - 1);\n    return myPow(x * x, n / 2);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/50.html",
    "category": "Algorithms",
    "acceptance_rate": 36.87246877880587,
    "topics": [
      "Math",
      "Recursion"
    ],
    "hints": [],
    "likes": 10675,
    "dislikes": 10146,
    "similar_questions": "[{\"title\": \"Sqrt(x)\", \"titleSlug\": \"sqrtx\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Super Pow\", \"titleSlug\": \"super-pow\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Collisions of Monkeys on a Polygon\", \"titleSlug\": \"count-collisions-of-monkeys-on-a-polygon\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.2M\", \"totalSubmission\": \"6M\", \"totalAcceptedRaw\": 2195213, \"totalSubmissionRaw\": 5953567, \"acRate\": \"36.9%\"}",
    "title_pt": "Potência(x, n)",
    "description_pt": "<p>Implemente <a href=\"http://www.cplusplus.com/reference/valarray/pow/\" target=\"_blank\">pow(x, n)</a>, que calcula <code>x</code> elevado à potência <code>n</code> (isto é, <code>x<sup>n</sup></code>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 2.00000, n = 10\n<strong>Saída:</strong> 1024.00000\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 2.10000, n = 3\n<strong>Saída:</strong> 9.26100\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 2.00000, n = -2\n<strong>Saída:</strong> 0.25000\n<strong>Explicação:</strong> 2<sup>-2</sup> = 1/2<sup>2</sup> = 1/4 = 0.25\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-100.0 &lt; x &lt; 100.0</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup>-1</code></li>\n\t<li><code>n</code> é um inteiro.</li>\n\t<li>Ou <code>x</code> não é zero ou <code>n &gt; 0</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sup>n</sup> &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "51",
    "paidOnly": false,
    "title": "N-Queens",
    "titleSlug": "n-queens",
    "url": "https://leetcode.com/problems/n-queens",
    "description_url": "https://leetcode.com/problems/n-queens/description/",
    "description": "<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>\n\n<p>Given an integer <code>n</code>, return <em>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\" />\n<pre>\n<strong>Input:</strong> n = 4\n<strong>Output:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]]\n<strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> [[&quot;Q&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/n-queens/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def solveNQueens(self, n: int) -> List[List[str]]:\n    ans = []\n    cols = [False] * n\n    diag1 = [False] * (2 * n - 1)\n    diag2 = [False] * (2 * n - 1)\n\n    def dfs(i: int, board: List[int]) -> None:\n      if i == n:\n        ans.append(board)\n        return\n\n      for j in range(n):\n        if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:\n          continue\n        cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True\n        dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)])\n        cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False\n\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> solveNQueens(int n) {\n    List<List<String>> ans = new ArrayList<>();\n    char[][] board = new char[n][n];\n\n    for (int i = 0; i < n; ++i)\n      Arrays.fill(board[i], '.');\n\n    dfs(n, 0, new boolean[n], new boolean[2 * n - 1], new boolean[2 * n - 1], board, ans);\n    return ans;\n  }\n\n  private void dfs(int n, int i, boolean[] cols, boolean[] diag1, boolean[] diag2, char[][] board,\n                   List<List<String>> ans) {\n    if (i == n) {\n      ans.add(construct(board));\n      return;\n    }\n\n    for (int j = 0; j < cols.length; ++j) {\n      if (cols[j] || diag1[i + j] || diag2[j - i + n - 1])\n        continue;\n      board[i][j] = 'Q';\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true;\n      dfs(n, i + 1, cols, diag1, diag2, board, ans);\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false;\n      board[i][j] = '.';\n    }\n  }\n\n  private List<String> construct(char[][] board) {\n    List<String> listBoard = new ArrayList<>();\n    for (int i = 0; i < board.length; ++i)\n      listBoard.add(String.valueOf(board[i]));\n    return listBoard;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> solveNQueens(int n) {\n    vector<vector<string>> ans;\n    dfs(n, 0, vector<bool>(n), vector<bool>(2 * n - 1), vector<bool>(2 * n - 1),\n        vector<string>(n, string(n, '.')), ans);\n    return ans;\n  }\n\n private:\n  void dfs(int n, int i, vector<bool>&& cols, vector<bool>&& diag1,\n           vector<bool>&& diag2, vector<string>&& board,\n           vector<vector<string>>& ans) {\n    if (i == n) {\n      ans.push_back(board);\n      return;\n    }\n\n    for (int j = 0; j < n; ++j) {\n      if (cols[j] || diag1[i + j] || diag2[j - i + n - 1])\n        continue;\n      board[i][j] = 'Q';\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true;\n      dfs(n, i + 1, move(cols), move(diag1), move(diag2), move(board), ans);\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false;\n      board[i][j] = '.';\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/51.html",
    "category": "Algorithms",
    "acceptance_rate": 72.40869046870179,
    "topics": [
      "Array",
      "Backtracking"
    ],
    "hints": [],
    "likes": 13211,
    "dislikes": 320,
    "similar_questions": "[{\"title\": \"N-Queens II\", \"titleSlug\": \"n-queens-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Grid Illumination\", \"titleSlug\": \"grid-illumination\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"966.9K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 966907, \"totalSubmissionRaw\": 1335346, \"acRate\": \"72.4%\"}",
    "title_pt": "N-Rainhas",
    "description_pt": "<p>O problema das <strong>n-rainhas</strong> consiste em posicionar <code>n</code> rainhas em um tabuleiro de xadrez <code>n x n</code> de forma que nenhuma duas rainhas ataquem uma à outra.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>todas as soluções distintas do <strong>problema das n-rainhas</strong></em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>Cada solução contém uma configuração distinta do tabuleiro para o posicionamento das n-rainhas, em que <code>&#39;Q&#39;</code> e <code>&#39;.&#39;</code> indicam, respectivamente, uma rainha e um espaço vazio.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\" />\n<pre>\n<strong>Entrada:</strong> n = 4\n<strong>Saída:</strong> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]]\n<strong>Explicação:</strong> Existem duas soluções distintas para o problema das 4-rainhas, como mostrado acima\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [[&quot;Q&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "52",
    "paidOnly": false,
    "title": "N-Queens II",
    "titleSlug": "n-queens-ii",
    "url": "https://leetcode.com/problems/n-queens-ii",
    "description_url": "https://leetcode.com/problems/n-queens-ii/description/",
    "description": "<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>\n\n<p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\" />\n<pre>\n<strong>Input:</strong> n = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/n-queens-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def totalNQueens(self, n: int) -> int:\n    ans = 0\n    cols = [False] * n\n    diag1 = [False] * (2 * n - 1)\n    diag2 = [False] * (2 * n - 1)\n\n    def dfs(i: int) -> None:\n      nonlocal ans\n      if i == n:\n        ans += 1\n        return\n\n      for j in range(n):\n        if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:\n          continue\n        cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True\n        dfs(i + 1)\n        cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False\n\n    dfs(0)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int totalNQueens(int n) {\n    dfs(n, 0, new boolean[n], new boolean[2 * n - 1], new boolean[2 * n - 1]);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  private void dfs(int n, int i, boolean[] cols, boolean[] diag1, boolean[] diag2) {\n    if (i == n) {\n      ++ans;\n      return;\n    }\n\n    for (int j = 0; j < cols.length; ++j) {\n      if (cols[j] || diag1[i + j] || diag2[j - i + n - 1])\n        continue;\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true;\n      dfs(n, i + 1, cols, diag1, diag2);\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false;\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int totalNQueens(int n) {\n    int ans = 0;\n    dfs(n, 0, vector<bool>(n), vector<bool>(2 * n - 1), vector<bool>(2 * n - 1),\n        ans);\n    return ans;\n  }\n\n private:\n  void dfs(int n, int i, vector<bool>&& cols, vector<bool>&& diag1,\n           vector<bool>&& diag2, int& ans) {\n    if (i == n) {\n      ++ans;\n      return;\n    }\n\n    for (int j = 0; j < n; ++j) {\n      if (cols[j] || diag1[i + j] || diag2[j - i + n - 1])\n        continue;\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = true;\n      dfs(n, i + 1, move(cols), move(diag1), move(diag2), ans);\n      cols[j] = diag1[i + j] = diag2[j - i + n - 1] = false;\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/52.html",
    "category": "Algorithms",
    "acceptance_rate": 76.50912104834367,
    "topics": [
      "Backtracking"
    ],
    "hints": [],
    "likes": 4063,
    "dislikes": 274,
    "similar_questions": "[{\"title\": \"N-Queens\", \"titleSlug\": \"n-queens\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"487.4K\", \"totalSubmission\": \"637K\", \"totalAcceptedRaw\": 487390, \"totalSubmissionRaw\": 637036, \"acRate\": \"76.5%\"}",
    "title_pt": "N-Rainhas II",
    "description_pt": "<p>O problema das <strong>n-rainhas</strong> consiste em posicionar <code>n</code> rainhas em um tabuleiro de xadrez <code>n x n</code> de modo que nenhuma duas rainhas se ataquem.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>o número de soluções distintas para o&nbsp;<strong>problema das n-rainhas</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/queens.jpg\" style=\"width: 600px; height: 268px;\" />\n<pre>\n<strong>Entrada:</strong> n = 4\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Há duas soluções distintas para o problema das 4-rainhas, como mostrado.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "53",
    "paidOnly": false,
    "title": "Maximum Subarray",
    "titleSlug": "maximum-subarray",
    "url": "https://leetcode.com/problems/maximum-subarray",
    "description_url": "https://leetcode.com/problems/maximum-subarray/description/",
    "description": "<p>Given an integer array <code>nums</code>, find the <span data-keyword=\"subarray-nonempty\">subarray</span> with the largest sum, and return <em>its sum</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The subarray [4,-1,2,1] has the largest sum 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The subarray [1] has the largest sum 1.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [5,4,-1,7,8]\n<strong>Output:</strong> 23\n<strong>Explanation:</strong> The subarray [5,4,-1,7,8] has the largest sum 23.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>\n",
    "solution_url": "https://leetcode.com/problems/maximum-subarray/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxSubArray(self, nums: List[int]) -> int:\n    ans = -math.inf\n    summ = 0\n\n    for num in nums:\n      summ += num\n      ans = max(ans, summ)\n      summ = max(summ, 0)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxSubArray(int[] nums) {\n    int ans = Integer.MIN_VALUE;\n    int sum = 0;\n\n    for (final int num : nums) {\n      sum += num;\n      ans = Math.max(ans, sum);\n      sum = Math.max(sum, 0);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxSubArray(vector<int>& nums) {\n    int ans = INT_MIN;\n    int sum = 0;\n\n    for (const int num : nums) {\n      sum += num;\n      ans = max(ans, sum);\n      sum = max(sum, 0);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/53.html",
    "category": "Algorithms",
    "acceptance_rate": 51.98742458804949,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 35618,
    "dislikes": 1509,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock\", \"titleSlug\": \"best-time-to-buy-and-sell-stock\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Product Subarray\", \"titleSlug\": \"maximum-product-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Degree of an Array\", \"titleSlug\": \"degree-of-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Longest Turbulent Subarray\", \"titleSlug\": \"longest-turbulent-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Score Of Spliced Array\", \"titleSlug\": \"maximum-score-of-spliced-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Absolute Sum of Any Subarray\", \"titleSlug\": \"maximum-absolute-sum-of-any-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Subarray Sum After One Operation\", \"titleSlug\": \"maximum-subarray-sum-after-one-operation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Substring With Largest Variance\", \"titleSlug\": \"substring-with-largest-variance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Subarrays With Score Less Than K\", \"titleSlug\": \"count-subarrays-with-score-less-than-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Value of a String in an Array\", \"titleSlug\": \"maximum-value-of-a-string-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Substring With Maximum Cost\", \"titleSlug\": \"find-the-substring-with-maximum-cost\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Items With the Maximum Sum\", \"titleSlug\": \"k-items-with-the-maximum-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Good Subarray Sum\", \"titleSlug\": \"maximum-good-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximize Subarray Sum After Removing All Occurrences of One Element\", \"titleSlug\": \"maximize-subarray-sum-after-removing-all-occurrences-of-one-element\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.9M\", \"totalSubmission\": \"9.5M\", \"totalAcceptedRaw\": 4920165, \"totalSubmissionRaw\": 9464152, \"acRate\": \"52.0%\"}",
    "title_pt": "Subarray Máximo",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, encontre o <span data-keyword=\"subarray-nonempty\">subarray</span> com a maior soma e retorne <em>sua soma</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O subarray [4,-1,2,1] tem a maior soma 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> O subarray [1] tem a maior soma 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [5,4,-1,7,8]\n<strong>Saída:</strong> 23\n<strong>Explicação:</strong> O subarray [5,4,-1,7,8] tem a maior soma 23.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Se você já descobriu a solução em <code>O(n)</code>, tente codificar outra solução usando a abordagem de <strong>divide and conquer</strong>, que é mais sutil.</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "54",
    "paidOnly": false,
    "title": "Spiral Matrix",
    "titleSlug": "spiral-matrix",
    "url": "https://leetcode.com/problems/spiral-matrix",
    "description_url": "https://leetcode.com/problems/spiral-matrix/description/",
    "description": "<p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Output:</strong> [1,2,3,6,9,8,7,4,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n<strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10</code></li>\n\t<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/spiral-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n    if not matrix:\n      return []\n\n    m = len(matrix)\n    n = len(matrix[0])\n    ans = []\n    r1 = 0\n    c1 = 0\n    r2 = m - 1\n    c2 = n - 1\n\n    # Repeatedly add matrix[r1..r2][c1..c2] to ans\n    while len(ans) < m * n:\n      j = c1\n      while j <= c2 and len(ans) < m * n:\n        ans.append(matrix[r1][j])\n        j += 1\n      i = r1 + 1\n      while i <= r2 - 1 and len(ans) < m * n:\n        ans.append(matrix[i][c2])\n        i += 1\n      j = c2\n      while j >= c1 and len(ans) < m * n:\n        ans.append(matrix[r2][j])\n        j -= 1\n      i = r2 - 1\n      while i >= r1 + 1 and len(ans) < m * n:\n        ans.append(matrix[i][c1])\n        i -= 1\n      r1 += 1\n      c1 += 1\n      r2 -= 1\n      c2 -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> spiralOrder(int[][] matrix) {\n    if (matrix.length == 0)\n      return new ArrayList<>();\n\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    List<Integer> ans = new ArrayList<>();\n    int r1 = 0;\n    int c1 = 0;\n    int r2 = m - 1;\n    int c2 = n - 1;\n\n    // Repeatedly add matrix[r1..r2][c1..c2] to ans\n    while (ans.size() < m * n) {\n      for (int j = c1; j <= c2 && ans.size() < m * n; ++j)\n        ans.add(matrix[r1][j]);\n      for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i)\n        ans.add(matrix[i][c2]);\n      for (int j = c2; j >= c1 && ans.size() < m * n; --j)\n        ans.add(matrix[r2][j]);\n      for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i)\n        ans.add(matrix[i][c1]);\n      ++r1;\n      ++c1;\n      --r2;\n      --c2;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> spiralOrder(vector<vector<int>>& matrix) {\n    if (matrix.empty())\n      return {};\n\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    vector<int> ans;\n    int r1 = 0;\n    int c1 = 0;\n    int r2 = m - 1;\n    int c2 = n - 1;\n\n    // Repeatedly add matrix[r1..r2][c1..c2] to ans\n    while (ans.size() < m * n) {\n      for (int j = c1; j <= c2 && ans.size() < m * n; ++j)\n        ans.push_back(matrix[r1][j]);\n      for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i)\n        ans.push_back(matrix[i][c2]);\n      for (int j = c2; j >= c1 && ans.size() < m * n; --j)\n        ans.push_back(matrix[r2][j]);\n      for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i)\n        ans.push_back(matrix[i][c1]);\n      ++r1, ++c1, --r2, --c2;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/54.html",
    "category": "Algorithms",
    "acceptance_rate": 53.61208262148119,
    "topics": [
      "Array",
      "Matrix",
      "Simulation"
    ],
    "hints": [
      "Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do.",
      "We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column, and then we move inwards by 1 and repeat. That's all. That is all the simulation that we need.",
      "Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'll shift in the same column. Similarly, by changing values for j, you'd be shifting in the same row.\r\nAlso, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to simulate edge cases like a single column or a single row to see if anything breaks or not."
    ],
    "likes": 15993,
    "dislikes": 1430,
    "similar_questions": "[{\"title\": \"Spiral Matrix II\", \"titleSlug\": \"spiral-matrix-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Spiral Matrix III\", \"titleSlug\": \"spiral-matrix-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Spiral Matrix IV\", \"titleSlug\": \"spiral-matrix-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 1896957, \"totalSubmissionRaw\": 3538300, \"acRate\": \"53.6%\"}",
    "title_pt": "Matriz em Espiral",
    "description_pt": "<p>Dada uma <code>matrix</code> de <code>m x n</code>, retorne <em>todos os elementos da</em> <code>matrix</code> <em>em ordem espiral</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Saída:</strong> [1,2,3,6,9,8,7,4,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n<strong>Saída:</strong> [1,2,3,4,8,12,11,10,9,5,6,7]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10</code></li>\n\t<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Bem, para alguns problemas, a melhor maneira realmente é criar alguns algoritmos de simulação. Basicamente, você precisa simular o que o problema nos pede para fazer.",
      "Dica 2: Percorremos fronteira por fronteira e avançamos para dentro. Essa é a operação essencial. Primeira linha, última coluna, última linha, primeira coluna e então avançamos para dentro em 1 e repetimos. Isso é tudo. Essa é toda a simulação de que precisamos.",
      "Dica 3: Pense em quando você quer alternar o progresso em um dos índices. Se você progredir em i em [i, j], você se deslocará na mesma coluna. Da mesma forma, ao mudar os valores de j, você se deslocará na mesma linha.\nAlém disso, acompanhe o fim de uma fronteira para que você possa avançar para dentro e então continuar repetindo. Sempre é melhor simular casos extremos, como uma única coluna ou uma única linha, para ver se algo quebra ou não."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "55",
    "paidOnly": false,
    "title": "Jump Game",
    "titleSlug": "jump-game",
    "url": "https://leetcode.com/problems/jump-game",
    "description_url": "https://leetcode.com/problems/jump-game/description/",
    "description": "<p>You are given an integer array <code>nums</code>. You are initially positioned at the array&#39;s <strong>first index</strong>, and each element in the array represents your maximum jump length at that position.</p>\n\n<p>Return <code>true</code><em> if you can reach the last index, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,1,1,4]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Jump 1 step from index 0 to 1, then 3 steps to the last index.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,1,0,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/jump-game/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canJump(self, nums: List[int]) -> bool:\n    i = 0\n    reach = 0\n\n    while i < len(nums) and i <= reach:\n      reach = max(reach, i + nums[i])\n      i += 1\n\n    return i == len(nums)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canJump(int[] nums) {\n    int i = 0;\n\n    for (int reach = 0; i < nums.length && i <= reach; ++i)\n      reach = Math.max(reach, i + nums[i]);\n\n    return i == nums.length;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canJump(vector<int>& nums) {\n    int i = 0;\n\n    for (int reach = 0; i < nums.size() && i <= reach; ++i)\n      reach = max(reach, i + nums[i]);\n\n    return i == nums.size();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/55.html",
    "category": "Algorithms",
    "acceptance_rate": 39.34269964341027,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy"
    ],
    "hints": [],
    "likes": 20508,
    "dislikes": 1387,
    "similar_questions": "[{\"title\": \"Jump Game II\", \"titleSlug\": \"jump-game-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game III\", \"titleSlug\": \"jump-game-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game VII\", \"titleSlug\": \"jump-game-vii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Jump Game VIII\", \"titleSlug\": \"jump-game-viii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Visited Cells in a Grid\", \"titleSlug\": \"minimum-number-of-visited-cells-in-a-grid\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Largest Element in an Array after Merge Operations\", \"titleSlug\": \"largest-element-in-an-array-after-merge-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.6M\", \"totalSubmission\": \"6.6M\", \"totalAcceptedRaw\": 2587025, \"totalSubmissionRaw\": 6575617, \"acRate\": \"39.3%\"}",
    "title_pt": "Jogo do Salto",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code>. Inicialmente, você está posicionado no <strong>primeiro índice</strong> do array, e cada elemento no array representa o comprimento máximo do salto nessa posição.</p>\n\n<p>Retorne <code>true</code><em> se você puder alcançar o último índice, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,1,1,4]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Salte 1 passo do índice 0 para 1, depois 3 passos até o último índice.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,1,0,4]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Você sempre chegará ao índice 3, não importa o que aconteça. Seu comprimento máximo de salto é 0, o que torna impossível alcançar o último índice.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "56",
    "paidOnly": false,
    "title": "Merge Intervals",
    "titleSlug": "merge-intervals",
    "url": "https://leetcode.com/problems/merge-intervals",
    "description_url": "https://leetcode.com/problems/merge-intervals/description/",
    "description": "<p>Given an array&nbsp;of <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, merge all overlapping intervals, and return <em>an array of the non-overlapping intervals that cover all the intervals in the input</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]\n<strong>Output:</strong> [[1,6],[8,10],[15,18]]\n<strong>Explanation:</strong> Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,4],[4,5]]\n<strong>Output:</strong> [[1,5]]\n<strong>Explanation:</strong> Intervals [1,4] and [4,5] are considered overlapping.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/merge-intervals/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div>\n    <div class=\"video-container\">\n        <iframe src=\"https://player.vimeo.com/video/471861267\" width=\"640\" height=\"360\" frameborder=\"0\" allow=\"autoplay; fullscreen\" allowfullscreen></iframe>\n    </div>\n</div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Connected Components\n\n**Intuition**\n\nIf we draw a graph (with intervals as nodes) that contains undirected edges between all pairs of intervals that overlap, then all intervals in each *connected component* of the graph can be merged into a single interval.\n\n**Algorithm**\n\nWith the above intuition in mind, we can represent the graph as an adjacency list, inserting directed edges in both directions to simulate undirected edges. Then, to determine which connected component each node is in, we perform graph traversals from arbitrary unvisited nodes until all nodes have been visited. To do this efficiently, we store visited nodes in a `Set`, allowing for constant time containment checks and insertion. Finally, we consider each connected component, merging all of its intervals by constructing a new `Interval` with `start` equal to the minimum start among them and `end` equal to the maximum end.\n\nThis algorithm is correct simply because it is basically the brute force solution. We compare every interval to every other interval, so we know exactly which intervals overlap. The reason for the connected component search is that two intervals may not directly overlap, but might overlap indirectly via a third interval. See the example below to see this more clearly.\n\n![Components Example](../Figures/56/component.png)\n\nAlthough (1, 5) and (6, 10) do not directly overlap, either would overlap with the other if first merged with (4, 7). There are two connected components, so if we merge their nodes, we expect to get the following two merged intervals:\n\n(1, 10), (15, 20)\n\n\n<iframe src=\"https://leetcode.com/playground/VH5daGtY/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VH5daGtY\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$\n\n    Building the graph costs $$O(V + E) = O(V) + O(E) = O(n) + O(n^2) = O(n^2)$$ time, as in the worst case all intervals are mutually overlapping. Traversing the graph has the same cost (although it might appear higher at first) because our `visited` set guarantees that each node will be visited exactly once. Finally, because each node is part of exactly one component, the merge step costs $$O(V) = O(n)$$ time. This all adds up as follows:\n\n    $$\n        O(n^2) + O(n^2) + O(n) = O(n^2)\n    $$\n\n* Space complexity : $$O(n^2)$$\n\n    As previously mentioned, in the worst case, all intervals are mutually overlapping, so there will be an edge for every pair of intervals. Therefore, the memory footprint is quadratic in the input size.\n\n<br/>\n\n---\n\n### Approach 2: Sorting\n\n**Intuition**\n\nIf we sort the intervals by their `start` value, then each set of intervals that can be merged will appear as a contiguous \"run\" in the sorted list.\n\n**Algorithm**\n\nFirst, we sort the list as described. Then, we insert the first interval into our `merged` list and continue considering each interval in turn as follows: If the current interval begins *after* the previous interval ends, then they do not overlap and we can append the current interval to `merged`. Otherwise, they do overlap, and we merge them by updating the `end` of the previous interval if it is less than the `end` of the current interval.\n\nA simple proof by contradiction shows that this algorithm always produces the correct answer. First, suppose that the algorithm at some point fails to merge two intervals that should be merged. This would imply that there exists some triple of indices $$i$$, $$j$$, and $$k$$ in a list of intervals $$\\text{ints}$$ such that $$i < j < k$$ and ($$\\text{ints[i]}$$, $$\\text{ints[k]}$$) can be merged, but neither ($$\\text{ints[i]}$$, $$\\text{ints[j]}$$) nor ($$\\text{ints[j]}$$, $$\\text{ints[k]}$$) can be merged. From this scenario follow several inequalities:\n\n$$\n\\begin{aligned}\n    \\text{ints[i].end} < \\text{ints[j].start} \\\\\n    \\text{ints[j].end} < \\text{ints[k].start} \\\\\n    \\text{ints[i].end} \\geq \\text{ints[k].start} \\\\\n\\end{aligned}\n$$\n\nWe can chain these inequalities (along with the following inequality, implied by the well-formedness of the intervals: $$\\text{ints[j].start} \\leq \\text{ints[j].end}$$) to demonstrate a contradiction:\n\n$$\n\\begin{aligned}\n    \\text{ints[i].end} < \\text{ints[j].start} \\leq \\text{ints[j].end} < \\text{ints[k].start} \\\\\n    \\text{ints[i].end} \\geq \\text{ints[k].start}\n\\end{aligned}\n$$\n\nTherefore, all mergeable intervals must occur in a contiguous run of the sorted list.\n\n![Sorting Example](../Figures/56/sort.png)\n\n\nConsider the example above, where the intervals are sorted, and then all mergeable intervals form contiguous blocks.\n\n<iframe src=\"https://leetcode.com/playground/95HUcjnF/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"95HUcjnF\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n\\log{}n)$$\n\n    Other than the `sort` invocation, we do a simple linear scan of the list, so the runtime is dominated by the $$O(n\\log{}n)$$ complexity of sorting.\n\n* Space complexity : $$O(\\log N)$$ (or $$O(n)$$)\n\n    If we can sort `intervals` in place, we do not need more than constant additional space, although the sorting itself takes $$O(\\log n)$$ space. Otherwise, we must allocate linear space to store a copy of `intervals` and sort that.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n    ans = []\n\n    for interval in sorted(intervals):\n      if not ans or ans[-1][1] < interval[0]:\n        ans.append(interval)\n      else:\n        ans[-1][1] = max(ans[-1][1], interval[1])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] merge(int[][] intervals) {\n    List<int[]> ans = new ArrayList<>();\n\n    Arrays.sort(intervals, (a, b) -> (a[0] - b[0]));\n\n    for (int[] interval : intervals)\n      if (ans.isEmpty() || ans.get(ans.size() - 1)[1] < interval[0])\n        ans.add(interval);\n      else\n        ans.get(ans.size() - 1)[1] = Math.max(ans.get(ans.size() - 1)[1], interval[1]);\n\n    return ans.toArray(new int[ans.size()][]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> merge(vector<vector<int>>& intervals) {\n    vector<vector<int>> ans;\n\n    sort(begin(intervals), end(intervals));\n\n    for (const vector<int>& interval : intervals)\n      if (ans.empty() || ans.back()[1] < interval[0])\n        ans.push_back(interval);\n      else\n        ans.back()[1] = max(ans.back()[1], interval[1]);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/56.html",
    "category": "Algorithms",
    "acceptance_rate": 49.21381211115299,
    "topics": [
      "Array",
      "Sorting"
    ],
    "hints": [],
    "likes": 23328,
    "dislikes": 848,
    "similar_questions": "[{\"title\": \"Insert Interval\", \"titleSlug\": \"insert-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms\", \"titleSlug\": \"meeting-rooms\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms II\", \"titleSlug\": \"meeting-rooms-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Teemo Attacking\", \"titleSlug\": \"teemo-attacking\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Bold Tag in String\", \"titleSlug\": \"add-bold-tag-in-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Module\", \"titleSlug\": \"range-module\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Employee Free Time\", \"titleSlug\": \"employee-free-time\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Partition Labels\", \"titleSlug\": \"partition-labels\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Interval List Intersections\", \"titleSlug\": \"interval-list-intersections\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Amount of New Area Painted Each Day\", \"titleSlug\": \"amount-of-new-area-painted-each-day\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Substring of One Repeating Character\", \"titleSlug\": \"longest-substring-of-one-repeating-character\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Integers in Intervals\", \"titleSlug\": \"count-integers-in-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Divide Intervals Into Minimum Number of Groups\", \"titleSlug\": \"divide-intervals-into-minimum-number-of-groups\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Determine if Two Events Have Conflict\", \"titleSlug\": \"determine-if-two-events-have-conflict\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Ways to Group Overlapping Ranges\", \"titleSlug\": \"count-ways-to-group-overlapping-ranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Points That Intersect With Cars\", \"titleSlug\": \"points-that-intersect-with-cars\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Days Without Meetings\", \"titleSlug\": \"count-days-without-meetings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimize Connected Groups by Inserting Interval\", \"titleSlug\": \"minimize-connected-groups-by-inserting-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.2M\", \"totalSubmission\": \"6.4M\", \"totalAcceptedRaw\": 3153388, \"totalSubmissionRaw\": 6407540, \"acRate\": \"49.2%\"}",
    "title_pt": "Mesclar Intervalos",
    "description_pt": "<p>Dado um array&nbsp;de <code>intervals</code>&nbsp;em que <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, mescle todos os intervalos sobrepostos e retorne <em>um array dos intervalos não sobrepostos que cobrem todos os intervalos na entrada</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,3],[2,6],[8,10],[15,18]]\n<strong>Saída:</strong> [[1,6],[8,10],[15,18]]\n<strong>Explicação:</strong> Como os intervalos [1,3] e [2,6] se sobrepõem, mescle-os em [1,6].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,4],[4,5]]\n<strong>Saída:</strong> [[1,5]]\n<strong>Explicação:</strong> Os intervalos [1,4] e [4,5] são considerados sobrepostos.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "57",
    "paidOnly": false,
    "title": "Insert Interval",
    "titleSlug": "insert-interval",
    "url": "https://leetcode.com/problems/insert-interval",
    "description_url": "https://leetcode.com/problems/insert-interval/description/",
    "description": "<p>You are given an array of non-overlapping intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> represent the start and the end of the <code>i<sup>th</sup></code> interval and <code>intervals</code> is sorted in ascending order by <code>start<sub>i</sub></code>. You are also given an interval <code>newInterval = [start, end]</code> that represents the start and end of another interval.</p>\n\n<p>Insert <code>newInterval</code> into <code>intervals</code> such that <code>intervals</code> is still sorted in ascending order by <code>start<sub>i</sub></code> and <code>intervals</code> still does not have any overlapping intervals (merge overlapping intervals if necessary).</p>\n\n<p>Return <code>intervals</code><em> after the insertion</em>.</p>\n\n<p><strong>Note</strong> that you don&#39;t need to modify <code>intervals</code> in-place. You can make a new array and return it.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]\n<strong>Output:</strong> [[1,5],[6,9]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\n<strong>Output:</strong> [[1,2],[3,10],[12,16]]\n<strong>Explanation:</strong> Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>intervals</code> is sorted by <code>start<sub>i</sub></code> in <strong>ascending</strong> order.</li>\n\t<li><code>newInterval.length == 2</code></li>\n\t<li><code>0 &lt;= start &lt;= end &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/insert-interval/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a sorted list of non-overlapping `intervals` and a `newInterval`. The task is to insert the `newInterval` into the `intervals` while maintaining sorted order and ensuring no overlapping intervals. If there is any overlap, the overlapping intervals should be merged. In the end, return the intervals list with the addition of the new intervals.\n\nTwo key observations are crucial for this problem:\n1. The given intervals are already sorted in ascending order based on the start values.\n2. Initially, the intervals are non-overlapping, but inserting a new interval might lead to overlaps that need resolution by merging while maintaining sorted order.\n\nTo solve this problem, we break it into three cases when comparing the current interval with the new interval:\nCase 1. The current interval ends before the new interval starts.\nCase 2. There is an overlap, and the intervals need merging.\nCase 3. The current interval starts after the new interval ends.\n\nA visual representation below illustrates all three scenarios:\n\n![img](../Figures/57_re/1.png)\n\n\nNow let us consider the given problem description example with `intervals` and a `newInterval`:\n```\nintervals = [[1, 3], [6, 9]]\nnewInterval = [2, 5]\n```\n\nThe first interval starts at 1 and ends at 3, while the second interval starts at 6 and ends at 9. The goal is to insert the `newInterval` into the existing list of `intervals`, maintaining sorted order.\n\nUpon analysis, we observe that the `newInterval` [2, 5] overlaps with the first interval [1, 3] because 2 is less than 3. Now, since we know the intervals need to be merged, we must ensure the merged interval covers the entire overlapping region.\n\nTo achieve this, we take the maximum of the end of the first interval and the end of the new interval, as well as the minimum of the start of the first interval and the start of the new interval. Therefore, the merged interval becomes `[min(1, 2), max(3, 5)] = [1, 5]`.\n\nMoving on to the second interval [6, 9], its starting point (6) comes after the new interval's ending point (5). There is no overlap between them. Therefore, the second interval remains unchanged.\n\n\n| Original Intervals | New Interval | Action                     | Resulting Intervals |\n|-------------------- |--------------|---------------------------- |----------------------|\n|      [1,3]          |   [2,5]      | New interval overlaps with the first interval [1,3]. Merge intervals by taking [min(1, 2), max(3, 5)] = [1, 5]. |      [1,5]           |\n|      [6,9]          |              | No overlap with the new interval [2,5]. Interval remains unchanged. |      [6,9]           |\n\nIn conclusion, the final result is [[1, 5], [6, 9]], representing the intervals after inserting and merging the new interval [2, 5].\n\nIn a concrete business context, this problem may be presented as follows: Suppose we have an array representing video watch times, where each segment consists of the start and stop times of a user watching a video. The task is to calculate the total number of unique minutes watched across all the video segments. This is fundamentally the same question.\n\n> We recommend solving [Merge Intervals](https://leetcode.com/problems/merge-intervals/) problem before attempting this question, as it provides valuable insights into pattern recognition. This question is an extension of the Merge Intervals concept, building upon the same principles.\n\n---\n\n### Approach 1: Linear Search\n\n#### Intuition\n\nWe can do a linear search by iterating through all the intervals and checking which one of the three conditions the intervals fall under:\n\n1. **No Overlaps before Merging:**\n   - This occurs when the current interval ends before the new interval starts.\n\n2. **Overlapping and Merging:**\n   - This occurs when the starting point of the current interval is less than or equal to the ending point of the new interval (`newInterval[1]`), indicating an overlap. We can merge the current interval with the new interval by updating the start and end values of the new interval.\n\n3. **No Overlapping after Merging:**\n   - This occurs when the current interval starts after the new interval ends.\n\n##### 1. Identifying Non-Overlapping Intervals Before Merging:\nWe iterate through all intervals, checking whether the endpoint of the current interval (`intervals[i][1]`) is less than the starting point of the new interval (`newInterval[0]`). If this condition holds true, it indicates there is no overlap before merging, and we add the current interval to the result.\n\n##### 2. Identifying and Merging Overlapping Intervals:\nDuring the iteration, we identify overlap by comparing the endpoint of the new interval (`newInterval[1]`) with the starting point of the current interval (`intervals[i][0]`). When an overlap is detected, we merge the intervals by updating the start and end values of the new interval. The index (`i`) is then incremented to move to the next interval. After merging, the new interval is added to the result.\n\n##### 3. Identifying Non-Overlapping Intervals After Merging:\nAs we have already added the non-overlapping intervals before `newInterval` and merged overlapping ones, the remaining intervals after are guaranteed not to overlap with the newly merged interval. We simply add these remaining intervals to the result.\n\nThe following slideshow illustrates how the linear search algorithm is employed:\n\n!?!../Documents/57/57_LS.json:945,480!?!\n\n#### Algorithm\n\n- Initialize variables `n` and `i` to store the size of intervals and the current index, respectively, and an empty array `res` to store the result.\n- Case 1: No Overlap Before Insertion:\n    - Loop through intervals while `i` is less than `n` and the current interval's endpoint (`intervals[i][1]`) is less than the new interval's start point (`newInterval[0]`).\n    - Add the current interval from intervals to the `res` array.\n    - Increment `i` to move to the next interval.\n- Case 2: Overlap and Merge:\n    - Loop through intervals while `i` is less than `n` and the new interval's endpoint (`newInterval[1]`) is greater than or equal to the current interval's start point (`intervals[i][0]`).\n    - Update the newInterval's start point to the minimum of its current start and the current interval's start.\n    - Update the newInterval's endpoint to the maximum of its current end and the current interval's end.\n    - This essentially merges overlapping intervals into a single larger interval.\n    - Increment `i` to move to the next interval.\n- Add the updated `newInterval` to the `res` array, representing the merged interval.\n- Case 3: No overlap after insertion:\n    - Loop through the remaining intervals (from index `i`) and add them to the `res` array.\n        - This includes intervals that occur after the new interval and those that don't overlap, as they have already been correctly inserted in the previous iterations (previous two cases).\n- Return the `res` array containing all intervals with the new interval inserted correctly.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/XFeK8AcX/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"XFeK8AcX\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of intervals.\n\n* Time complexity: $O(N)$\n\n    We iterate through the intervals once, and each interval is considered and processed only once.\n\n* Space complexity: $O(1)$\n\n    We only use the result (`res`) array to store output, so this could be considered $O(1)$.\n\n---\n\n### Approach 2: Binary Search\n\n#### Intuition\n\nTo apply binary search to a problem, a crucial requirement is that the input should have a monotonically increasing or decreasing nature. In our given scenario, it is explicitly stated that the input is already sorted with respect to the start value, indicating a monotonically increasing order. Therefore, we can confidently consider applying binary search.\n\n##### 1. Finding the Insertion Position\nAs the intervals are sorted by start value, we perform a binary search comparing the starting point of the current interval (`intervals[mid][0]`) with the starting point of the new interval (`target`). If `intervals[mid][0]` is less than the target, it indicates that the insertion point should be to the right of the current position. Consequently, we update `left` to `mid + 1`. If it's greater, the insertion point should be to the left, so we update `right` to `mid - 1`. This process continues until `left` becomes greater than `right`, revealing the correct insertion position.\n\n##### 2. Handling Merging\n1. If `res` is empty or the end of the last interval in `res` is less than the starting point of the current interval, it indicates there is no overlap before merging. The current interval is directly added to `res` in such cases.\n2. If an overlap is detected, signifying the need for merging, the current interval is merged with the last interval in `res`. The end of the last interval in `res` is updated to the maximum of its current end and the end of the current interval.\n\nThe following slideshow illustrates how the binary search algorithm is employed:\n\n!?!../Documents/57/57_BS.json:930,315!?!\n\n#### Algorithm\n\n- If `intervals` is empty, it means there are no existing intervals, so we can simply return a array containing the `newInterval`.\n- Perform a binary search to find the correct position to insert the new interval in the `intervals` array. It updates the values of `left` and `right` based on the comparison of the target value with the first element of the interval at the middle index.\n    - Initialize the variables `target` with the starting point of `newInterval` (i.e., `newInterval[0]`), `left` with 0, and `right` with `n - 1` to define the search space in the `intervals` array.\n    - Perform a binary search by repeatedly dividing the search space in half until `left` is greater than `right`.\n    - Calculate the middle index `mid` as the average of `left` and `right`.\n    - If the start of the interval at index `mid` is less than the target value, update `left` to `mid + 1` to search the right half of the search space. Otherwise, update `right` to `mid - 1` to search the left half of the search space.\n    - The search updates `left` and `right` until they converge to the correct position. Repeat until `left` is greater than `right`.\n- Use `intervals.insert(intervals.begin() + left, newInterval)` to insert the `newInterval` at the correct position.\n- Initialize an empty array `res` to store the result.\n- Iterate through the sorted intervals.\n    - Check if `res` is empty or if the end of the last interval in `res` is less than the start of the current interval. If either condition is true, add the current interval to `res`.\n    - If there is an overlap, update the endpoint of the last interval in `res` to cover the current interval. This step ensures that non-overlapping intervals are added directly, and overlapping intervals are merged.\n- The final merged and inserted intervals are stored in the `res` array, which is then returned.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Rg6hYgzg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Rg6hYgzg\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of intervals.\n\n* Time complexity: $O(N)$\n\n    The binary search for finding the position to insert the `newInterval` has a time complexity of $O(\\log N)$. However, the insertion of the `newInterval` into the list may take $O(N)$ time in the worst case, as it could involve shifting elements within the list. Consequently, the overall time complexity is $O(N + \\log N)$, which simplifies to $O(N)$.\n\n* Space complexity: $O(N)$\n\n    We use the additional space to store the result (`res`) and perform calculations using `res,` so it does count towards the space complexity. In the worst case, the size of `res` will be proportional to the number of intervals in the input list.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n    n = len(intervals)\n    ans = []\n    i = 0\n\n    while i < n and intervals[i][1] < newInterval[0]:\n      ans.append(intervals[i])\n      i += 1\n\n    while i < n and intervals[i][0] <= newInterval[1]:\n      newInterval[0] = min(newInterval[0], intervals[i][0])\n      newInterval[1] = max(newInterval[1], intervals[i][1])\n      i += 1\n\n    ans.append(newInterval)\n\n    while i < n:\n      ans.append(intervals[i])\n      i += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] insert(int[][] intervals, int[] newInterval) {\n    final int n = intervals.length;\n    List<int[]> ans = new ArrayList<>();\n    int i = 0;\n\n    while (i < n && intervals[i][1] < newInterval[0])\n      ans.add(intervals[i++]);\n\n    while (i < n && intervals[i][0] <= newInterval[1]) {\n      newInterval[0] = Math.min(newInterval[0], intervals[i][0]);\n      newInterval[1] = Math.max(newInterval[1], intervals[i][1]);\n      ++i;\n    }\n\n    ans.add(newInterval);\n\n    while (i < n)\n      ans.add(intervals[i++]);\n\n    return ans.toArray(new int[ans.size()][]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> insert(vector<vector<int>>& intervals,\n                             vector<int>& newInterval) {\n    const int n = intervals.size();\n    vector<vector<int>> ans;\n    int i = 0;\n\n    while (i < n && intervals[i][1] < newInterval[0])\n      ans.push_back(intervals[i++]);\n\n    // Merge overlapping intervals\n    while (i < n && intervals[i][0] <= newInterval[1]) {\n      newInterval[0] = min(newInterval[0], intervals[i][0]);\n      newInterval[1] = max(newInterval[1], intervals[i][1]);\n      ++i;\n    }\n\n    ans.push_back(newInterval);\n\n    while (i < n)\n      ans.push_back(intervals[i++]);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/57.html",
    "category": "Algorithms",
    "acceptance_rate": 43.29028139242576,
    "topics": [
      "Array"
    ],
    "hints": [
      "Intervals Array is sorted. Can you use Binary Search to find the correct position to insert the new Interval.?",
      "Can you try merging the overlapping intervals while inserting the new interval?",
      "This can be done by comparing the end of the last interval with the start of the new interval and vice versa."
    ],
    "likes": 11032,
    "dislikes": 877,
    "similar_questions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Module\", \"titleSlug\": \"range-module\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Integers in Intervals\", \"titleSlug\": \"count-integers-in-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1434814, \"totalSubmissionRaw\": 3314416, \"acRate\": \"43.3%\"}",
    "title_pt": "Inserir Intervalo",
    "description_pt": "<p>Você recebe um array de intervalos não sobrepostos <code>intervals</code> onde <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> representam o início e o fim do <code>i<sup>th</sup></code> intervalo e <code>intervals</code> está ordenado em ordem crescente por <code>start<sub>i</sub></code>. Você também recebe um intervalo <code>newInterval = [start, end]</code> que representa o início e o fim de outro intervalo.</p>\n\n<p>Insira <code>newInterval</code> em <code>intervals</code> de forma que <code>intervals</code> continue ordenado em ordem crescente por <code>start<sub>i</sub></code> e <code>intervals</code> ainda não tenha nenhum intervalo sobreposto (faça a mesclagem de intervalos sobrepostos, se necessário).</p>\n\n<p>Retorne <code>intervals</code><em> após a inserção</em>.</p>\n\n<p><strong>Nota</strong> que você não precisa modificar <code>intervals</code> in-place. Você pode criar um novo array e retorná-lo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,3],[6,9]], newInterval = [2,5]\n<strong>Saída:</strong> [[1,5],[6,9]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\n<strong>Saída:</strong> [[1,2],[3,10],[12,16]]\n<strong>Explicação:</strong> Porque o novo intervalo [4,8] se sobrepõe a [3,5],[6,7],[8,10].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>0 &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>intervals</code> está ordenado por <code>start<sub>i</sub></code> em ordem <strong>crescente</strong>.</li>\n\t<li><code>newInterval.length == 2</code></li>\n\t<li><code>0 &lt;= start &lt;= end &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: O array de intervalos está ordenado. Você consegue usar Busca Binária para encontrar a posição correta para inserir o novo intervalo?",
      "- Dica 2: Você consegue tentar mesclar os intervalos sobrepostos enquanto insere o novo intervalo?",
      "- Dica 3: Isso pode ser feito comparando o fim do último intervalo com o início do novo intervalo e vice-versa."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "58",
    "paidOnly": false,
    "title": "Length of Last Word",
    "titleSlug": "length-of-last-word",
    "url": "https://leetcode.com/problems/length-of-last-word",
    "description_url": "https://leetcode.com/problems/length-of-last-word/description/",
    "description": "<p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>\n\n<p>A <strong>word</strong> is a maximal <span data-keyword=\"substring-nonempty\">substring</span> consisting of non-space characters only.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Hello World&quot;\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The last word is &quot;World&quot; with length 5.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;   fly me   to   the moon  &quot;\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The last word is &quot;moon&quot; with length 4.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;luffy is still joyboy&quot;\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The last word is &quot;joyboy&quot; with length 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of only English letters and spaces <code>&#39; &#39;</code>.</li>\n\t<li>There will be at least one word in <code>s</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/length-of-last-word/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def lengthOfLastWord(self, s: str) -> int:\n    i = len(s) - 1\n\n    while i >= 0 and s[i] == ' ':\n      i -= 1\n    lastIndex = i\n    while i >= 0 and s[i] != ' ':\n      i -= 1\n\n    return lastIndex - i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int lengthOfLastWord(String s) {\n    int i = s.length() - 1;\n\n    while (i >= 0 && s.charAt(i) == ' ')\n      --i;\n    final int lastIndex = i;\n    while (i >= 0 && s.charAt(i) != ' ')\n      --i;\n\n    return lastIndex - i;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int lengthOfLastWord(string s) {\n    int i = s.length() - 1;\n\n    while (i >= 0 && s[i] == ' ')\n      --i;\n    const int lastIndex = i;\n    while (i >= 0 && s[i] != ' ')\n      --i;\n\n    return lastIndex - i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/58.html",
    "category": "Algorithms",
    "acceptance_rate": 56.06293612333938,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 5723,
    "dislikes": 325,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"2.7M\", \"totalSubmission\": \"4.8M\", \"totalAcceptedRaw\": 2716275, \"totalSubmissionRaw\": 4845057, \"acRate\": \"56.1%\"}",
    "title_pt": "Comprimento da Última Palavra",
    "description_pt": "<p>Dada uma string <code>s</code> composta por palavras e espaços, retorne <em>o comprimento da <strong>última</strong> palavra na string.</em></p>\n\n<p>Uma <strong>palavra</strong> é uma <span data-keyword=\"substring-nonempty\">substring</span> máxima composta somente por caracteres não espaços.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Hello World&quot;\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> A última palavra é &quot;World&quot; com comprimento 5.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;   fly me   to   the moon  &quot;\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> A última palavra é &quot;moon&quot; com comprimento 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;luffy is still joyboy&quot;\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> A última palavra é &quot;joyboy&quot; com comprimento 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras inglesas e espaços <code>&#39; &#39;</code>.</li>\n\t<li>Haverá pelo menos uma palavra em <code>s</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "59",
    "paidOnly": false,
    "title": "Spiral Matrix II",
    "titleSlug": "spiral-matrix-ii",
    "url": "https://leetcode.com/problems/spiral-matrix-ii",
    "description_url": "https://leetcode.com/problems/spiral-matrix-ii/description/",
    "description": "<p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/spiral-matrix-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Overview\n\nThere are various problems in spiral matrix series with some variations like [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) and [Spiral Matrix III](https://leetcode.com/problems/spiral-matrix-iii/).\n\nIn order to solve such questions, the core idea is to decode the underlying pattern. This can be done by simulating the pattern and finding a generic representation that would work for any given $$n$$.\nLet's discuss a few approaches.\n\n---\n### Approach 1: Traverse Layer by Layer in Spiral Form\n\n**Intuition**\n\nIf we try to build a pattern for a given $$n$$, we observe that the pattern repeats after completing one circular traversal around the matrix. Let's call this one circular traversal as  _layer_. We start traversing from the outer layer and move towards inner layers on every iteration.\n\n![img](../Figures/59/spiral_layers.png)\n\n**Algorithm**\n\nLet's devise an algorithm for the spiral traversal:\n\n-  We can observe that, for any given $$n$$, the total number of layers is given by :\n$$\\lfloor \\frac{n+1}{2} \\rfloor$$\nThis works for both even and odd $$n$$.\n\n_Example_\n\nFor $$n = 3$$, $$layers = 2$$\n\nFor $$n = 6$$, total $$layers = 3$$\n\n- Also, for each layer, we traverse in _at most_ 4 directions :\n\n\n![img](../Figures/59/spiral_traverse.png)\n\n\nIn every direction, either row or column remains constant and other parameter changes (increments/decrements).\n\n_Direction 1: From top left corner to top right corner._\n\nThe row remains constant as $$\\text{layer}$$ and column increments from $$\\text{layer}$$ to  $$n-\\text{layer}-1$$\n\n_Direction 2: From top right corner to the bottom right corner._\n\nThe column remains constant as $$n-layer-1$$ and row increments from\n$$\\text{layer}+1$$ to $$n-\\text{layer}$$.\n\n_Direction 3: From bottom right corner to bottom left corner._\n\nThe row remains constant as $$n-\\text{layer}-1$$ and column decrements from $$n-\\text{layer}-2$$ to $$\\text{layer}$$.\n\n_Direction 4: From bottom left corner to top left corner._\n\nThe column remains constant as $$\\text{layer}$$ and column decrements from $$n-\\text{layer}-2$$ to $$\\text{layer}+1$$.\n\nThis process repeats $$(n+1)/2$$ times until all layers are traversed.\n\n![img](../Figures/59/spiral_detailed.png)\n\n\n<iframe src=\"https://leetcode.com/playground/6UNnc6fM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"6UNnc6fM\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$\\mathcal{O}(n^2)$$. Here, $$n$$ is given input and we are iterating over $$n\\cdot n$$ matrix in spiral form.\n* Space Complexity: $$\\mathcal{O}(1)$$  We use constant extra space for storing $$cnt$$.\n\n---\n### Approach 2: Optimized spiral traversal\n\n**Intuition**\n\nOur main aim is to walk in a spiral form and fill the array in a particular pattern. In the previous approach, we used a separate loop for each direction. Here, we discuss another optimized to achieve the same result.\n\n**Algorithm**\n\n- We have to walk in 4 directions forming a layer. We use an array $$dir$$ that stores the changes in $$x$$ and $$y$$ co-ordinates in each direction.\n\n_Example_\n\nIn left to right walk ( _direction #1_ ), $$x$$ co-ordinates remains same and $$y$$ increments ($$x = 0$$, $$y = 1$$).\n\nIn right to left walk ( _direction #3_ ), $$x$$ remains same and $$y$$ decrements ($$x = 0$$, $$y = -1$$).\n\nUsing this intuition, we pre-define an array $$dir$$ having $$x$$ and $$y$$ co-ordinate changes for each direction. There are a total of 4 directions as discussed in the previous approach.\n\n- The $$\\text{row}$$ and $$col$$ variables represent the current $$x$$ and $$y$$ co-ordinates respectively. It updates based on the direction in which we are moving.\n\n_How do we know when we have to change the direction?_\n\nWhen we find the next row or column in a particular direction has a non-zero value, we are sure it is already traversed and we change the direction.\n\nLet $$d$$ be the current direction index. We go to next direction in array $$dir$$ using $$(d+ 1) \\% 4$$. Using this we could go back to direction 1 after completing one circular traversal from direction 1 to direction 4 .\n\n> It must be noted that we use `floorMod` in Java instead of modulo $$\\%$$ to handle mod of negative numbers. This is required because row and column values might go negative and using $$\\%$$ won't give desired results in such cases.  \n\n<iframe src=\"https://leetcode.com/playground/QYtw7GFR/shared\" frameBorder=\"0\" width=\"100%\" height=\"480\" name=\"QYtw7GFR\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$\\mathcal{O}(n^2)$$. Here, $$n$$ is given input and we are iterating over $$n\\cdot n$$ matrix in spiral form.\n* Space Complexity: $$\\mathcal{O}(1)$$  We use constant extra space for storing $$cnt$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def generateMatrix(self, n: int) -> List[List[int]]:\n    ans = [[0] * n for _ in range(n)]\n    count = 1\n\n    for min in range(n // 2):\n      max = n - min - 1\n      for i in range(min, max):\n        ans[min][i] = count\n        count += 1\n      for i in range(min, max):\n        ans[i][max] = count\n        count += 1\n      for i in range(max, min, -1):\n        ans[max][i] = count\n        count += 1\n      for i in range(max, min, -1):\n        ans[i][min] = count\n        count += 1\n\n    if n & 1:\n      ans[n // 2][n // 2] = count\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] generateMatrix(int n) {\n    int[][] ans = new int[n][n];\n    int count = 1;\n\n    for (int min = 0; min < n / 2; ++min) {\n      final int max = n - min - 1;\n      for (int i = min; i < max; ++i)\n        ans[min][i] = count++;\n      for (int i = min; i < max; ++i)\n        ans[i][max] = count++;\n      for (int i = max; i > min; --i)\n        ans[max][i] = count++;\n      for (int i = max; i > min; --i)\n        ans[i][min] = count++;\n    }\n\n    if (n % 2 == 1)\n      ans[n / 2][n / 2] = count;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> generateMatrix(int n) {\n    vector<vector<int>> ans(n, vector<int>(n));\n    int count = 1;\n\n    for (int min = 0; min < n / 2; ++min) {\n      const int max = n - min - 1;\n      for (int i = min; i < max; ++i)\n        ans[min][i] = count++;\n      for (int i = min; i < max; ++i)\n        ans[i][max] = count++;\n      for (int i = max; i > min; --i)\n        ans[max][i] = count++;\n      for (int i = max; i > min; --i)\n        ans[i][min] = count++;\n    }\n\n    if (n & 1)\n      ans[n / 2][n / 2] = count;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/59.html",
    "category": "Algorithms",
    "acceptance_rate": 73.29523919959372,
    "topics": [
      "Array",
      "Matrix",
      "Simulation"
    ],
    "hints": [],
    "likes": 6626,
    "dislikes": 273,
    "similar_questions": "[{\"title\": \"Spiral Matrix\", \"titleSlug\": \"spiral-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Spiral Matrix III\", \"titleSlug\": \"spiral-matrix-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Spiral Matrix IV\", \"titleSlug\": \"spiral-matrix-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"682.7K\", \"totalSubmission\": \"931.4K\", \"totalAcceptedRaw\": 682653, \"totalSubmissionRaw\": 931374, \"acRate\": \"73.3%\"}",
    "title_pt": "Matriz Espiral II",
    "description_pt": "<p>Dado um inteiro positivo <code>n</code>, gere uma <code>matrix</code> <code>n x n</code> preenchida com elementos de <code>1</code> até <code>n<sup>2</sup></code> em ordem espiral.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> [[1,2,3],[8,9,4],[7,6,5]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "60",
    "paidOnly": false,
    "title": "Permutation Sequence",
    "titleSlug": "permutation-sequence",
    "url": "https://leetcode.com/problems/permutation-sequence",
    "description_url": "https://leetcode.com/problems/permutation-sequence/description/",
    "description": "<p>The set <code>[1, 2, 3, ...,&nbsp;n]</code> contains a total of <code>n!</code> unique permutations.</p>\n\n<p>By listing and labeling all of the permutations in order, we get the following sequence for <code>n = 3</code>:</p>\n\n<ol>\n\t<li><code>&quot;123&quot;</code></li>\n\t<li><code>&quot;132&quot;</code></li>\n\t<li><code>&quot;213&quot;</code></li>\n\t<li><code>&quot;231&quot;</code></li>\n\t<li><code>&quot;312&quot;</code></li>\n\t<li><code>&quot;321&quot;</code></li>\n</ol>\n\n<p>Given <code>n</code> and <code>k</code>, return the <code>k<sup>th</sup></code> permutation sequence.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 3, k = 3\n<strong>Output:</strong> \"213\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 4, k = 9\n<strong>Output:</strong> \"2314\"\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> n = 3, k = 1\n<strong>Output:</strong> \"123\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n\t<li><code>1 &lt;= k &lt;= n!</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/permutation-sequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getPermutation(self, n: int, k: int) -> str:\n    ans = ''\n    nums = [i + 1 for i in range(n)]\n    factorial = [1] * (n + 1)  # factorial[i] := i!\n\n    for i in range(2, n + 1):\n      factorial[i] = factorial[i - 1] * i\n\n    k -= 1  # 0-indexed\n\n    for i in reversed(range(n)):\n      j = k // factorial[i]\n      k %= factorial[i]\n      ans += str(nums[j])\n      nums.pop(j)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String getPermutation(int n, int k) {\n    StringBuilder sb = new StringBuilder();\n    List<Integer> nums = new ArrayList<>();\n    int[] factorial = new int[n + 1]; // factorial[i] := i!\n\n    for (int i = 1; i <= n; ++i)\n      nums.add(i);\n\n    Arrays.fill(factorial, 1);\n    for (int i = 2; i <= n; ++i)\n      factorial[i] = factorial[i - 1] * i;\n\n    --k; // 0-indexed\n\n    for (int i = n - 1; i >= 0; --i) {\n      final int j = k / factorial[i];\n      k %= factorial[i];\n      sb.append(nums.get(j));\n      nums.remove(j);\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string getPermutation(int n, int k) {\n    string ans;\n    vector<int> nums(n);\n    vector<int> factorial(n + 1, 1);  // factorial[i] := i!\n\n    iota(begin(nums), end(nums), 1);\n\n    for (int i = 2; i <= n; ++i)\n      factorial[i] = factorial[i - 1] * i;\n\n    --k;  // 0-indexed\n\n    for (int i = n - 1; i >= 0; --i) {\n      const int j = k / factorial[i];\n      k %= factorial[i];\n      ans += to_string(nums[j]);\n      nums.erase(begin(nums) + j);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/60.html",
    "category": "Algorithms",
    "acceptance_rate": 49.69660874953733,
    "topics": [
      "Math",
      "Recursion"
    ],
    "hints": [],
    "likes": 6944,
    "dislikes": 491,
    "similar_questions": "[{\"title\": \"Next Permutation\", \"titleSlug\": \"next-permutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutations\", \"titleSlug\": \"permutations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"474K\", \"totalSubmission\": \"953.7K\", \"totalAcceptedRaw\": 473957, \"totalSubmissionRaw\": 953708, \"acRate\": \"49.7%\"}",
    "title_pt": "Sequência de Permutação",
    "description_pt": "<p>O conjunto <code>[1, 2, 3, ...,&nbsp;n]</code> contém um total de <code>n!</code> permutações únicas.</p>\n\n<p>Ao listar e rotular todas as permutações em ordem, obtemos a seguinte sequência para <code>n = 3</code>:</p>\n\n<ol>\n\t<li><code>&quot;123&quot;</code></li>\n\t<li><code>&quot;132&quot;</code></li>\n\t<li><code>&quot;213&quot;</code></li>\n\t<li><code>&quot;231&quot;</code></li>\n\t<li><code>&quot;312&quot;</code></li>\n\t<li><code>&quot;321&quot;</code></li>\n</ol>\n\n<p>Dados <code>n</code> e <code>k</code>, retorne a sequência de permutação <code>k<sup>th</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 3, k = 3\n<strong>Saída:</strong> \"213\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 4, k = 9\n<strong>Saída:</strong> \"2314\"\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> n = 3, k = 1\n<strong>Saída:</strong> \"123\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 9</code></li>\n\t<li><code>1 &lt;= k &lt;= n!</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "61",
    "paidOnly": false,
    "title": "Rotate List",
    "titleSlug": "rotate-list",
    "url": "https://leetcode.com/problems/rotate-list",
    "description_url": "https://leetcode.com/problems/rotate-list/description/",
    "description": "<p>Given the <code>head</code> of a linked&nbsp;list, rotate the list to the right by <code>k</code> places.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg\" style=\"width: 450px; height: 191px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5], k = 2\n<strong>Output:</strong> [4,5,1,2,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg\" style=\"width: 305px; height: 350px;\" />\n<pre>\n<strong>Input:</strong> head = [0,1,2], k = 4\n<strong>Output:</strong> [2,0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 500]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>0 &lt;= k &lt;= 2 * 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/rotate-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rotateRight(self, head: ListNode, k: int) -> ListNode:\n    if not head or not head.next or k == 0:\n      return head\n\n    tail = head\n    length = 1\n    while tail.next:\n      tail = tail.next\n      length += 1\n    tail.next = head  # Circle the list\n\n    t = length - k % length\n    for _ in range(t):\n      tail = tail.next\n    newHead = tail.next\n    tail.next = None\n\n    return newHead",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode rotateRight(ListNode head, int k) {\n    if (head == null || head.next == null || k == 0)\n      return head;\n\n    int length = 1;\n    ListNode tail = head;\n    for (; tail.next != null; tail = tail.next)\n      ++length;\n    tail.next = head; // Circle the list\n\n    final int t = length - k % length;\n    for (int i = 0; i < t; ++i)\n      tail = tail.next;\n    ListNode newHead = tail.next;\n    tail.next = null;\n\n    return newHead;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* rotateRight(ListNode* head, int k) {\n    if (!head || !head->next || k == 0)\n      return head;\n\n    ListNode* tail;\n    int length = 1;\n    for (tail = head; tail->next; tail = tail->next)\n      ++length;\n    tail->next = head;  // Circle the list\n\n    const int t = length - k % length;\n    for (int i = 0; i < t; ++i)\n      tail = tail->next;\n    ListNode* newHead = tail->next;\n    tail->next = nullptr;\n\n    return newHead;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/61.html",
    "category": "Algorithms",
    "acceptance_rate": 39.78052654347305,
    "topics": [
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 10380,
    "dislikes": 1497,
    "similar_questions": "[{\"title\": \"Rotate Array\", \"titleSlug\": \"rotate-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split Linked List in Parts\", \"titleSlug\": \"split-linked-list-in-parts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 1270834, \"totalSubmissionRaw\": 3194626, \"acRate\": \"39.8%\"}",
    "title_pt": "Rotacionar Lista",
    "description_pt": "<p>Dado o <code>head</code> de uma <code>linked&nbsp;list</code>, rotacione a lista para a direita em <code>k</code> posições.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/rotate1.jpg\" style=\"width: 450px; height: 191px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5], k = 2\n<strong>Saída:</strong> [4,5,1,2,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/13/roate2.jpg\" style=\"width: 305px; height: 350px;\" />\n<pre>\n<strong>Entrada:</strong> head = [0,1,2], k = 4\n<strong>Saída:</strong> [2,0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 500]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>0 &lt;= k &lt;= 2 * 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "62",
    "paidOnly": false,
    "title": "Unique Paths",
    "titleSlug": "unique-paths",
    "url": "https://leetcode.com/problems/unique-paths",
    "description_url": "https://leetcode.com/problems/unique-paths/description/",
    "description": "<p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>\n\n<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>\n\n<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png\" style=\"width: 400px; height: 183px;\" />\n<pre>\n<strong>Input:</strong> m = 3, n = 7\n<strong>Output:</strong> 28\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> m = 3, n = 2\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -&gt; Down -&gt; Down\n2. Down -&gt; Down -&gt; Right\n3. Down -&gt; Right -&gt; Down\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/unique-paths/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def uniquePaths(self, m: int, n: int) -> int:\n    # dp[i][j] := unique paths from (0, 0) to (i, j)\n    dp = [[1] * n for _ in range(m)]\n\n    for i in range(1, m):\n      for j in range(1, n):\n        dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n\n    return dp[-1][-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int uniquePaths(int m, int n) {\n    // dp[i][j] := unique paths from (0, 0) to (i, j)\n    int[][] dp = new int[m][n];\n    Arrays.stream(dp).forEach(row -> Arrays.fill(row, 1));\n\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        dp[i][j] = dp[i - 1][j] + dp[i][j - 1];\n\n    return dp[m - 1][n - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int uniquePaths(int m, int n) {\n    // dp[i][j] := unique paths from (0, 0) to (i, j)\n    vector<vector<int>> dp(m, vector<int>(n, 1));\n\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        dp[i][j] = dp[i - 1][j] + dp[i][j - 1];\n\n    return dp[m - 1][n - 1];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/62.html",
    "category": "Algorithms",
    "acceptance_rate": 65.651480001596,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Combinatorics"
    ],
    "hints": [],
    "likes": 17436,
    "dislikes": 465,
    "similar_questions": "[{\"title\": \"Unique Paths II\", \"titleSlug\": \"unique-paths-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Sum\", \"titleSlug\": \"minimum-path-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Dungeon Game\", \"titleSlug\": \"dungeon-game\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Cost in a Grid\", \"titleSlug\": \"minimum-path-cost-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost Homecoming of a Robot in a Grid\", \"titleSlug\": \"minimum-cost-homecoming-of-a-robot-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Reach a Position After Exactly k Steps\", \"titleSlug\": \"number-of-ways-to-reach-a-position-after-exactly-k-steps\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paths in Matrix Whose Sum Is Divisible by K\", \"titleSlug\": \"paths-in-matrix-whose-sum-is-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 2303564, \"totalSubmissionRaw\": 3508776, \"acRate\": \"65.7%\"}",
    "title_pt": "Caminhos Únicos",
    "description_pt": "<p>Há um robô em uma grade <code>m x n</code>. O robô está inicialmente localizado no <strong>canto superior esquerdo</strong> (ou seja, <code>grid[0][0]</code>). O robô tenta se mover para o <strong>canto inferior direito</strong> (ou seja, <code>grid[m - 1][n - 1]</code>). O robô só pode se mover para baixo ou para a direita a qualquer momento.</p>\n\n<p>Dados os dois inteiros <code>m</code> e <code>n</code>, retorne <em>o número de possíveis caminhos únicos que o robô pode seguir para alcançar o canto inferior direito</em>.</p>\n\n<p>Os casos de teste são gerados de forma que a resposta será menor ou igual a <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png\" style=\"width: 400px; height: 183px;\" />\n<pre>\n<strong>Entrada:</strong> m = 3, n = 7\n<strong>Saída:</strong> 28\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> m = 3, n = 2\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Do canto superior esquerdo, há um total de 3 maneiras de alcançar o canto inferior direito:\n1. Direita -&gt; Baixo -&gt; Baixo\n2. Baixo -&gt; Baixo -&gt; Direita\n3. Baixo -&gt; Direita -&gt; Baixo\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "63",
    "paidOnly": false,
    "title": "Unique Paths II",
    "titleSlug": "unique-paths-ii",
    "url": "https://leetcode.com/problems/unique-paths-ii",
    "description_url": "https://leetcode.com/problems/unique-paths-ii/description/",
    "description": "<p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>\n\n<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>\n\n<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>\n\n<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -&gt; Right -&gt; Down -&gt; Down\n2. Down -&gt; Down -&gt; Right -&gt; Right\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg\" style=\"width: 162px; height: 162px;\" />\n<pre>\n<strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == obstacleGrid.length</code></li>\n\t<li><code>n == obstacleGrid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/unique-paths-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n    m = len(obstacleGrid)\n    n = len(obstacleGrid[0])\n    # dp[i][j] := unique paths from (0, 0) to (i - 1, j - 1)\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n    dp[0][1] = 1  # Can also set dp[1][0] = 1\n\n    for i in range(1, m + 1):\n      for j in range(1, n + 1):\n        if obstacleGrid[i - 1][j - 1] == 0:\n          dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int uniquePathsWithObstacles(int[][] obstacleGrid) {\n    final int m = obstacleGrid.length;\n    final int n = obstacleGrid[0].length;\n    // dp[i][j] := unique paths from (0, 0) to (i - 1, j - 1)\n    long[][] dp = new long[m + 1][n + 1];\n    dp[0][1] = 1; // Can also set dp[1][0] = 1\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (obstacleGrid[i - 1][j - 1] == 0)\n          dp[i][j] = dp[i - 1][j] + dp[i][j - 1];\n\n    return (int) dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {\n    const int m = obstacleGrid.size();\n    const int n = obstacleGrid[0].size();\n    // dp[i][j] := unique paths from (0, 0) to (i - 1, j - 1)\n    vector<vector<long>> dp(m + 1, vector<long>(n + 1, 0));\n    dp[0][1] = 1;  // Can also set dp[1][0] = 1\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (!obstacleGrid[i - 1][j - 1])\n          dp[i][j] = dp[i - 1][j] + dp[i][j - 1];\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/63.html",
    "category": "Algorithms",
    "acceptance_rate": 43.015978663883736,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Matrix"
    ],
    "hints": [
      "Use dynamic programming since, from each cell, you can move to the right or down.",
      "assume dp[i][j] is the number of unique paths to reach (i, j). dp[i][j] = dp[i][j -1] + dp[i - 1][j]. Be careful when you encounter an obstacle. set its value in dp to 0."
    ],
    "likes": 9198,
    "dislikes": 536,
    "similar_questions": "[{\"title\": \"Unique Paths\", \"titleSlug\": \"unique-paths\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Unique Paths III\", \"titleSlug\": \"unique-paths-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Cost in a Grid\", \"titleSlug\": \"minimum-path-cost-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paths in Matrix Whose Sum Is Divisible by K\", \"titleSlug\": \"paths-in-matrix-whose-sum-is-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.8M\", \"totalAcceptedRaw\": 1193684, \"totalSubmissionRaw\": 2774982, \"acRate\": \"43.0%\"}",
    "title_pt": "Caminhos Únicos II",
    "description_pt": "<p>Você recebe um array inteiro <code>m x n</code> <code>grid</code>. Há um robô inicialmente localizado no <b>canto superior esquerdo</b> (isto é, <code>grid[0][0]</code>). O robô tenta se mover para o <strong>canto inferior direito</strong> (isto é, <code>grid[m - 1][n - 1]</code>). O robô só pode se mover para baixo ou para a direita em qualquer momento.</p>\n\n<p>Um obstáculo e um espaço são marcados como <code>1</code> ou <code>0</code> respectivamente em <code>grid</code>. Um caminho que o robô percorre não pode incluir <strong>nenhuma</strong> casa que seja um obstáculo.</p>\n\n<p>Retorne <em>o número de possíveis caminhos únicos que o robô pode seguir para alcançar o canto inferior direito</em>.</p>\n\n<p>Os casos de teste são gerados de forma que a resposta será menor ou igual a <code>2 * 10<sup>9</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Há um obstáculo no meio do grid 3x3 acima.\nExistem duas maneiras de alcançar o canto inferior direito:\n1. Direita -&gt; Direita -&gt; Baixo -&gt; Baixo\n2. Baixo -&gt; Baixo -&gt; Direita -&gt; Direita\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg\" style=\"width: 162px; height: 162px;\" />\n<pre>\n<strong>Entrada:</strong> obstacleGrid = [[0,1],[0,0]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == obstacleGrid.length</code></li>\n\t<li><code>n == obstacleGrid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>obstacleGrid[i][j]</code> é <code>0</code> ou <code>1</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Use programação dinâmica, já que, a partir de cada célula, você pode se mover para a direita ou para baixo.",
      "Dica 2: suponha que dp[i][j] seja o número de caminhos únicos para alcançar (i, j). dp[i][j] = dp[i][j -1] + dp[i - 1][j]. Tenha cuidado ao encontrar um obstáculo. defina seu valor em dp como 0."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "64",
    "paidOnly": false,
    "title": "Minimum Path Sum",
    "titleSlug": "minimum-path-sum",
    "url": "https://leetcode.com/problems/minimum-path-sum",
    "description_url": "https://leetcode.com/problems/minimum-path-sum/description/",
    "description": "<p>Given a <code>m x n</code> <code>grid</code> filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.</p>\n\n<p><strong>Note:</strong> You can only move either down or right at any point in time.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> Because the path 1 &rarr; 3 &rarr; 1 &rarr; 1 &rarr; 1 minimizes the sum.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [[1,2,3],[4,5,6]]\n<strong>Output:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= grid[i][j] &lt;= 200</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-path-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minPathSum(self, grid: List[List[int]]) -> int:\n    m = len(grid)\n    n = len(grid[0])\n\n    for i in range(m):\n      for j in range(n):\n        if i > 0 and j > 0:\n          grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])\n        elif i > 0:\n          grid[i][0] += grid[i - 1][0]\n        elif j > 0:\n          grid[0][j] += grid[0][j - 1]\n\n    return grid[m - 1][n - 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minPathSum(int[][] grid) {\n    final int m = grid.length;\n    final int n = grid[0].length;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (i > 0 && j > 0)\n          grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);\n        else if (i > 0)\n          grid[i][0] += grid[i - 1][0];\n        else if (j > 0)\n          grid[0][j] += grid[0][j - 1];\n\n    return grid[m - 1][n - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minPathSum(vector<vector<int>>& grid) {\n    const int m = grid.size();\n    const int n = grid[0].size();\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (i > 0 && j > 0)\n          grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);\n        else if (i > 0)\n          grid[i][0] += grid[i - 1][0];\n        else if (j > 0)\n          grid[0][j] += grid[0][j - 1];\n\n    return grid[m - 1][n - 1];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/64.html",
    "category": "Algorithms",
    "acceptance_rate": 66.26856021818885,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Matrix"
    ],
    "hints": [],
    "likes": 13008,
    "dislikes": 179,
    "similar_questions": "[{\"title\": \"Unique Paths\", \"titleSlug\": \"unique-paths\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Dungeon Game\", \"titleSlug\": \"dungeon-game\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Cherry Pickup\", \"titleSlug\": \"cherry-pickup\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Cost in a Grid\", \"titleSlug\": \"minimum-path-cost-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Points with Cost\", \"titleSlug\": \"maximum-number-of-points-with-cost\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost Homecoming of a Robot in a Grid\", \"titleSlug\": \"minimum-cost-homecoming-of-a-robot-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paths in Matrix Whose Sum Is Divisible by K\", \"titleSlug\": \"paths-in-matrix-whose-sum-is-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check if There is a Path With Equal Number of 0's And 1's\", \"titleSlug\": \"check-if-there-is-a-path-with-equal-number-of-0s-and-1s\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost of a Path With Special Roads\", \"titleSlug\": \"minimum-cost-of-a-path-with-special-roads\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1492343, \"totalSubmissionRaw\": 2251972, \"acRate\": \"66.3%\"}",
    "title_pt": "Soma Mínima de Caminho",
    "description_pt": "<p>Dado um <code>grid</code> <code>m x n</code> preenchido com números não negativos, encontre um caminho do canto superior esquerdo ao canto inferior direito, que minimize a soma de todos os números ao longo do seu caminho.</p>\n\n<p><strong>Nota:</strong> Você só pode se mover para baixo ou para a direita em qualquer momento.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> grid = [[1,3,1],[1,5,1],[4,2,1]]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Porque o caminho 1 &rarr; 3 &rarr; 1 &rarr; 1 &rarr; 1 minimiza a soma.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [[1,2,3],[4,5,6]]\n<strong>Saída:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= grid[i][j] &lt;= 200</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "65",
    "paidOnly": false,
    "title": "Valid Number",
    "titleSlug": "valid-number",
    "url": "https://leetcode.com/problems/valid-number",
    "description_url": "https://leetcode.com/problems/valid-number/description/",
    "description": "<p>Given a string <code>s</code>, return whether <code>s</code> is a <strong>valid number</strong>.<br />\n<br />\nFor example, all the following are valid numbers: <code>&quot;2&quot;, &quot;0089&quot;, &quot;-0.1&quot;, &quot;+3.14&quot;, &quot;4.&quot;, &quot;-.9&quot;, &quot;2e10&quot;, &quot;-90E3&quot;, &quot;3e+7&quot;, &quot;+6e-1&quot;, &quot;53.5e93&quot;, &quot;-123.456e789&quot;</code>, while the following are not valid numbers: <code>&quot;abc&quot;, &quot;1a&quot;, &quot;1e&quot;, &quot;e3&quot;, &quot;99e2.5&quot;, &quot;--6&quot;, &quot;-+3&quot;, &quot;95a54e53&quot;</code>.</p>\n\n<p>Formally, a&nbsp;<strong>valid number</strong> is defined using one of the following definitions:</p>\n\n<ol>\n\t<li>An <strong>integer number</strong> followed by an <strong>optional exponent</strong>.</li>\n\t<li>A <strong>decimal number</strong> followed by an <strong>optional exponent</strong>.</li>\n</ol>\n\n<p>An <strong>integer number</strong> is defined with an <strong>optional sign</strong> <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> followed by <strong>digits</strong>.</p>\n\n<p>A <strong>decimal number</strong> is defined with an <strong>optional sign</strong> <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> followed by one of the following definitions:</p>\n\n<ol>\n\t<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>&#39;.&#39;</code>.</li>\n\t<li><strong>Digits</strong> followed by a <strong>dot</strong> <code>&#39;.&#39;</code> followed by <strong>digits</strong>.</li>\n\t<li>A <strong>dot</strong> <code>&#39;.&#39;</code> followed by <strong>digits</strong>.</li>\n</ol>\n\n<p>An <strong>exponent</strong> is defined with an <strong>exponent notation</strong> <code>&#39;e&#39;</code> or <code>&#39;E&#39;</code> followed by an <strong>integer number</strong>.</p>\n\n<p>The <strong>digits</strong> are defined as one or more digits.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;0&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;e&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;.&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>s</code> consists of only English letters (both uppercase and lowercase), digits (<code>0-9</code>), plus <code>&#39;+&#39;</code>, minus <code>&#39;-&#39;</code>, or dot <code>&#39;.&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isNumber(self, s: str) -> bool:\n    s = s.strip()\n    if not s:\n      return False\n\n    seenNum = False\n    seenDot = False\n    seenE = False\n\n    for i, c in enumerate(s):\n      if c == '.':\n        if seenDot or seenE:\n          return False\n        seenDot = True\n      elif c == 'e' or c == 'E':\n        if seenE or not seenNum:\n          return False\n        seenE = True\n        seenNum = False\n      elif c in '+-':\n        if i > 0 and s[i - 1] != 'e':\n          return False\n        seenNum = False\n      else:\n        if not c.isdigit():\n          return False\n        seenNum = True\n\n    return seenNum",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isNumber(String s) {\n    s = s.trim();\n    if (s.isEmpty())\n      return false;\n\n    boolean seenNum = false;\n    boolean seenDot = false;\n    boolean seenE = false;\n\n    for (int i = 0; i < s.length(); ++i) {\n      switch (s.charAt(i)) {\n        case '.':\n          if (seenDot || seenE)\n            return false;\n          seenDot = true;\n          break;\n        case 'e':\n        case 'E':\n          if (seenE || !seenNum)\n            return false;\n          seenE = true;\n          seenNum = false;\n          break;\n        case '+':\n        case '-':\n          if (i > 0 && s.charAt(i - 1) != 'e')\n            return false;\n          seenNum = false;\n          break;\n        default:\n          if (!Character.isDigit(s.charAt(i)))\n            return false;\n          seenNum = true;\n      }\n    }\n\n    return seenNum;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isNumber(string s) {\n    trim(s);\n    if (s.empty())\n      return false;\n\n    bool seenNum = false;\n    bool seenDot = false;\n    bool seenE = false;\n\n    for (int i = 0; i < s.length(); ++i) {\n      switch (s[i]) {\n        case '.':\n          if (seenDot || seenE)\n            return false;\n          seenDot = true;\n          break;\n        case 'e':\n        case 'E':\n          if (seenE || !seenNum)\n            return false;\n          seenE = true;\n          seenNum = false;\n          break;\n        case '+':\n        case '-':\n          if (i > 0 && s[i - 1] != 'e')\n            return false;\n          seenNum = false;\n          break;\n        default:\n          if (!isdigit(s[i]))\n            return false;\n          seenNum = true;\n      }\n    }\n\n    return seenNum;\n  }\n\n private:\n  void trim(string& s) {\n    s.erase(0, s.find_first_not_of(' '));\n    s.erase(s.find_last_not_of(' ') + 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/65.html",
    "category": "Algorithms",
    "acceptance_rate": 21.426653728584085,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 1383,
    "dislikes": 2148,
    "similar_questions": "[{\"title\": \"String to Integer (atoi)\", \"titleSlug\": \"string-to-integer-atoi\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"446.9K\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 446920, \"totalSubmissionRaw\": 2085828, \"acRate\": \"21.4%\"}",
    "title_pt": "Número Válido",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne se <code>s</code> é um <strong>número válido</strong>.<br />\n<br />\nPor exemplo, todos os seguintes são números válidos: <code>&quot;2&quot;, &quot;0089&quot;, &quot;-0.1&quot;, &quot;+3.14&quot;, &quot;4.&quot;, &quot;-.9&quot;, &quot;2e10&quot;, &quot;-90E3&quot;, &quot;3e+7&quot;, &quot;+6e-1&quot;, &quot;53.5e93&quot;, &quot;-123.456e789&quot;</code>, enquanto os seguintes não são números válidos: <code>&quot;abc&quot;, &quot;1a&quot;, &quot;1e&quot;, &quot;e3&quot;, &quot;99e2.5&quot;, &quot;--6&quot;, &quot;-+3&quot;, &quot;95a54e53&quot;</code>.</p>\n\n<p>Formalmente, um <strong>número válido</strong> é definido usando uma das seguintes definições:</p>\n\n<ol>\n\t<li>Um <strong>número inteiro</strong> seguido por um <strong>expoente opcional</strong>.</li>\n\t<li>Um <strong>número decimal</strong> seguido por um <strong>expoente opcional</strong>.</li>\n</ol>\n\n<p>Um <strong>número inteiro</strong> é definido com um <strong>sinal opcional</strong> <code>&#39;-&#39;</code> ou <code>&#39;+&#39;</code> seguido por <strong>dígitos</strong>.</p>\n\n<p>Um <strong>número decimal</strong> é definido com um <strong>sinal opcional</strong> <code>&#39;-&#39;</code> ou <code>&#39;+&#39;</code> seguido por uma das seguintes definições:</p>\n\n<ol>\n\t<li><strong>Dígitos</strong> seguidos por um <strong>ponto</strong> <code>&#39;.&#39;</code>.</li>\n\t<li><strong>Dígitos</strong> seguidos por um <strong>ponto</strong> <code>&#39;.&#39;</code> seguidos por <strong>dígitos</strong>.</li>\n\t<li>Um <strong>ponto</strong> <code>&#39;.&#39;</code> seguido por <strong>dígitos</strong>.</li>\n</ol>\n\n<p>Um <strong>expoente</strong> é definido com a <strong>notação de expoente</strong> <code>&#39;e&#39;</code> ou <code>&#39;E&#39;</code> seguida por um <strong>número inteiro</strong>.</p>\n\n<p>Os <strong>dígitos</strong> são definidos como um ou mais dígitos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;0&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;e&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;.&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>s</code> consiste apenas de letras inglesas (maiúsculas e minúsculas), dígitos (<code>0-9</code>), além de <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> ou ponto <code>&#39;.&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "66",
    "paidOnly": false,
    "title": "Plus One",
    "titleSlug": "plus-one",
    "url": "https://leetcode.com/problems/plus-one",
    "description_url": "https://leetcode.com/problems/plus-one/description/",
    "description": "<p>You are given a <strong>large integer</strong> represented as an integer array <code>digits</code>, where each <code>digits[i]</code> is the <code>i<sup>th</sup></code> digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading <code>0</code>&#39;s.</p>\n\n<p>Increment the large integer by one and return <em>the resulting array of digits</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = [1,2,3]\n<strong>Output:</strong> [1,2,4]\n<strong>Explanation:</strong> The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = [4,3,2,1]\n<strong>Output:</strong> [4,3,2,2]\n<strong>Explanation:</strong> The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> digits = [9]\n<strong>Output:</strong> [1,0]\n<strong>Explanation:</strong> The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= digits.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= digits[i] &lt;= 9</code></li>\n\t<li><code>digits</code> does not contain any leading <code>0</code>&#39;s.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/plus-one/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def plusOne(self, digits: List[int]) -> List[int]:\n    for i, d in reversed(list(enumerate(digits))):\n      if d < 9:\n        digits[i] += 1\n        return digits\n      digits[i] = 0\n\n    return [1] + digits",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] plusOne(int[] digits) {\n    for (int i = digits.length - 1; i >= 0; i--) {\n      if (digits[i] < 9) {\n        ++digits[i];\n        return digits;\n      }\n      digits[i] = 0;\n    }\n\n    int[] ans = new int[digits.length + 1];\n    ans[0] = 1;\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> plusOne(vector<int>& digits) {\n    for (int i = digits.size() - 1; i >= 0; --i) {\n      if (digits[i] < 9) {\n        ++digits[i];\n        return digits;\n      }\n      digits[i] = 0;\n    }\n\n    digits.insert(begin(digits), 1);\n    return digits;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/66.html",
    "category": "Algorithms",
    "acceptance_rate": 47.4019775314563,
    "topics": [
      "Array",
      "Math"
    ],
    "hints": [],
    "likes": 10261,
    "dislikes": 5489,
    "similar_questions": "[{\"title\": \"Multiply Strings\", \"titleSlug\": \"multiply-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Binary\", \"titleSlug\": \"add-binary\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Plus One Linked List\", \"titleSlug\": \"plus-one-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add to Array-Form of Integer\", \"titleSlug\": \"add-to-array-form-of-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Reduce an Integer to 0\", \"titleSlug\": \"minimum-operations-to-reduce-an-integer-to-0\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.9M\", \"totalSubmission\": \"6.1M\", \"totalAcceptedRaw\": 2898428, \"totalSubmissionRaw\": 6114578, \"acRate\": \"47.4%\"}",
    "title_pt": "Mais Um",
    "description_pt": "<p>Você recebe um <strong>inteiro grande</strong> representado como um array de inteiros <code>digits</code>, em que cada <code>digits[i]</code> é o <code>i<sup>ésimo</sup></code> dígito do inteiro. Os dígitos são ordenados do mais significativo para o menos significativo, em ordem da esquerda para a direita. O inteiro grande não contém nenhum <code>0</code> à esquerda.</p>\n\n<p>Incremente o inteiro grande em um e retorne <em>o array de dígitos resultante</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = [1,2,3]\n<strong>Saída:</strong> [1,2,4]\n<strong>Explicação:</strong> O array representa o inteiro 123.\nIncrementá-lo em um dá 123 + 1 = 124.\nPortanto, o resultado deve ser [1,2,4].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = [4,3,2,1]\n<strong>Saída:</strong> [4,3,2,2]\n<strong>Explicação:</strong> O array representa o inteiro 4321.\nIncrementá-lo em um dá 4321 + 1 = 4322.\nPortanto, o resultado deve ser [4,3,2,2].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> digits = [9]\n<strong>Saída:</strong> [1,0]\n<strong>Explicação:</strong> O array representa o inteiro 9.\nIncrementá-lo em um dá 9 + 1 = 10.\nPortanto, o resultado deve ser [1,0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= digits.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= digits[i] &lt;= 9</code></li>\n\t<li><code>digits</code> não contém nenhum <code>0</code> à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "67",
    "paidOnly": false,
    "title": "Add Binary",
    "titleSlug": "add-binary",
    "url": "https://leetcode.com/problems/add-binary",
    "description_url": "https://leetcode.com/problems/add-binary/description/",
    "description": "<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> a = \"11\", b = \"1\"\n<strong>Output:</strong> \"100\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> a = \"1010\", b = \"1011\"\n<strong>Output:</strong> \"10101\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>a</code> and <code>b</code> consist&nbsp;only of <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code> characters.</li>\n\t<li>Each string does not contain leading zeros except for the zero itself.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/add-binary/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addBinary(self, a: str, b: str) -> str:\n    s = []\n    carry = 0\n    i = len(a) - 1\n    j = len(b) - 1\n\n    while i >= 0 or j >= 0 or carry:\n      if i >= 0:\n        carry += int(a[i])\n        i -= 1\n      if j >= 0:\n        carry += int(b[j])\n        j -= 1\n      s.append(str(carry % 2))\n      carry //= 2\n\n    return ''.join(reversed(s))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String addBinary(String a, String b) {\n    StringBuilder sb = new StringBuilder();\n    int carry = 0;\n    int i = a.length() - 1;\n    int j = b.length() - 1;\n\n    while (i >= 0 || j >= 0 || carry == 1) {\n      if (i >= 0)\n        carry += a.charAt(i--) - '0';\n      if (j >= 0)\n        carry += b.charAt(j--) - '0';\n      sb.append(carry % 2);\n      carry /= 2;\n    }\n\n    return sb.reverse().toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string addBinary(string a, string b) {\n    string ans;\n    int carry = 0;\n    int i = a.length() - 1;\n    int j = b.length() - 1;\n\n    while (i >= 0 || j >= 0 || carry) {\n      if (i >= 0)\n        carry += a[i--] - '0';\n      if (j >= 0)\n        carry += b[j--] - '0';\n      ans += carry % 2 + '0';\n      carry /= 2;\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/67.html",
    "category": "Algorithms",
    "acceptance_rate": 55.54233033762566,
    "topics": [
      "Math",
      "String",
      "Bit Manipulation",
      "Simulation"
    ],
    "hints": [],
    "likes": 9892,
    "dislikes": 1039,
    "similar_questions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Multiply Strings\", \"titleSlug\": \"multiply-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Plus One\", \"titleSlug\": \"plus-one\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add to Array-Form of Integer\", \"titleSlug\": \"add-to-array-form-of-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1843680, \"totalSubmissionRaw\": 3319413, \"acRate\": \"55.5%\"}",
    "title_pt": "Adicionar Binários",
    "description_pt": "<p>Dadas duas strings binárias <code>a</code> e <code>b</code>, retorne <em>sua soma como uma string binária</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> a = \"11\", b = \"1\"\n<strong>Saída:</strong> \"100\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> a = \"1010\", b = \"1011\"\n<strong>Saída:</strong> \"10101\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>a</code> e <code>b</code> consistem&nbsp;apenas dos caracteres <code>&#39;0&#39;</code> ou <code>&#39;1&#39;</code>.</li>\n\t<li>Cada string não contém zeros à esquerda, exceto pelo próprio zero.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "68",
    "paidOnly": false,
    "title": "Text Justification",
    "titleSlug": "text-justification",
    "url": "https://leetcode.com/problems/text-justification",
    "description_url": "https://leetcode.com/problems/text-justification/description/",
    "description": "<p>Given an array of strings <code>words</code> and a width <code>maxWidth</code>, format the text such that each line has exactly <code>maxWidth</code> characters and is fully (left and right) justified.</p>\n\n<p>You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces <code>&#39; &#39;</code> when necessary so that each line has exactly <code>maxWidth</code> characters.</p>\n\n<p>Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.</p>\n\n<p>For the last line of text, it should be left-justified, and no extra space is inserted between words.</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>A word is defined as a character sequence consisting of non-space characters only.</li>\n\t<li>Each word&#39;s length is guaranteed to be greater than <code>0</code> and not exceed <code>maxWidth</code>.</li>\n\t<li>The input array <code>words</code> contains at least one word.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;This&quot;, &quot;is&quot;, &quot;an&quot;, &quot;example&quot;, &quot;of&quot;, &quot;text&quot;, &quot;justification.&quot;], maxWidth = 16\n<strong>Output:</strong>\n[\n&nbsp; &nbsp;&quot;This &nbsp; &nbsp;is &nbsp; &nbsp;an&quot;,\n&nbsp; &nbsp;&quot;example &nbsp;of text&quot;,\n&nbsp; &nbsp;&quot;justification. &nbsp;&quot;\n]</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;What&quot;,&quot;must&quot;,&quot;be&quot;,&quot;acknowledgment&quot;,&quot;shall&quot;,&quot;be&quot;], maxWidth = 16\n<strong>Output:</strong>\n[\n&nbsp; &quot;What &nbsp; must &nbsp; be&quot;,\n&nbsp; &quot;acknowledgment &nbsp;&quot;,\n&nbsp; &quot;shall be &nbsp; &nbsp; &nbsp; &nbsp;&quot;\n]\n<strong>Explanation:</strong> Note that the last line is &quot;shall be    &quot; instead of &quot;shall     be&quot;, because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;Science&quot;,&quot;is&quot;,&quot;what&quot;,&quot;we&quot;,&quot;understand&quot;,&quot;well&quot;,&quot;enough&quot;,&quot;to&quot;,&quot;explain&quot;,&quot;to&quot;,&quot;a&quot;,&quot;computer.&quot;,&quot;Art&quot;,&quot;is&quot;,&quot;everything&quot;,&quot;else&quot;,&quot;we&quot;,&quot;do&quot;], maxWidth = 20\n<strong>Output:</strong>\n[\n&nbsp; &quot;Science &nbsp;is &nbsp;what we&quot;,\n  &quot;understand &nbsp; &nbsp; &nbsp;well&quot;,\n&nbsp; &quot;enough to explain to&quot;,\n&nbsp; &quot;a &nbsp;computer. &nbsp;Art is&quot;,\n&nbsp; &quot;everything &nbsp;else &nbsp;we&quot;,\n&nbsp; &quot;do &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;\n]</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 20</code></li>\n\t<li><code>words[i]</code> consists of only English letters and symbols.</li>\n\t<li><code>1 &lt;= maxWidth &lt;= 100</code></li>\n\t<li><code>words[i].length &lt;= maxWidth</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/text-justification/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n    ans = []\n    row = []\n    rowLetters = 0\n\n    for word in words:\n      if rowLetters + len(word) + len(row) > maxWidth:\n        for i in range(maxWidth - rowLetters):\n          row[i % (len(row) - 1 or 1)] += ' '\n        ans.append(''.join(row))\n        row = []\n        rowLetters = 0\n      row.append(word)\n      rowLetters += len(word)\n\n    return ans + [' '.join(row).ljust(maxWidth)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> fullJustify(String[] words, int maxWidth) {\n    List<String> ans = new ArrayList<>();\n    List<StringBuilder> row = new ArrayList<>();\n    int rowLetters = 0;\n\n    for (final String word : words) {\n      if (rowLetters + row.size() + word.length() > maxWidth) {\n        final int spaces = maxWidth - rowLetters;\n        if (row.size() == 1) {\n          for (int i = 0; i < spaces; ++i)\n            row.get(0).append(\" \");\n        } else {\n          for (int i = 0; i < spaces; ++i)\n            row.get(i % (row.size() - 1)).append(\" \");\n        }\n        final String joinedRow =\n            row.stream().map(StringBuilder::toString).collect(Collectors.joining(\"\"));\n        ans.add(joinedRow);\n        row.clear();\n        rowLetters = 0;\n      }\n      row.add(new StringBuilder(word));\n      rowLetters += word.length();\n    }\n\n    final String lastRow =\n        row.stream().map(StringBuilder::toString).collect(Collectors.joining(\" \"));\n    StringBuilder sb = new StringBuilder(lastRow);\n    final int spacesToBeAdded = maxWidth - sb.length();\n    for (int i = 0; i < spacesToBeAdded; ++i)\n      sb.append(\" \");\n\n    ans.add(sb.toString());\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> fullJustify(vector<string>& words, size_t maxWidth) {\n    vector<string> ans;\n    vector<string> row;\n    size_t rowLetters = 0;\n\n    for (const string& word : words) {\n      // If we put the word in this row, it'll exceed the maxWidth,\n      // So we cannot put the word to this row and have to pad spaces to\n      // Each word in this row\n      if (rowLetters + row.size() + word.length() > maxWidth) {\n        const int spaces = maxWidth - rowLetters;\n        if (row.size() == 1) {\n          // Pad all spaces after row[0]\n          for (int i = 0; i < spaces; ++i)\n            row[0] += \" \";\n        } else {\n          // Evenly pad spaces to each word (expect the last one) in this row\n          for (int i = 0; i < spaces; ++i)\n            row[i % (row.size() - 1)] += \" \";\n        }\n        ans.push_back(join(row, \"\"));\n        row.clear();\n        rowLetters = 0;\n      }\n      row.push_back(word);\n      rowLetters += word.length();\n    }\n    ans.push_back(ljust(join(row, \" \"), maxWidth));\n\n    return ans;\n  }\n\n private:\n  string join(const vector<string>& v, const string& c) {\n    string s;\n    for (auto p = begin(v); p != end(v); ++p) {\n      s += *p;\n      if (p != end(v) - 1)\n        s += c;\n    }\n    return s;\n  }\n\n  string ljust(string s, int width) {\n    for (int i = 0; i < s.length() - width; ++i)\n      s += \" \";\n    return s;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/68.html",
    "category": "Algorithms",
    "acceptance_rate": 47.848490407752884,
    "topics": [
      "Array",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 4127,
    "dislikes": 5076,
    "similar_questions": "[{\"title\": \"Rearrange Spaces Between Words\", \"titleSlug\": \"rearrange-spaces-between-words\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Divide a String Into Groups of Size k\", \"titleSlug\": \"divide-a-string-into-groups-of-size-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Split Message Based on Limit\", \"titleSlug\": \"split-message-based-on-limit\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"537.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 537277, \"totalSubmissionRaw\": 1122879, \"acRate\": \"47.8%\"}",
    "title_pt": "Justificação de Texto",
    "description_pt": "<p>Dado um array de strings <code>words</code> e uma largura <code>maxWidth</code>, formate o texto de modo que cada linha tenha exatamente <code>maxWidth</code> caracteres e esteja totalmente justificada (à esquerda e à direita).</p>\n\n<p>Você deve empacotar suas palavras com uma abordagem gulosa; isto é, coloque o máximo de palavras que puder em cada linha. Adicione espaços extras <code>&#39; &#39;</code> quando necessário para que cada linha tenha exatamente <code>maxWidth</code> caracteres.</p>\n\n<p>Os espaços extras entre palavras devem ser distribuídos da forma mais uniforme possível. Se o número de espaços em uma linha não for divisível igualmente entre as palavras, os espaços vazios à esquerda receberão mais espaços do que os espaços à direita.</p>\n\n<p>Para a última linha do texto, ela deve ser alinhada à esquerda, e nenhum espaço extra é inserido entre as palavras.</p>\n\n<p><strong>Nota:</strong></p>\n\n<ul>\n\t<li>Uma palavra é definida como uma sequência de caracteres composta apenas por caracteres que não sejam espaços.</li>\n\t<li>É garantido que o comprimento de cada palavra seja maior que <code>0</code> e não exceda <code>maxWidth</code>.</li>\n\t<li>O array de entrada <code>words</code> contém pelo menos uma palavra.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;This&quot;, &quot;is&quot;, &quot;an&quot;, &quot;example&quot;, &quot;of&quot;, &quot;text&quot;, &quot;justification.&quot;], maxWidth = 16\n<strong>Saída:</strong>\n[\n&nbsp; &nbsp;&quot;This &nbsp; &nbsp;is &nbsp; &nbsp;an&quot;,\n&nbsp; &nbsp;&quot;example &nbsp;of text&quot;,\n&nbsp; &nbsp;&quot;justification. &nbsp;&quot;\n]</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;What&quot;,&quot;must&quot;,&quot;be&quot;,&quot;acknowledgment&quot;,&quot;shall&quot;,&quot;be&quot;], maxWidth = 16\n<strong>Saída:</strong>\n[\n&nbsp; &quot;What &nbsp; must &nbsp; be&quot;,\n&nbsp; &quot;acknowledgment &nbsp;&quot;,\n&nbsp; &quot;shall be &nbsp; &nbsp; &nbsp; &nbsp;&quot;\n]\n<strong>Explicação:</strong> Observe que a última linha é &quot;shall be    &quot; em vez de &quot;shall     be&quot;, porque a última linha deve ser alinhada à esquerda em vez de totalmente justificada.\nObserve que a segunda linha também é alinhada à esquerda porque contém apenas uma palavra.</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;Science&quot;,&quot;is&quot;,&quot;what&quot;,&quot;we&quot;,&quot;understand&quot;,&quot;well&quot;,&quot;enough&quot;,&quot;to&quot;,&quot;explain&quot;,&quot;to&quot;,&quot;a&quot;,&quot;computer.&quot;,&quot;Art&quot;,&quot;is&quot;,&quot;everything&quot;,&quot;else&quot;,&quot;we&quot;,&quot;do&quot;], maxWidth = 20\n<strong>Saída:</strong>\n[\n&nbsp; &quot;Science &nbsp;is &nbsp;what we&quot;,\n  &quot;understand &nbsp; &nbsp; &nbsp;well&quot;,\n&nbsp; &quot;enough to explain to&quot;,\n&nbsp; &quot;a &nbsp;computer. &nbsp;Art is&quot;,\n&nbsp; &quot;everything &nbsp;else &nbsp;we&quot;,\n&nbsp; &quot;do &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&quot;\n]</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 20</code></li>\n\t<li><code>words[i]</code> consiste apenas de letras e símbolos do inglês.</li>\n\t<li><code>1 &lt;= maxWidth &lt;= 100</code></li>\n\t<li><code>words[i].length &lt;= maxWidth</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "69",
    "paidOnly": false,
    "title": "Sqrt(x)",
    "titleSlug": "sqrtx",
    "url": "https://leetcode.com/problems/sqrtx",
    "description_url": "https://leetcode.com/problems/sqrtx/description/",
    "description": "<p>Given a non-negative integer <code>x</code>, return <em>the square root of </em><code>x</code><em> rounded down to the nearest integer</em>. The returned integer should be <strong>non-negative</strong> as well.</p>\n\n<p>You <strong>must not use</strong> any built-in exponent function or operator.</p>\n\n<ul>\n\t<li>For example, do not use <code>pow(x, 0.5)</code> in c++ or <code>x ** 0.5</code> in python.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The square root of 4 is 2, so we return 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 8\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sqrtx/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def mySqrt(self, x: int) -> int:\n    l = 1\n    r = x + 1\n\n    while l < r:\n      m = (l + r) // 2\n      if m * m > x:\n        r = m\n      else:\n        l = m + 1\n\n    # L: smallest number s.t. l * l > x\n    return l - 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int mySqrt(long x) {\n    long l = 1;\n    long r = x + 1;\n\n    while (l < r) {\n      final long m = (l + r) / 2;\n      if (m > x / m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    // L: smallest number s.t. l * l > x\n    return (int) l - 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int mySqrt(int x) {\n    unsigned l = 1;\n    unsigned r = x + 1u;\n\n    while (l < r) {\n      const unsigned m = (l + r) / 2;\n      if (m > x / m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    // L: smallest number s.t. l * l > x\n    return l - 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/69.html",
    "category": "Algorithms",
    "acceptance_rate": 40.27495566392121,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [
      "Try exploring all integers. (Credits: @annujoshi)",
      "Use the sorted property of integers to reduced the search space. (Credits: @annujoshi)"
    ],
    "likes": 8849,
    "dislikes": 4575,
    "similar_questions": "[{\"title\": \"Pow(x, n)\", \"titleSlug\": \"powx-n\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Valid Perfect Square\", \"titleSlug\": \"valid-perfect-square\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"6.3M\", \"totalAcceptedRaw\": 2546014, \"totalSubmissionRaw\": 6321589, \"acRate\": \"40.3%\"}",
    "title_pt": "Raiz Quadrada de x",
    "description_pt": "<p>Dado um inteiro não negativo <code>x</code>, retorne <em>a raiz quadrada de </em><code>x</code><em> arredondada para baixo para o inteiro mais próximo</em>. O inteiro retornado também deve ser <strong>não negativo</strong>.</p>\n\n<p>Você <strong>não deve usar</strong> nenhuma função ou operador embutido de exponenciação.</p>\n\n<ul>\n\t<li>Por exemplo, não use <code>pow(x, 0.5)</code> em c++ ou <code>x ** 0.5</code> em python.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 4\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A raiz quadrada de 4 é 2, então retornamos 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 8\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A raiz quadrada de 8 é 2.82842..., e como arredondamos para baixo para o inteiro mais próximo, 2 é retornado.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Tente explorar todos os inteiros. (Créditos: @annujoshi)",
      "- Dica 2: Use a propriedade de ordenação dos inteiros para reduzir o espaço de busca. (Créditos: @annujoshi)"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "70",
    "paidOnly": false,
    "title": "Climbing Stairs",
    "titleSlug": "climbing-stairs",
    "url": "https://leetcode.com/problems/climbing-stairs",
    "description_url": "https://leetcode.com/problems/climbing-stairs/description/",
    "description": "<p>You are climbing a staircase. It takes <code>n</code> steps to reach the top.</p>\n\n<p>Each time you can either climb <code>1</code> or <code>2</code> steps. In how many distinct ways can you climb to the top?</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 45</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/climbing-stairs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def climbStairs(self, n: int) -> int:\n    # dp[i] := # Of distinct ways to climb to i-th stair\n    dp = [1, 1] + [0] * (n - 1)\n\n    for i in range(2, n + 1):\n      dp[i] = dp[i - 1] + dp[i - 2]\n\n    return dp[n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int climbStairs(int n) {\n    // dp[i] := # of distinct ways to climb to i-th stair\n    int[] dp = new int[n + 1];\n    dp[0] = 1;\n    dp[1] = 1;\n\n    for (int i = 2; i <= n; ++i)\n      dp[i] = dp[i - 1] + dp[i - 2];\n\n    return dp[n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int climbStairs(int n) {\n    // dp[i] := # of distinct ways to climb to i-th stair\n    vector<int> dp(n + 1);\n    dp[0] = 1;\n    dp[1] = 1;\n\n    for (int i = 2; i <= n; ++i)\n      dp[i] = dp[i - 1] + dp[i - 2];\n\n    return dp[n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/70.html",
    "category": "Algorithms",
    "acceptance_rate": 53.482260470245905,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Memoization"
    ],
    "hints": [
      "To reach nth step, what could have been your previous steps? (Think about the step sizes)"
    ],
    "likes": 23098,
    "dislikes": 956,
    "similar_questions": "[{\"title\": \"Min Cost Climbing Stairs\", \"titleSlug\": \"min-cost-climbing-stairs\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Fibonacci Number\", \"titleSlug\": \"fibonacci-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-th Tribonacci Number\", \"titleSlug\": \"n-th-tribonacci-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Rounds to Complete All Tasks\", \"titleSlug\": \"minimum-rounds-to-complete-all-tasks\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Number of Ways to Place Houses\", \"titleSlug\": \"count-number-of-ways-to-place-houses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Reach a Position After Exactly k Steps\", \"titleSlug\": \"number-of-ways-to-reach-a-position-after-exactly-k-steps\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Ways To Build Good Strings\", \"titleSlug\": \"count-ways-to-build-good-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Frog Jump II\", \"titleSlug\": \"frog-jump-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Number of Ways to Reach the K-th Stair\", \"titleSlug\": \"find-number-of-ways-to-reach-the-k-th-stair\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"The Number of Ways to Make the Sum\", \"titleSlug\": \"the-number-of-ways-to-make-the-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.2M\", \"totalSubmission\": \"7.8M\", \"totalAcceptedRaw\": 4173354, \"totalSubmissionRaw\": 7803244, \"acRate\": \"53.5%\"}",
    "title_pt": "Subindo Escadas",
    "description_pt": "<p>Você está subindo uma escada. São necessários <code>n</code> degraus para alcançar o topo.</p>\n\n<p>Cada vez, você pode subir <code>1</code> ou <code>2</code> degraus. De quantas maneiras distintas você pode chegar ao topo?</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Há duas maneiras de subir até o topo.\n1. 1 step + 1 step\n2. 2 steps\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Há três maneiras de subir até o topo.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 45</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Para alcançar o degrau n-ésimo, quais poderiam ter sido seus degraus anteriores? (Pense nos tamanhos dos passos)"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "71",
    "paidOnly": false,
    "title": "Simplify Path",
    "titleSlug": "simplify-path",
    "url": "https://leetcode.com/problems/simplify-path",
    "description_url": "https://leetcode.com/problems/simplify-path/description/",
    "description": "<p>You are given an <em>absolute</em> path for a Unix-style file system, which always begins with a slash <code>&#39;/&#39;</code>. Your task is to transform this absolute path into its <strong>simplified canonical path</strong>.</p>\n\n<p>The <em>rules</em> of a Unix-style file system are as follows:</p>\n\n<ul>\n\t<li>A single period <code>&#39;.&#39;</code> represents the current directory.</li>\n\t<li>A double period <code>&#39;..&#39;</code> represents the previous/parent directory.</li>\n\t<li>Multiple consecutive slashes such as <code>&#39;//&#39;</code> and <code>&#39;///&#39;</code> are treated as a single slash <code>&#39;/&#39;</code>.</li>\n\t<li>Any sequence of periods that does <strong>not match</strong> the rules above should be treated as a <strong>valid directory or</strong> <strong>file </strong><strong>name</strong>. For example, <code>&#39;...&#39; </code>and <code>&#39;....&#39;</code> are valid directory or file names.</li>\n</ul>\n\n<p>The simplified canonical path should follow these <em>rules</em>:</p>\n\n<ul>\n\t<li>The path must start with a single slash <code>&#39;/&#39;</code>.</li>\n\t<li>Directories within the path must be separated by exactly one slash <code>&#39;/&#39;</code>.</li>\n\t<li>The path must not end with a slash <code>&#39;/&#39;</code>, unless it is the root directory.</li>\n\t<li>The path must not have any single or double periods (<code>&#39;.&#39;</code> and <code>&#39;..&#39;</code>) used to denote current or parent directories.</li>\n</ul>\n\n<p>Return the <strong>simplified canonical path</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">path = &quot;/home/&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;/home&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The trailing slash should be removed.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">path = &quot;/home//foo/&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;/home/foo&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Multiple consecutive slashes are replaced by a single one.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">path = &quot;/home/user/Documents/../Pictures&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;/home/user/Pictures&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>A double period <code>&quot;..&quot;</code> refers to the directory up a level (the parent directory).</p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">path = &quot;/../&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;/&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Going one level up from the root directory is not possible.</p>\n</div>\n\n<p><strong class=\"example\">Example 5:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">path = &quot;/.../a/../b/c/../d/./&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;/.../b/d&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><code>&quot;...&quot;</code> is a valid name for a directory in this problem.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= path.length &lt;= 3000</code></li>\n\t<li><code>path</code> consists of English letters, digits, period <code>&#39;.&#39;</code>, slash <code>&#39;/&#39;</code> or <code>&#39;_&#39;</code>.</li>\n\t<li><code>path</code> is a valid absolute Unix path.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/simplify-path/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def simplifyPath(self, path: str) -> str:\n    stack = []\n\n    for str in path.split('/'):\n      if str in ('', '.'):\n        continue\n      if str == '..':\n        if stack:\n          stack.pop()\n      else:\n        stack.append(str)\n\n    return '/' + '/'.join(stack)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String simplifyPath(String path) {\n    final String[] dirs = path.split(\"/\");\n    Stack<String> stack = new Stack<>();\n\n    for (final String dir : dirs) {\n      if (dir.isEmpty() || dir.equals(\".\"))\n        continue;\n      if (dir.equals(\"..\")) {\n        if (!stack.isEmpty())\n          stack.pop();\n      } else {\n        stack.push(dir);\n      }\n    }\n\n    return \"/\" + String.join(\"/\", stack);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string simplifyPath(string path) {\n    string ans;\n    istringstream iss(path);\n    vector<string> stack;\n\n    for (string dir; getline(iss, dir, '/');) {\n      if (dir.empty() || dir == \".\")\n        continue;\n      if (dir == \"..\") {\n        if (!stack.empty())\n          stack.pop_back();\n      } else {\n        stack.push_back(dir);\n      }\n    }\n\n    for (const string& s : stack)\n      ans += \"/\" + s;\n\n    return ans.empty() ? \"/\" : ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/71.html",
    "category": "Algorithms",
    "acceptance_rate": 47.4845134075857,
    "topics": [
      "String",
      "Stack"
    ],
    "hints": [],
    "likes": 6066,
    "dislikes": 1360,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1064332, \"totalSubmissionRaw\": 2241440, \"acRate\": \"47.5%\"}",
    "title_pt": "Simplificar Caminho",
    "description_pt": "<p>Você recebe um caminho <em>absoluto</em> para um sistema de arquivos no estilo Unix, que sempre começa com uma barra <code>&#39;/&#39;</code>. Sua tarefa é transformar esse caminho absoluto em seu <strong>caminho canônico simplificado</strong>.</p>\n\n<p>As <em>regras</em> de um sistema de arquivos no estilo Unix são as seguintes:</p>\n\n<ul>\n\t<li>Um único ponto <code>&#39;.&#39;</code> representa o diretório atual.</li>\n\t<li>Um duplo ponto <code>&#39;..&#39;</code> representa o diretório anterior/pai.</li>\n\t<li>Várias barras consecutivas, como <code>&#39;//&#39;</code> e <code>&#39;///&#39;</code>, são tratadas como uma única barra <code>&#39;/&#39;</code>.</li>\n\t<li>Qualquer sequência de pontos que <strong>não corresponda</strong> às regras acima deve ser tratada como um <strong>nome válido de diretório ou</strong> <strong>arquivo</strong>. Por exemplo, <code>&#39;...&#39; </code>e <code>&#39;....&#39;</code> são nomes válidos de diretório ou arquivo.</li>\n</ul>\n\n<p>O caminho canônico simplificado deve seguir estas <em>regras</em>:</p>\n\n<ul>\n\t<li>O caminho deve começar com uma única barra <code>&#39;/&#39;</code>.</li>\n\t<li>Os diretórios dentro do caminho devem ser separados por exatamente uma barra <code>&#39;/&#39;</code>.</li>\n\t<li>O caminho não deve terminar com uma barra <code>&#39;/&#39;</code>, a menos que seja o diretório raiz.</li>\n\t<li>O caminho não deve ter nenhum ponto simples ou duplo (<code>&#39;.&#39;</code> e <code>&#39;..&#39;</code>) usado para denotar diretórios atuais ou pais.</li>\n</ul>\n\n<p>Retorne o <strong>caminho canônico simplificado</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">path = &quot;/home/&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;/home&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A barra final deve ser removida.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">path = &quot;/home//foo/&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;/home/foo&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Múltiplas barras consecutivas são substituídas por uma única.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">path = &quot;/home/user/Documents/../Pictures&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;/home/user/Pictures&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Um duplo ponto <code>&quot;..&quot;</code> refere-se ao diretório um nível acima (o diretório pai).</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">path = &quot;/../&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;/&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Subir um nível a partir do diretório raiz não é possível.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 5:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">path = &quot;/.../a/../b/c/../d/./&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;/.../b/d&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><code>&quot;...&quot;</code> é um nome válido para um diretório neste problema.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= path.length &lt;= 3000</code></li>\n\t<li><code>path</code> consiste em letras do inglês, dígitos, ponto <code>&#39;.&#39;</code>, barra <code>&#39;/&#39;</code> ou <code>&#39;_&#39;</code>.</li>\n\t<li><code>path</code> é um caminho absoluto Unix válido.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "72",
    "paidOnly": false,
    "title": "Edit Distance",
    "titleSlug": "edit-distance",
    "url": "https://leetcode.com/problems/edit-distance",
    "description_url": "https://leetcode.com/problems/edit-distance/description/",
    "description": "<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of operations required to convert <code>word1</code> to <code>word2</code></em>.</p>\n\n<p>You have the following three operations permitted on a word:</p>\n\n<ul>\n\t<li>Insert a character</li>\n\t<li>Delete a character</li>\n\t<li>Replace a character</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> word1 = &quot;horse&quot;, word2 = &quot;ros&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> \nhorse -&gt; rorse (replace &#39;h&#39; with &#39;r&#39;)\nrorse -&gt; rose (remove &#39;r&#39;)\nrose -&gt; ros (remove &#39;e&#39;)\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> word1 = &quot;intention&quot;, word2 = &quot;execution&quot;\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> \nintention -&gt; inention (remove &#39;t&#39;)\ninention -&gt; enention (replace &#39;i&#39; with &#39;e&#39;)\nenention -&gt; exention (replace &#39;n&#39; with &#39;x&#39;)\nexention -&gt; exection (replace &#39;n&#39; with &#39;c&#39;)\nexection -&gt; execution (insert &#39;u&#39;)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= word1.length, word2.length &lt;= 500</code></li>\n\t<li><code>word1</code> and <code>word2</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/edit-distance/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minDistance(self, word1: str, word2: str) -> int:\n    m = len(word1)\n    n = len(word2)\n    # dp[i][j] := min # Of operations to convert word1[0..i) to word2[0..j)\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n    for i in range(1, m + 1):\n      dp[i][0] = i\n\n    for j in range(1, n + 1):\n      dp[0][j] = j\n\n    for i in range(1, m + 1):\n      for j in range(1, n + 1):\n        if word1[i - 1] == word2[j - 1]:\n          dp[i][j] = dp[i - 1][j - 1]\n        else:\n          dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minDistance(String word1, String word2) {\n    final int m = word1.length();\n    final int n = word2.length();\n    // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j)\n    int[][] dp = new int[m + 1][n + 1];\n\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = i;\n\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = j;\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (word1.charAt(i - 1) == word2.charAt(j - 1))\n          dp[i][j] = dp[i - 1][j - 1];\n        else\n          dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;\n\n    return dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minDistance(string word1, string word2) {\n    const int m = word1.length();\n    const int n = word2.length();\n    // dp[i][j] := min # of operations to convert word1[0..i) to word2[0..j)\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = i;\n\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = j;\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (word1[i - 1] == word2[j - 1])\n          dp[i][j] = dp[i - 1][j - 1];\n        else\n          dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/72.html",
    "category": "Algorithms",
    "acceptance_rate": 58.59239065604317,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 15577,
    "dislikes": 276,
    "similar_questions": "[{\"title\": \"One Edit Distance\", \"titleSlug\": \"one-edit-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete Operation for Two Strings\", \"titleSlug\": \"delete-operation-for-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum ASCII Delete Sum for Two Strings\", \"titleSlug\": \"minimum-ascii-delete-sum-for-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Uncrossed Lines\", \"titleSlug\": \"uncrossed-lines\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum White Tiles After Covering With Carpets\", \"titleSlug\": \"minimum-white-tiles-after-covering-with-carpets\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Palindrome After Substring Concatenation II\", \"titleSlug\": \"longest-palindrome-after-substring-concatenation-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1139535, \"totalSubmissionRaw\": 1944854, \"acRate\": \"58.6%\"}",
    "title_pt": "Distância de Edição",
    "description_pt": "<p>Dadas duas strings <code>word1</code> e <code>word2</code>, retorne <em>o número mínimo de operações necessárias para converter <code>word1</code> em <code>word2</code></em>.</p>\n\n<p>Você tem as três operações a seguir permitidas em uma palavra:</p>\n\n<ul>\n\t<li>Inserir um caractere</li>\n\t<li>Remover um caractere</li>\n\t<li>Substituir um caractere</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> word1 = &quot;horse&quot;, word2 = &quot;ros&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> \nhorse -&gt; rorse (substituir &#39;h&#39; por &#39;r&#39;)\nrorse -&gt; rose (remover &#39;r&#39;)\nrose -&gt; ros (remover &#39;e&#39;)\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> word1 = &quot;intention&quot;, word2 = &quot;execution&quot;\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> \nintention -&gt; inention (remover &#39;t&#39;)\ninention -&gt; enention (substituir &#39;i&#39; por &#39;e&#39;)\nenention -&gt; exention (substituir &#39;n&#39; por &#39;x&#39;)\nexention -&gt; exection (substituir &#39;n&#39; por &#39;c&#39;)\nexection -&gt; execution (inserir &#39;u&#39;)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= word1.length, word2.length &lt;= 500</code></li>\n\t<li><code>word1</code> e <code>word2</code> consistem de letras minúsculas do alfabeto ইংlês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "73",
    "paidOnly": false,
    "title": "Set Matrix Zeroes",
    "titleSlug": "set-matrix-zeroes",
    "url": "https://leetcode.com/problems/set-matrix-zeroes",
    "description_url": "https://leetcode.com/problems/set-matrix-zeroes/description/",
    "description": "<p>Given an <code>m x n</code> integer matrix <code>matrix</code>, if an element is <code>0</code>, set its entire row and column to <code>0</code>&#39;s.</p>\n\n<p>You must do it <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in place</a>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg\" style=\"width: 450px; height: 169px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,1,1],[1,0,1],[1,1,1]]\n<strong>Output:</strong> [[1,0,1],[0,0,0],[1,0,1]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg\" style=\"width: 450px; height: 137px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\n<strong>Output:</strong> [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[0].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>A straightforward solution using <code>O(mn)</code> space is probably a bad idea.</li>\n\t<li>A simple improvement uses <code>O(m + n)</code> space, but still not the best solution.</li>\n\t<li>Could you devise a constant space solution?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/set-matrix-zeroes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def setZeroes(self, matrix: List[List[int]]) -> None:\n    m = len(matrix)\n    n = len(matrix[0])\n    shouldFillFirstRow = 0 in matrix[0]\n    shouldFillFirstCol = 0 in list(zip(*matrix))[0]\n\n    # Store the information in the 1st row/col\n    for i in range(1, m):\n      for j in range(1, n):\n        if matrix[i][j] == 0:\n          matrix[i][0] = 0\n          matrix[0][j] = 0\n\n    # Fill 0s for the matrix except the 1st row/col\n    for i in range(1, m):\n      for j in range(1, n):\n        if matrix[i][0] == 0 or matrix[0][j] == 0:\n          matrix[i][j] = 0\n\n    # Fill 0s for the 1st row if needed\n    if shouldFillFirstRow:\n      matrix[0] = [0] * n\n\n    # Fill 0s for the 1st col if needed\n    if shouldFillFirstCol:\n      for row in matrix:\n        row[0] = 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void setZeroes(int[][] matrix) {\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    boolean shouldFillFirstRow = false;\n    boolean shouldFillFirstCol = false;\n\n    for (int j = 0; j < n; ++j)\n      if (matrix[0][j] == 0) {\n        shouldFillFirstRow = true;\n        break;\n      }\n\n    for (int i = 0; i < m; ++i)\n      if (matrix[i][0] == 0) {\n        shouldFillFirstCol = true;\n        break;\n      }\n\n    // Store the information in the 1st row/col\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        if (matrix[i][j] == 0) {\n          matrix[i][0] = 0;\n          matrix[0][j] = 0;\n        }\n\n    // Fill 0s for the matrix except the 1st row/col\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        if (matrix[i][0] == 0 || matrix[0][j] == 0)\n          matrix[i][j] = 0;\n\n    // Fill 0s for the 1st row if needed\n    if (shouldFillFirstRow)\n      for (int j = 0; j < n; ++j)\n        matrix[0][j] = 0;\n\n    // Fill 0s for the 1st col if needed\n    if (shouldFillFirstCol)\n      for (int i = 0; i < m; ++i)\n        matrix[i][0] = 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void setZeroes(vector<vector<int>>& matrix) {\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    bool shouldFillFirstRow = false;\n    bool shouldFillFirstCol = false;\n\n    for (int j = 0; j < n; ++j)\n      if (matrix[0][j] == 0) {\n        shouldFillFirstRow = true;\n        break;\n      }\n\n    for (int i = 0; i < m; ++i)\n      if (matrix[i][0] == 0) {\n        shouldFillFirstCol = true;\n        break;\n      }\n\n    // Store the information in the 1st row/col\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        if (matrix[i][j] == 0) {\n          matrix[i][0] = 0;\n          matrix[0][j] = 0;\n        }\n\n    // Fill 0s for the matrix except the 1st row/col\n    for (int i = 1; i < m; ++i)\n      for (int j = 1; j < n; ++j)\n        if (matrix[i][0] == 0 || matrix[0][j] == 0)\n          matrix[i][j] = 0;\n\n    // Fill 0s for the 1st row if needed\n    if (shouldFillFirstRow)\n      for (int j = 0; j < n; ++j)\n        matrix[0][j] = 0;\n\n    // Fill 0s for the 1st col if needed\n    if (shouldFillFirstCol)\n      for (int i = 0; i < m; ++i)\n        matrix[i][0] = 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/73.html",
    "category": "Algorithms",
    "acceptance_rate": 59.535832672213914,
    "topics": [
      "Array",
      "Hash Table",
      "Matrix"
    ],
    "hints": [
      "If any cell of the matrix has a zero we can record its row and column number using additional memory.\r\nBut if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says.",
      "Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?\r\nThere is still a better approach for this problem with 0(1) space.",
      "We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information.",
      "We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero."
    ],
    "likes": 15588,
    "dislikes": 791,
    "similar_questions": "[{\"title\": \"Game of Life\", \"titleSlug\": \"game-of-life\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Laser Beams in a Bank\", \"titleSlug\": \"number-of-laser-beams-in-a-bank\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Remove Adjacent Ones in Matrix\", \"titleSlug\": \"minimum-operations-to-remove-adjacent-ones-in-matrix\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Remove All Ones With Row and Column Flips II\", \"titleSlug\": \"remove-all-ones-with-row-and-column-flips-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1936135, \"totalSubmissionRaw\": 3252054, \"acRate\": \"59.5%\"}",
    "title_pt": "Definir Zeros na Matriz",
    "description_pt": "<p>Dada uma matriz inteira <code>m x n</code> <code>matrix</code>, se um elemento for <code>0</code>, defina toda a sua linha e coluna como <code>0</code>&#39;s.</p>\n\n<p>Você deve fazer isso <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in place</a>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/mat1.jpg\" style=\"width: 450px; height: 169px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,1,1],[1,0,1],[1,1,1]]\n<strong>Saída:</strong> [[1,0,1],[0,0,0],[1,0,1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/mat2.jpg\" style=\"width: 450px; height: 137px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\n<strong>Saída:</strong> [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[0].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Uma solução direta usando espaço <code>O(mn)</code> é provavelmente uma má ideia.</li>\n\t<li>Uma melhoria simples usa espaço <code>O(m + n)</code>, mas ainda não é a melhor solução.</li>\n\t<li>Você consegue elaborar uma solução com espaço constante?</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Se qualquer célula da matriz tiver um zero, podemos registrar o número de sua linha e coluna usando memória adicional.\r\nMas, se você não quiser usar memória extra, então pode manipular o array em vez disso. isto é, simulando exatamente o que a questão diz.",
      "- Dica 2: Definir os valores das células como zero durante a iteração pode levar a discrepâncias. E se você usar algum outro valor inteiro como sua marcação?\r\nAinda há uma abordagem melhor para este problema com espaço O(1).",
      "- Dica 3: Poderíamos ter usado 2 conjuntos para manter um registro das linhas/colunas que precisam ser definidas como zero. Mas, para uma solução com espaço O(1), você pode usar uma das linhas e uma das colunas para manter o controle dessas informações.",
      "- Dica 4: Podemos usar a primeira célula de cada linha e coluna como uma flag. Essa flag determinaria se uma linha ou coluna foi definida como zero."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "74",
    "paidOnly": false,
    "title": "Search a 2D Matrix",
    "titleSlug": "search-a-2d-matrix",
    "url": "https://leetcode.com/problems/search-a-2d-matrix",
    "description_url": "https://leetcode.com/problems/search-a-2d-matrix/description/",
    "description": "<p>You are given an <code>m x n</code> integer matrix <code>matrix</code> with the following two properties:</p>\n\n<ul>\n\t<li>Each row is sorted in non-decreasing order.</li>\n\t<li>The first integer of each row is greater than the last integer of the previous row.</li>\n</ul>\n\n<p>Given an integer <code>target</code>, return <code>true</code> <em>if</em> <code>target</code> <em>is in</em> <code>matrix</code> <em>or</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>You must write a solution in <code>O(log(m * n))</code> time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= matrix[i][j], target &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/search-a-2d-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n    if not matrix:\n      return False\n\n    m = len(matrix)\n    n = len(matrix[0])\n    l = 0\n    r = m * n\n\n    while l < r:\n      mid = (l + r) // 2\n      i = mid // n\n      j = mid % n\n      if matrix[i][j] == target:\n        return True\n      if matrix[i][j] < target:\n        l = mid + 1\n      else:\n        r = mid\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean searchMatrix(int[][] matrix, int target) {\n    if (matrix.length == 0)\n      return false;\n\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    int l = 0;\n    int r = m * n;\n\n    while (l < r) {\n      final int mid = (l + r) / 2;\n      final int i = mid / n;\n      final int j = mid % n;\n      if (matrix[i][j] == target)\n        return true;\n      if (matrix[i][j] < target)\n        l = mid + 1;\n      else\n        r = mid;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool searchMatrix(vector<vector<int>>& matrix, int target) {\n    if (matrix.empty())\n      return false;\n\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    int l = 0;\n    int r = m * n;\n\n    while (l < r) {\n      const int mid = (l + r) / 2;\n      const int i = mid / n;\n      const int j = mid % n;\n      if (matrix[i][j] == target)\n        return true;\n      if (matrix[i][j] < target)\n        l = mid + 1;\n      else\n        r = mid;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/74.html",
    "category": "Algorithms",
    "acceptance_rate": 52.10603925666061,
    "topics": [
      "Array",
      "Binary Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 16753,
    "dislikes": 450,
    "similar_questions": "[{\"title\": \"Search a 2D Matrix II\", \"titleSlug\": \"search-a-2d-matrix-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split Message Based on Limit\", \"titleSlug\": \"split-message-based-on-limit\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"4.5M\", \"totalAcceptedRaw\": 2321921, \"totalSubmissionRaw\": 4456150, \"acRate\": \"52.1%\"}",
    "title_pt": "Buscar em uma Matriz 2D",
    "description_pt": "<p>Você recebe uma matriz inteira <code>m x n</code> <code>matrix</code> com as seguintes duas propriedades:</p>\n\n<ul>\n\t<li>Cada linha está ordenada em ordem não decrescente.</li>\n\t<li>O primeiro inteiro de cada linha é maior do que o último inteiro da linha anterior.</li>\n</ul>\n\n<p>Dado um inteiro <code>target</code>, retorne <code>true</code> <em>se</em> <code>target</code> <em>estiver em</em> <code>matrix</code> <em>ou</em> <code>false</code> <em>caso contrário</em>.</p>\n\n<p>Você deve escrever uma solução com complexidade de tempo <code>O(log(m * n))</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= matrix[i][j], target &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "75",
    "paidOnly": false,
    "title": "Sort Colors",
    "titleSlug": "sort-colors",
    "url": "https://leetcode.com/problems/sort-colors",
    "description_url": "https://leetcode.com/problems/sort-colors/description/",
    "description": "<p>Given an array <code>nums</code> with <code>n</code> objects colored red, white, or blue, sort them <strong><a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> </strong>so that objects of the same color are adjacent, with the colors in the order red, white, and blue.</p>\n\n<p>We will use the integers <code>0</code>, <code>1</code>, and <code>2</code> to represent the color red, white, and blue, respectively.</p>\n\n<p>You must solve this problem without using the library&#39;s sort function.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,0,2,1,1,0]\n<strong>Output:</strong> [0,0,1,1,2,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,0,1]\n<strong>Output:</strong> [0,1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>nums[i]</code> is either <code>0</code>, <code>1</code>, or <code>2</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong>&nbsp;Could you come up with a one-pass algorithm using only&nbsp;constant extra space?</p>\n",
    "solution_url": "https://leetcode.com/problems/sort-colors/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def sortColors(self, nums: List[int]) -> None:\n    zero = -1\n    one = -1\n    two = -1\n\n    for num in nums:\n      if num == 0:\n        two += 1\n        one += 1\n        zero += 1\n        nums[two] = 2\n        nums[one] = 1\n        nums[zero] = 0\n      elif num == 1:\n        two += 1\n        one += 1\n        nums[two] = 2\n        nums[one] = 1\n      else:\n        two += 1\n        nums[two] = 2",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void sortColors(int[] nums) {\n    int zero = -1;\n    int one = -1;\n    int two = -1;\n\n    for (final int num : nums)\n      if (num == 0) {\n        nums[++two] = 2;\n        nums[++one] = 1;\n        nums[++zero] = 0;\n      } else if (num == 1) {\n        nums[++two] = 2;\n        nums[++one] = 1;\n      } else {\n        nums[++two] = 2;\n      }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void sortColors(vector<int>& nums) {\n    int zero = -1;\n    int one = -1;\n    int two = -1;\n\n    for (const int num : nums)\n      if (num == 0) {\n        nums[++two] = 2;\n        nums[++one] = 1;\n        nums[++zero] = 0;\n      } else if (num == 1) {\n        nums[++two] = 2;\n        nums[++one] = 1;\n      } else {\n        nums[++two] = 2;\n      }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/75.html",
    "category": "Algorithms",
    "acceptance_rate": 67.03235482371839,
    "topics": [
      "Array",
      "Two Pointers",
      "Sorting"
    ],
    "hints": [
      "A rather straight forward solution is a two-pass algorithm using counting sort.",
      "Iterate the array counting number of 0's, 1's, and 2's.",
      "Overwrite array with the total number of 0's, then 1's and followed by 2's."
    ],
    "likes": 19857,
    "dislikes": 704,
    "similar_questions": "[{\"title\": \"Sort List\", \"titleSlug\": \"sort-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort\", \"titleSlug\": \"wiggle-sort\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort II\", \"titleSlug\": \"wiggle-sort-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2843737, \"totalSubmissionRaw\": 4242549, \"acRate\": \"67.0%\"}",
    "title_pt": "Ordenar Cores",
    "description_pt": "<p>Dado um array <code>nums</code> com <code>n</code> objetos coloridos de vermelho, branco ou azul, ordene-os <strong><a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> </strong>de modo que os objetos da mesma cor fiquem adjacentes, com as cores na ordem vermelho, branco e azul.</p>\n\n<p>Usaremos os inteiros <code>0</code>, <code>1</code> e <code>2</code> para representar as cores vermelho, branco e azul, respectivamente.</p>\n\n<p>Você deve resolver este problema sem usar a função de ordenação da biblioteca.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,0,2,1,1,0]\n<strong>Saída:</strong> [0,0,1,1,2,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,0,1]\n<strong>Saída:</strong> [0,1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>nums[i]</code> é ou <code>0</code>, ou <code>1</code>, ou <code>2</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong>&nbsp;Você conseguiria criar um algoritmo de uma passada usando apenas&nbsp;espaço extra constante?</p>",
    "hints_pt": [
      "Dica 1: Uma solução bastante direta é um algoritmo de duas passagens usando counting sort.",
      "Dica 2: Percorra o array contando o número de 0's, 1's e 2's.",
      "Dica 3: Sobrescreva o array com o número total de 0's, depois de 1's e, em seguida, de 2's."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "76",
    "paidOnly": false,
    "title": "Minimum Window Substring",
    "titleSlug": "minimum-window-substring",
    "url": "https://leetcode.com/problems/minimum-window-substring",
    "description_url": "https://leetcode.com/problems/minimum-window-substring/description/",
    "description": "<p>Given two strings <code>s</code> and <code>t</code> of lengths <code>m</code> and <code>n</code> respectively, return <em>the <strong>minimum window</strong></em> <span data-keyword=\"substring-nonempty\"><strong><em>substring</em></strong></span><em> of </em><code>s</code><em> such that every character in </em><code>t</code><em> (<strong>including duplicates</strong>) is included in the window</em>. If there is no such substring, return <em>the empty string </em><code>&quot;&quot;</code>.</p>\n\n<p>The testcases will be generated such that the answer is <strong>unique</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;ADOBECODEBANC&quot;, t = &quot;ABC&quot;\n<strong>Output:</strong> &quot;BANC&quot;\n<strong>Explanation:</strong> The minimum window substring &quot;BANC&quot; includes &#39;A&#39;, &#39;B&#39;, and &#39;C&#39; from string t.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a&quot;, t = &quot;a&quot;\n<strong>Output:</strong> &quot;a&quot;\n<strong>Explanation:</strong> The entire string s is the minimum window.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a&quot;, t = &quot;aa&quot;\n<strong>Output:</strong> &quot;&quot;\n<strong>Explanation:</strong> Both &#39;a&#39;s from t must be included in the window.\nSince the largest window of s only has one &#39;a&#39;, return empty string.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == s.length</code></li>\n\t<li><code>n == t.length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of uppercase and lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you find an algorithm that runs in <code>O(m + n)</code> time?</p>\n",
    "solution_url": "https://leetcode.com/problems/minimum-window-substring/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minWindow(self, s: str, t: str) -> str:\n    count = Counter(t)\n    required = len(t)\n    bestLeft = -1\n    minLength = len(s) + 1\n\n    l = 0\n    for r, c in enumerate(s):\n      count[c] -= 1\n      if count[c] >= 0:\n        required -= 1\n      while required == 0:\n        if r - l + 1 < minLength:\n          bestLeft = l\n          minLength = r - l + 1\n        count[s[l]] += 1\n        if count[s[l]] > 0:\n          required += 1\n        l += 1\n\n    return '' if bestLeft == -1 else s[bestLeft: bestLeft + minLength]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String minWindow(String s, String t) {\n    int[] count = new int[128];\n    int required = t.length();\n    int bestLeft = -1;\n    int minLength = s.length() + 1;\n\n    for (final char c : t.toCharArray())\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (--count[s.charAt(r)] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 < minLength) {\n          bestLeft = l;\n          minLength = r - l + 1;\n        }\n        if (++count[s.charAt(l++)] > 0)\n          ++required;\n      }\n    }\n\n    return bestLeft == -1 ? \"\" : s.substring(bestLeft, bestLeft + minLength);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string minWindow(string s, string t) {\n    vector<int> count(128);\n    int required = t.length();\n    int bestLeft = -1;\n    int minLength = s.length() + 1;\n\n    for (const char c : t)\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (--count[s[r]] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 < minLength) {\n          bestLeft = l;\n          minLength = r - l + 1;\n        }\n        if (++count[s[l++]] > 0)\n          ++required;\n      }\n    }\n\n    return bestLeft == -1 ? \"\" : s.substr(bestLeft, minLength);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/76.html",
    "category": "Algorithms",
    "acceptance_rate": 45.122489418453384,
    "topics": [
      "Hash Table",
      "String",
      "Sliding Window"
    ],
    "hints": [
      "Use two pointers to create a window of letters in s, which would have all the characters from t.",
      "Expand the right pointer until all the characters of t are covered.",
      "Once all the characters are covered, move the left pointer and ensure that all the characters are still covered to minimize the subarray size.",
      "Continue expanding the right and left pointers until you reach the end of s."
    ],
    "likes": 18863,
    "dislikes": 783,
    "similar_questions": "[{\"title\": \"Substring with Concatenation of All Words\", \"titleSlug\": \"substring-with-concatenation-of-all-words\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Size Subarray Sum\", \"titleSlug\": \"minimum-size-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sliding Window Maximum\", \"titleSlug\": \"sliding-window-maximum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Permutation in String\", \"titleSlug\": \"permutation-in-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Range Covering Elements from K Lists\", \"titleSlug\": \"smallest-range-covering-elements-from-k-lists\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Window Subsequence\", \"titleSlug\": \"minimum-window-subsequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Substrings That Can Be Rearranged to Contain a String II\", \"titleSlug\": \"count-substrings-that-can-be-rearranged-to-contain-a-string-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Substrings That Can Be Rearranged to Contain a String I\", \"titleSlug\": \"count-substrings-that-can-be-rearranged-to-contain-a-string-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"3.8M\", \"totalAcceptedRaw\": 1723823, \"totalSubmissionRaw\": 3820323, \"acRate\": \"45.1%\"}",
    "title_pt": "Substring de Janela Mínima",
    "description_pt": "<p>Dadas duas strings <code>s</code> e <code>t</code> de comprimentos <code>m</code> e <code>n</code>, respectivamente, retorne <em>a <strong>substring de janela mínima</strong></em> <span data-keyword=\"substring-nonempty\"><strong><em>substring</em></strong></span><em> de </em><code>s</code><em> tal que cada caractere em </em><code>t</code><em> (<strong>incluindo duplicatas</strong>) esteja incluído na janela</em>. Se não houver tal substring, retorne <em>a string vazia </em><code>&quot;&quot;</code>.</p>\n\n<p>Os casos de teste serão gerados de forma que a resposta seja <strong>única</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;ADOBECODEBANC&quot;, t = &quot;ABC&quot;\n<strong>Saída:</strong> &quot;BANC&quot;\n<strong>Explicação:</strong> A substring de janela mínima &quot;BANC&quot; inclui &#39;A&#39;, &#39;B&#39; e &#39;C&#39; da string t.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a&quot;, t = &quot;a&quot;\n<strong>Saída:</strong> &quot;a&quot;\n<strong>Explicação:</strong> A string s inteira é a janela mínima.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a&quot;, t = &quot;aa&quot;\n<strong>Saída:</strong> &quot;&quot;\n<strong>Explicação:</strong> Ambos os &#39;a&#39;s de t devem ser incluídos na janela.\nComo a maior janela de s tem apenas um &#39;a&#39;, retorne string vazia.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == s.length</code></li>\n\t<li><code>n == t.length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> e <code>t</code> consistem em letras inglesas maiúsculas e minúsculas.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria encontrar um algoritmo que execute em tempo <code>O(m + n)</code>?</p>",
    "hints_pt": [
      "- Dica 1: Use dois ponteiros para criar uma janela de letras em s, que conteria todos os caracteres de t.",
      "- Dica 2: Expanda o ponteiro da direita até que todos os caracteres de t estejam cobertos.",
      "- Dica 3: Assim que todos os caracteres estiverem cobertos, mova o ponteiro da esquerda e garanta que todos os caracteres ainda estejam cobertos para minimizar o tamanho do subarray.",
      "- Dica 4: Continue expandindo os ponteiros da direita e da esquerda até chegar ao final de s."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "77",
    "paidOnly": false,
    "title": "Combinations",
    "titleSlug": "combinations",
    "url": "https://leetcode.com/problems/combinations",
    "description_url": "https://leetcode.com/problems/combinations/description/",
    "description": "<p>Given two integers <code>n</code> and <code>k</code>, return <em>all possible combinations of</em> <code>k</code> <em>numbers chosen from the range</em> <code>[1, n]</code>.</p>\n\n<p>You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 4, k = 2\n<strong>Output:</strong> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n<strong>Explanation:</strong> There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, k = 1\n<strong>Output:</strong> [[1]]\n<strong>Explanation:</strong> There is 1 choose 1 = 1 total combination.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>1 &lt;= k &lt;= n</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/combinations/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def combine(self, n: int, k: int) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, path: List[int]) -> None:\n      if len(path) == k:\n        ans.append(path.copy())\n        return\n\n      for i in range(s, n + 1):\n        path.append(i)\n        dfs(i + 1, path)\n        path.pop()\n\n    dfs(1, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> combine(int n, int k) {\n    List<List<Integer>> ans = new ArrayList<>();\n    dfs(n, k, 1, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int n, int k, int s, List<Integer> path, List<List<Integer>> ans) {\n    if (path.size() == k) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = s; i <= n; ++i) {\n      path.add(i);\n      dfs(n, k, i + 1, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> combine(int n, int k) {\n    vector<vector<int>> ans;\n    dfs(n, k, 1, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(int n, int k, int s, vector<int>&& path, vector<vector<int>>& ans) {\n    if (path.size() == k) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = s; i <= n; ++i) {\n      path.push_back(i);\n      dfs(n, k, i + 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/77.html",
    "category": "Algorithms",
    "acceptance_rate": 72.6973374298635,
    "topics": [
      "Backtracking"
    ],
    "hints": [],
    "likes": 8554,
    "dislikes": 236,
    "similar_questions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Permutations\", \"titleSlug\": \"permutations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 1111139, \"totalSubmissionRaw\": 1528446, \"acRate\": \"72.7%\"}",
    "title_pt": "Combinações",
    "description_pt": "<p>Dados dois inteiros <code>n</code> e <code>k</code>, retorne <em>todas as combinações possíveis de</em> <code>k</code> <em>números escolhidos do intervalo</em> <code>[1, n]</code>.</p>\n\n<p>Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 4, k = 2\n<strong>Saída:</strong> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n<strong>Explicação:</strong> Existem 4 choose 2 = 6 combinações no total.\nObserve que combinações não são ordenadas, isto é, [1,2] e [2,1] são consideradas a mesma combinação.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, k = 1\n<strong>Saída:</strong> [[1]]\n<strong>Explicação:</strong> Existe 1 choose 1 = 1 combinação no total.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 20</code></li>\n\t<li><code>1 &lt;= k &lt;= n</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "78",
    "paidOnly": false,
    "title": "Subsets",
    "titleSlug": "subsets",
    "url": "https://leetcode.com/problems/subsets",
    "description_url": "https://leetcode.com/problems/subsets/description/",
    "description": "<p>Given an integer array <code>nums</code> of <strong>unique</strong> elements, return <em>all possible</em> <span data-keyword=\"subset\"><em>subsets</em></span> <em>(the power set)</em>.</p>\n\n<p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0]\n<strong>Output:</strong> [[],[0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>All the numbers of&nbsp;<code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/subsets/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Overview: Solution Pattern\n\nLet us first review the problems of Permutations / Combinations / Subsets, since they are quite similar to each other and there are some common strategies to solve them.\n\nFirst, their solution space is often quite large:\n\n- [Permutations](https://en.wikipedia.org/wiki/Permutation#k-permutations_of_n): $$N!$$. \n\n- [Combinations](https://en.wikipedia.org/wiki/Combination#Number_of_k-combinations): $$C_N^k = \\frac{N!}{(N - k)! k!}$$\n\n- Subsets: $$2^N$$, since each element could be absent or present. \n\nGiven their exponential solution space, it is tricky to ensure that the generated solutions are _**complete**_ and _**non-redundant**_. It is essential to have a clear and easy-to-reason strategy.\n\nThere are generally three strategies to do it:\n\n- Iterative\n\n- Recursion/Backtracking\n\n- Lexicographic generation based on the mapping between binary bitmasks and the corresponding permutations / combinations / subsets.\n\nAs one would see later, the third method could be a good candidate for the interview because it simplifies the problem to the generation of binary numbers, therefore it is easy to implement and verify that no solution is missing.\n\nBesides, as a bonus, it generates lexicographically sorted output for the sorted inputs.\n\n\n---\n### Approach 1: Cascading\n\n#### Intuition\n\nLet's start from an empty subset in the output list. At each step, one takes a new integer into consideration and generates new subsets from the existing ones. \n\n![diff](../Figures/78/recursion.png)\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/GfSoguWr/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"GfSoguWr\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $$\\mathcal{O}(N \\times 2^N)$$ to generate all subsets and then copy them into the output list. \n    \n* Space complexity: $$\\mathcal{O}(N \\times 2^N)$$. This is exactly the number of solutions for subsets multiplied by the number $$N$$ of elements to keep for each subset.  \n    - For a given number, it could be present or absent (_i.e._ binary choice) in a subset solution. As a result, for $$N$$ numbers, we would have in total $$2^N$$ choices (solutions). \n<br />\n<br />\n\n\n---\n### Approach 2: Backtracking\n\n#### Algorithm\n\n>Power set is all possible combinations of all possible _lengths_, from 0 to n.\n\nGiven the definition, the problem can also be interpreted as finding the _power set_ from a sequence.\n\nSo, this time let us loop over the length of combination, rather than the candidate numbers, and generate all combinations for a given length with the help of _backtracking_ technique.\n\n![diff](../Figures/78/combinations.png)\n\n>[Backtracking](https://leetcode.com/explore/learn/card/recursion-ii/472/backtracking/2654/) is an algorithm for finding all solutions by exploring all potential candidates. If the solution candidate turns out to be _not_ a solution (or at least not the _last_ one), the backtracking algorithm discards it by making some changes on the previous step, *i.e.* _backtracks_ and then tries again.\n\n![diff](../Figures/78/backtracking.png)\n\n#### Algorithm\n\nWe define a backtrack function named `backtrack(first, curr)` that takes the index of the first element to add and a current combination as arguments.\n\n- If the current combination is done, we add the combination to the final output.\n\n- Otherwise, we iterate over the indexes `i` from `first` to the length of the entire sequence `n`.\n\n    - Add integer `nums[i]` into the current combination `curr`.\n\n    - Proceed to add more integers into the combination: `backtrack(i + 1, curr)`.\n\n    - Backtrack by removing `nums[i]` from `curr`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/X6GCLJ3t/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"X6GCLJ3t\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $$\\mathcal{O}(N \\times 2^N)$$ to generate all subsets and then copy them into the output list.\n \n* Space complexity: $$\\mathcal{O}(N)$$. We are using $$O(N)$$ space to maintain `curr`, and are modifying `curr` in-place with backtracking. Note that for space complexity analysis, we do not count space that is *only* used for the purpose of returning output, so the `output` array is ignored.\n\n\n---\n### Approach 3: Lexicographic (Binary Sorted) Subsets\n\n#### Intuition\n\nThe idea of this solution is originated from [Donald E. Knuth](https://www-cs-faculty.stanford.edu/~knuth/taocp.html).\n\n>The idea is that we map each subset to a bitmask of length n,\nwhere `1` on the i*th* position in bitmask means the presence of `nums[i]`\nin the subset, and `0` means its absence. \n\n![diff](../Figures/78/bitmask4.png)\n\nFor instance, the bitmask `0..00` (all zeros) corresponds to an empty subset, \nand the bitmask `1..11` (all ones) corresponds to the entire input array `nums`. \n\nHence to solve the initial problem, we just need to generate n bitmasks\nfrom `0..00` to `1..11`. \n\nIt might seem simple at first glance to generate binary numbers, but \nthe real problem here is how to deal with \n[zero left padding](https://en.wikipedia.org/wiki/Padding_(cryptography)#Zero_padding),\nbecause one has to generate bitmasks of fixed length, _i.e._ `001` and not just `1`.\nFor that one could use standard bit manipulation trick:\n\n<iframe src=\"https://leetcode.com/playground/PtHUHaeY/shared\" frameBorder=\"0\" width=\"100%\" height=\"140\" name=\"PtHUHaeY\"></iframe>\n\nor keep it simple stupid and shift iteration limits:\n\n<iframe src=\"https://leetcode.com/playground/4XWEGcWd/shared\" frameBorder=\"0\" width=\"100%\" height=\"123\" name=\"4XWEGcWd\"></iframe>\n\n#### Algorithm\n\n- Generate all possible binary bitmasks of length n.\n\n- Map a subset to each bitmask: \n`1` on the i*th* position in bitmask means the presence of `nums[i]`\nin the subset, and `0` means its absence. \n\n- Return output list.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/DwHHy2yt/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"DwHHy2yt\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $$\\mathcal{O}(N \\times 2^N)$$ to generate all subsets \nand then copy them into output list.\n    \n* Space complexity: $$\\mathcal{O}(N)$$ to store the bitset\nof length $$N$$. Note that for space complexity analysis, we do not count space that is *only* used for the purpose of returning output, so the `output` array is ignored.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def subsets(self, nums: List[int]) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, path: List[int]) -> None:\n      ans.append(path)\n\n      for i in range(s, len(nums)):\n        dfs(i + 1, path + [nums[i]])\n\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> subsets(int[] nums) {\n    List<List<Integer>> ans = new ArrayList<>();\n    dfs(nums, 0, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int[] nums, int s, List<Integer> path, List<List<Integer>> ans) {\n    ans.add(new ArrayList<>(path));\n\n    for (int i = s; i < nums.length; ++i) {\n      path.add(nums[i]);\n      dfs(nums, i + 1, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> subsets(vector<int>& nums) {\n    vector<vector<int>> ans;\n    dfs(nums, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& nums, int s, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    ans.push_back(path);\n\n    for (int i = s; i < nums.size(); ++i) {\n      path.push_back(nums[i]);\n      dfs(nums, i + 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/78.html",
    "category": "Algorithms",
    "acceptance_rate": 80.66235760785779,
    "topics": [
      "Array",
      "Backtracking",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 18140,
    "dislikes": 305,
    "similar_questions": "[{\"title\": \"Subsets II\", \"titleSlug\": \"subsets-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Generalized Abbreviation\", \"titleSlug\": \"generalized-abbreviation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Letter Case Permutation\", \"titleSlug\": \"letter-case-permutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Array Given Subset Sums\", \"titleSlug\": \"find-array-given-subset-sums\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Number of Maximum Bitwise-OR Subsets\", \"titleSlug\": \"count-number-of-maximum-bitwise-or-subsets\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"3.1M\", \"totalAcceptedRaw\": 2467442, \"totalSubmissionRaw\": 3058977, \"acRate\": \"80.7%\"}",
    "title_pt": "Subconjuntos",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> de elementos <strong>únicos</strong>, retorne <em>todos os</em> <span data-keyword=\"subset\"><em>subconjuntos</em></span> <em>(o conjunto potência)</em> possíveis.</p>\n\n<p>O conjunto de soluções <strong>não deve</strong> conter subconjuntos duplicados. Retorne a solução em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0]\n<strong>Saída:</strong> [[],[0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>Todos os números de&nbsp;<code>nums</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "79",
    "paidOnly": false,
    "title": "Word Search",
    "titleSlug": "word-search",
    "url": "https://leetcode.com/problems/word-search",
    "description_url": "https://leetcode.com/problems/word-search/description/",
    "description": "<p>Given an <code>m x n</code> grid of characters <code>board</code> and a string <code>word</code>, return <code>true</code> <em>if</em> <code>word</code> <em>exists in the grid</em>.</p>\n\n<p>The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word2.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;ABCCED&quot;\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;SEE&quot;\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/word3.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;ABCB&quot;\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n = board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 6</code></li>\n\t<li><code>1 &lt;= word.length &lt;= 15</code></li>\n\t<li><code>board</code> and <code>word</code> consists of only lowercase and uppercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you use search pruning to make your solution faster with a larger <code>board</code>?</p>\n",
    "solution_url": "https://leetcode.com/problems/word-search/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def exist(self, board: List[List[str]], word: str) -> bool:\n    m = len(board)\n    n = len(board[0])\n\n    def dfs(i: int, j: int, s: int) -> bool:\n      if i < 0 or i == m or j < 0 or j == n:\n        return False\n      if board[i][j] != word[s] or board[i][j] == '*':\n        return False\n      if s == len(word) - 1:\n        return True\n\n      cache = board[i][j]\n      board[i][j] = '*'\n      isExist = \\\n          dfs(i + 1, j, s + 1) or \\\n          dfs(i - 1, j, s + 1) or \\\n          dfs(i, j + 1, s + 1) or \\\n          dfs(i, j - 1, s + 1)\n      board[i][j] = cache\n\n      return isExist\n\n    return any(dfs(i, j, 0) for i in range(m) for j in range(n))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean exist(char[][] board, String word) {\n    for (int i = 0; i < board.length; ++i)\n      for (int j = 0; j < board[0].length; ++j)\n        if (dfs(board, word, i, j, 0))\n          return true;\n    return false;\n  }\n\n  private boolean dfs(char[][] board, String word, int i, int j, int s) {\n    if (i < 0 || i == board.length || j < 0 || j == board[0].length)\n      return false;\n    if (board[i][j] != word.charAt(s) || board[i][j] == '*')\n      return false;\n    if (s == word.length() - 1)\n      return true;\n\n    final char cache = board[i][j];\n    board[i][j] = '*';\n    final boolean isExist = dfs(board, word, i + 1, j, s + 1) ||\n                            dfs(board, word, i - 1, j, s + 1) ||\n                            dfs(board, word, i, j + 1, s + 1) ||\n                            dfs(board, word, i, j - 1, s + 1);\n    board[i][j] = cache;\n\n    return isExist;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool exist(vector<vector<char>>& board, string word) {\n    for (int i = 0; i < board.size(); ++i)\n      for (int j = 0; j < board[0].size(); ++j)\n        if (dfs(board, word, i, j, 0))\n          return true;\n    return false;\n  }\n\n private:\n  bool dfs(vector<vector<char>>& board, const string& word, int i, int j,\n           int s) {\n    if (i < 0 || i == board.size() || j < 0 || j == board[0].size())\n      return false;\n    if (board[i][j] != word[s] || board[i][j] == '*')\n      return false;\n    if (s == word.length() - 1)\n      return true;\n\n    const char cache = board[i][j];\n    board[i][j] = '*';\n    const bool isExist = dfs(board, word, i + 1, j, s + 1) ||\n                         dfs(board, word, i - 1, j, s + 1) ||\n                         dfs(board, word, i, j + 1, s + 1) ||\n                         dfs(board, word, i, j - 1, s + 1);\n    board[i][j] = cache;\n\n    return isExist;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/79.html",
    "category": "Algorithms",
    "acceptance_rate": 45.048985342505425,
    "topics": [
      "Array",
      "String",
      "Backtracking",
      "Depth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 16690,
    "dislikes": 711,
    "similar_questions": "[{\"title\": \"Word Search II\", \"titleSlug\": \"word-search-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"4.6M\", \"totalAcceptedRaw\": 2068697, \"totalSubmissionRaw\": 4592138, \"acRate\": \"45.0%\"}",
    "title_pt": "Busca de Palavras",
    "description_pt": "<p>Dado uma grade <code>m x n</code> de caracteres <code>board</code> e uma string <code>word</code>, retorne <code>true</code> <em>se</em> <code>word</code> <em>existir na grade</em>.</p>\n\n<p>A palavra pode ser construída a partir de letras de células adjacentes sequencialmente, onde células adjacentes são vizinhas horizontalmente ou verticalmente. A mesma célula de letra não pode ser usada mais de uma vez.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word2.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;ABCCED&quot;\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;SEE&quot;\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/word3.jpg\" style=\"width: 322px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;E&quot;],[&quot;S&quot;,&quot;F&quot;,&quot;C&quot;,&quot;S&quot;],[&quot;A&quot;,&quot;D&quot;,&quot;E&quot;,&quot;E&quot;]], word = &quot;ABCB&quot;\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n = board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 6</code></li>\n\t<li><code>1 &lt;= word.length &lt;= 15</code></li>\n\t<li><code>board</code> and <code>word</code> consists of only lowercase and uppercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você poderia usar poda de busca para tornar sua solução mais rápida com um <code>board</code> maior?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "80",
    "paidOnly": false,
    "title": "Remove Duplicates from Sorted Array II",
    "titleSlug": "remove-duplicates-from-sorted-array-ii",
    "url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii",
    "description_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/",
    "description": "<p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing order</strong>, remove some duplicates <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a> such that each unique element appears <strong>at most twice</strong>. The <strong>relative order</strong> of the elements should be kept the <strong>same</strong>.</p>\n\n<p>Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the <strong>first part</strong> of the array <code>nums</code>. More formally, if there are <code>k</code> elements after removing the duplicates, then the first <code>k</code> elements of <code>nums</code>&nbsp;should hold the final result. It does not matter what you leave beyond the first&nbsp;<code>k</code>&nbsp;elements.</p>\n\n<p>Return <code>k</code><em> after placing the final result in the first </em><code>k</code><em> slots of </em><code>nums</code>.</p>\n\n<p>Do <strong>not</strong> allocate extra space for another array. You must do this by <strong>modifying the input array <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a></strong> with O(1) extra memory.</p>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The judge will test your solution with the following code:</p>\n\n<pre>\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>If all assertions pass, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,1,2,2,3]\n<strong>Output:</strong> 5, nums = [1,1,2,2,3,_]\n<strong>Explanation:</strong> Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,0,1,1,1,1,2,3,3]\n<strong>Output:</strong> 7, nums = [0,0,1,1,2,3,3,_,_]\n<strong>Explanation:</strong> Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeDuplicates(self, nums: List[int]) -> int:\n    i = 0\n\n    for num in nums:\n      if i < 2 or num != nums[i - 2]:\n        nums[i] = num\n        i += 1\n\n    return i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int removeDuplicates(int[] nums) {\n    int i = 0;\n\n    for (final int num : nums)\n      if (i < 2 || num > nums[i - 2])\n        nums[i++] = num;\n\n    return i;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int removeDuplicates(vector<int>& nums) {\n    int i = 0;\n\n    for (const int num : nums)\n      if (i < 2 || num > nums[i - 2])\n        nums[i++] = num;\n\n    return i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/80.html",
    "category": "Algorithms",
    "acceptance_rate": 62.71870316417433,
    "topics": [
      "Array",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 7617,
    "dislikes": 1446,
    "similar_questions": "[{\"title\": \"Remove Duplicates from Sorted Array\", \"titleSlug\": \"remove-duplicates-from-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1537452, \"totalSubmissionRaw\": 2451352, \"acRate\": \"62.7%\"}",
    "title_pt": "Remover Duplicatas de Array Ordenado II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> ordenado em <strong>ordem não decrescente</strong>, remova algumas duplicatas <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\"><strong>in-place</strong></a> de forma que cada elemento único apareça <strong>no máximo duas vezes</strong>. A <strong>ordem relativa</strong> dos elementos deve ser mantida <strong>igual</strong>.</p>\n\n<p>Como é impossível alterar o comprimento do array em algumas linguagens, você deve, em vez disso, fazer com que o resultado seja colocado na <strong>primeira parte</strong> do array <code>nums</code>. Mais formalmente, se houver <code>k</code> elementos após remover as duplicatas, então os primeiros <code>k</code> elementos de <code>nums</code>&nbsp;devem conter o resultado final. Não importa o que você deixar além dos primeiros&nbsp;<code>k</code>&nbsp;elementos.</p>\n\n<p>Retorne <code>k</code><em> após colocar o resultado final nos primeiros </em><code>k</code><em> espaços de </em><code>nums</code>.</p>\n\n<p><strong>Não</strong> aloque espaço extra para outro array. Você deve fazer isso modificando o array de entrada <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> com O(1) de memória extra.</p>\n\n<p><strong>Juiz Personalizado:</strong></p>\n\n<p>O juiz testará sua solução com o seguinte código:</p>\n\n<pre>\nint[] nums = [...]; // Array de entrada\nint[] expectedNums = [...]; // A resposta esperada com o comprimento correto\n\nint k = removeDuplicates(nums); // Chama sua implementação\n\nassert k == expectedNums.length;\nfor (int i = 0; i &lt; k; i++) {\n    assert nums[i] == expectedNums[i];\n}\n</pre>\n\n<p>Se todas as asserções passarem, então sua solução será <strong>aceita</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,1,2,2,3]\n<strong>Saída:</strong> 5, nums = [1,1,2,2,3,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 5, com os primeiros cinco elementos de nums sendo 1, 1, 2, 2 e 3, respectivamente.\nNão importa o que você deixar além do k retornado (portanto eles são sublinhados).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,0,1,1,1,1,2,3,3]\n<strong>Saída:</strong> 7, nums = [0,0,1,1,2,3,3,_,_]\n<strong>Explicação:</strong> Sua função deve retornar k = 7, com os primeiros sete elementos de nums sendo 0, 0, 1, 1, 2, 3 e 3, respectivamente.\nNão importa o que você deixar além do k retornado (portanto eles são sublinhados).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> está ordenado em <strong>ordem não decrescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "81",
    "paidOnly": false,
    "title": "Search in Rotated Sorted Array II",
    "titleSlug": "search-in-rotated-sorted-array-ii",
    "url": "https://leetcode.com/problems/search-in-rotated-sorted-array-ii",
    "description_url": "https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/",
    "description": "<p>There is an integer array <code>nums</code> sorted in non-decreasing order (not necessarily with <strong>distinct</strong> values).</p>\n\n<p>Before being passed to your function, <code>nums</code> is <strong>rotated</strong> at an unknown pivot index <code>k</code> (<code>0 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,4,4,5,6,6,7]</code> might be rotated at pivot index <code>5</code> and become <code>[4,5,6,6,7,0,1,2,4,4]</code>.</p>\n\n<p>Given the array <code>nums</code> <strong>after</strong> the rotation and an integer <code>target</code>, return <code>true</code><em> if </em><code>target</code><em> is in </em><code>nums</code><em>, or </em><code>false</code><em> if it is not in </em><code>nums</code><em>.</em></p>\n\n<p>You must decrease the overall operation steps as much as possible.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [2,5,6,0,0,1,2], target = 0\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [2,5,6,0,0,1,2], target = 3\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is guaranteed to be rotated at some pivot.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> This problem is similar to&nbsp;<a href=\"/problems/search-in-rotated-sorted-array/description/\" target=\"_blank\">Search in Rotated Sorted Array</a>, but&nbsp;<code>nums</code> may contain <strong>duplicates</strong>. Would this affect the runtime complexity? How and why?</p>\n",
    "solution_url": "https://leetcode.com/problems/search-in-rotated-sorted-array-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def search(self, nums: List[int], target: int) -> bool:\n    l = 0\n    r = len(nums) - 1\n\n    while l <= r:\n      m = (l + r) // 2\n      if nums[m] == target:\n        return True\n      if nums[l] == nums[m] == nums[r]:\n        l += 1\n        r -= 1\n      elif nums[l] <= nums[m]:  # nums[l..m] are sorted\n        if nums[l] <= target < nums[m]:\n          r = m - 1\n        else:\n          l = m + 1\n      else:  # nums[m..n - 1] are sorted\n        if nums[m] < target <= nums[r]:\n          l = m + 1\n        else:\n          r = m - 1\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean search(int[] nums, int target) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l <= r) {\n      final int m = (l + r) / 2;\n      if (nums[m] == target)\n        return true;\n      if (nums[l] == nums[m] && nums[m] == nums[r]) {\n        ++l;\n        --r;\n      } else if (nums[l] <= nums[m]) { // nums[l..m] are sorted\n        if (nums[l] <= target && target < nums[m])\n          r = m - 1;\n        else\n          l = m + 1;\n      } else { // nums[m..n - 1] are sorted\n        if (nums[m] < target && target <= nums[r])\n          l = m + 1;\n        else\n          r = m - 1;\n      }\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool search(vector<int>& nums, int target) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l <= r) {\n      const int m = (l + r) / 2;\n      if (nums[m] == target)\n        return true;\n      if (nums[l] == nums[m] && nums[m] == nums[r]) {\n        ++l;\n        --r;\n      } else if (nums[l] <= nums[m]) {  // nums[l..m] are sorted\n        if (nums[l] <= target && target < nums[m])\n          r = m - 1;\n        else\n          l = m + 1;\n      } else {  // nums[m..n - 1] are sorted\n        if (nums[m] < target && target <= nums[r])\n          l = m + 1;\n        else\n          r = m - 1;\n      }\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/81.html",
    "category": "Algorithms",
    "acceptance_rate": 38.79111912214252,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 8989,
    "dislikes": 1087,
    "similar_questions": "[{\"title\": \"Search in Rotated Sorted Array\", \"titleSlug\": \"search-in-rotated-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"955.5K\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 955513, \"totalSubmissionRaw\": 2463234, \"acRate\": \"38.8%\"}",
    "title_pt": "Buscar em Array Ordenado Rotacionado II",
    "description_pt": "<p>Há um array inteiro <code>nums</code> ordenado em ordem não decrescente (não necessariamente com valores <strong>distintos</strong>).</p>\n\n<p>Antes de ser passado para sua função, <code>nums</code> é <strong>rotacionado</strong> em um índice pivô desconhecido <code>k</code> (<code>0 &lt;= k &lt; nums.length</code>) de modo que o array resultante é <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>indexado em 0</strong>). Por exemplo, <code>[0,1,2,4,4,4,5,6,6,7]</code> pode ser rotacionado no índice pivô <code>5</code> e se tornar <code>[4,5,6,6,7,0,1,2,4,4]</code>.</p>\n\n<p>Dado o array <code>nums</code> <strong>após</strong> a rotação e um inteiro <code>target</code>, retorne <code>true</code><em> se </em><code>target</code><em> estiver em </em><code>nums</code><em>, ou </em><code>false</code><em> se ele não estiver em </em><code>nums</code><em>.</em></p>\n\n<p>Você deve reduzir o número total de passos da operação o máximo possível.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [2,5,6,0,0,1,2], target = 0\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [2,5,6,0,0,1,2], target = 3\n<strong>Saída:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> tem garantia de ter sido rotacionado em algum pivô.</li>\n\t<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Este problema é semelhante a&nbsp;<a href=\"/problems/search-in-rotated-sorted-array/description/\" target=\"_blank\">Search in Rotated Sorted Array</a>, mas&nbsp;<code>nums</code> pode conter <strong>duplicatas</strong>. Isso afetaria a complexidade de tempo de execução? Como e por quê?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "82",
    "paidOnly": false,
    "title": "Remove Duplicates from Sorted List II",
    "titleSlug": "remove-duplicates-from-sorted-list-ii",
    "url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii",
    "description_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/",
    "description": "<p>Given the <code>head</code> of a sorted linked list, <em>delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list</em>. Return <em>the linked list <strong>sorted</strong> as well</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,3,4,4,5]\n<strong>Output:</strong> [1,2,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg\" style=\"width: 500px; height: 205px;\" />\n<pre>\n<strong>Input:</strong> head = [1,1,1,2,3]\n<strong>Output:</strong> [2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 300]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>The list is guaranteed to be <strong>sorted</strong> in ascending order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def deleteDuplicates(self, head: ListNode) -> ListNode:\n    dummy = ListNode(0, head)\n    prev = dummy\n\n    while head:\n      while head.next and head.val == head.next.val:\n        head = head.next\n      if prev.next == head:\n        prev = prev.next\n      else:\n        prev.next = head.next\n      head = head.next\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode deleteDuplicates(ListNode head) {\n    ListNode dummy = new ListNode(0, head);\n    ListNode prev = dummy;\n\n    while (head != null) {\n      while (head.next != null && head.val == head.next.val)\n        head = head.next;\n      if (prev.next == head)\n        prev = prev.next;\n      else\n        prev.next = head.next;\n      head = head.next;\n    }\n\n    return dummy.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* deleteDuplicates(ListNode* head) {\n    ListNode dummy(0, head);\n    ListNode* prev = &dummy;\n\n    while (head) {\n      while (head->next && head->val == head->next->val)\n        head = head->next;\n      if (prev->next == head)\n        prev = prev->next;\n      else\n        prev->next = head->next;\n      head = head->next;\n    }\n\n    return dummy.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/82.html",
    "category": "Algorithms",
    "acceptance_rate": 49.70581249141953,
    "topics": [
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 9213,
    "dislikes": 262,
    "similar_questions": "[{\"title\": \"Remove Duplicates from Sorted List\", \"titleSlug\": \"remove-duplicates-from-sorted-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Remove Duplicates From an Unsorted Linked List\", \"titleSlug\": \"remove-duplicates-from-an-unsorted-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"912.4K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 912378, \"totalSubmissionRaw\": 1835557, \"acRate\": \"49.7%\"}",
    "title_pt": "Remover Duplicatas de Lista Encadeada Ordenada II",
    "description_pt": "<p>Given the <code>head</code> of a sorted linked list, <em>delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list</em>. Return <em>the linked list <strong>sorted</strong> as well</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,3,4,4,5]\n<strong>Saída:</strong> [1,2,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg\" style=\"width: 500px; height: 205px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,1,1,2,3]\n<strong>Saída:</strong> [2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 300]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>A lista tem garantia de estar <strong>ordenada</strong> em ordem crescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "83",
    "paidOnly": false,
    "title": "Remove Duplicates from Sorted List",
    "titleSlug": "remove-duplicates-from-sorted-list",
    "url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list",
    "description_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/",
    "description": "<p>Given the <code>head</code> of a sorted linked list, <em>delete all duplicates such that each element appears only once</em>. Return <em>the linked list <strong>sorted</strong> as well</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/list1.jpg\" style=\"width: 302px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> head = [1,1,2]\n<strong>Output:</strong> [1,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/list2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,1,2,3,3]\n<strong>Output:</strong> [1,2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 300]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>The list is guaranteed to be <strong>sorted</strong> in ascending order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-duplicates-from-sorted-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def deleteDuplicates(self, head: ListNode) -> ListNode:\n    curr = head\n\n    while curr:\n      while curr.next and curr.val == curr.next.val:\n        curr.next = curr.next.next\n      curr = curr.next\n\n    return head",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode deleteDuplicates(ListNode head) {\n    ListNode curr = head;\n\n    while (curr != null) {\n      while (curr.next != null && curr.val == curr.next.val)\n        curr.next = curr.next.next;\n      curr = curr.next;\n    }\n\n    return head;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* deleteDuplicates(ListNode* head) {\n    ListNode* curr = head;\n\n    while (curr) {\n      while (curr->next && curr->val == curr->next->val)\n        curr->next = curr->next->next;\n      curr = curr->next;\n    }\n\n    return head;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/83.html",
    "category": "Algorithms",
    "acceptance_rate": 54.70971395237021,
    "topics": [
      "Linked List"
    ],
    "hints": [],
    "likes": 9223,
    "dislikes": 337,
    "similar_questions": "[{\"title\": \"Remove Duplicates from Sorted List II\", \"titleSlug\": \"remove-duplicates-from-sorted-list-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Remove Duplicates From an Unsorted Linked List\", \"titleSlug\": \"remove-duplicates-from-an-unsorted-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 1920699, \"totalSubmissionRaw\": 3510706, \"acRate\": \"54.7%\"}",
    "title_pt": "Remover Duplicatas de uma Lista Encadeada Ordenada",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada ordenada, <em>delete todas as duplicatas de modo que cada elemento apareça apenas uma vez</em>. Retorne <em>a lista encadeada <strong>ordenada</strong> também</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/list1.jpg\" style=\"width: 302px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,1,2]\n<strong>Saída:</strong> [1,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/list2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,1,2,3,3]\n<strong>Saída:</strong> [1,2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 300]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li>É garantido que a lista está <strong>ordenada</strong> em ordem crescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "84",
    "paidOnly": false,
    "title": "Largest Rectangle in Histogram",
    "titleSlug": "largest-rectangle-in-histogram",
    "url": "https://leetcode.com/problems/largest-rectangle-in-histogram",
    "description_url": "https://leetcode.com/problems/largest-rectangle-in-histogram/description/",
    "description": "<p>Given an array of integers <code>heights</code> representing the histogram&#39;s bar height where the width of each bar is <code>1</code>, return <em>the area of the largest rectangle in the histogram</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg\" style=\"width: 522px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> heights = [2,1,5,6,2,3]\n<strong>Output:</strong> 10\n<strong>Explanation:</strong> The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg\" style=\"width: 202px; height: 362px;\" />\n<pre>\n<strong>Input:</strong> heights = [2,4]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/largest-rectangle-in-histogram/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def largestRectangleArea(self, heights: List[int]) -> int:\n    ans = 0\n    stack = []\n\n    for i in range(len(heights) + 1):\n      while stack and (i == len(heights) or heights[stack[-1]] > heights[i]):\n        h = heights[stack.pop()]\n        w = i - stack[-1] - 1 if stack else i\n        ans = max(ans, h * w)\n      stack.append(i)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int largestRectangleArea(int[] heights) {\n    int ans = 0;\n    Deque<Integer> stack = new ArrayDeque<>();\n\n    for (int i = 0; i <= heights.length; ++i) {\n      while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) {\n        final int h = heights[stack.pop()];\n        final int w = stack.isEmpty() ? i : i - stack.peek() - 1;\n        ans = Math.max(ans, h * w);\n      }\n      stack.push(i);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int largestRectangleArea(vector<int>& heights) {\n    int ans = 0;\n    stack<int> stack;\n\n    for (int i = 0; i <= heights.size(); ++i) {\n      while (!stack.empty() &&\n             (i == heights.size() || heights[stack.top()] > heights[i])) {\n        const int h = heights[stack.top()];\n        stack.pop();\n        const int w = stack.empty() ? i : i - stack.top() - 1;\n        ans = max(ans, h * w);\n      }\n      stack.push(i);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/84.html",
    "category": "Algorithms",
    "acceptance_rate": 47.09459099237627,
    "topics": [
      "Array",
      "Stack",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 18216,
    "dislikes": 325,
    "similar_questions": "[{\"title\": \"Maximal Rectangle\", \"titleSlug\": \"maximal-rectangle\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Score of a Good Subarray\", \"titleSlug\": \"maximum-score-of-a-good-subarray\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1174856, \"totalSubmissionRaw\": 2494676, \"acRate\": \"47.1%\"}",
    "title_pt": "Maior Retângulo em um Histograma",
    "description_pt": "<p>Dado um array de inteiros <code>heights</code> representando a altura das barras do histograma, em que a largura de cada barra é <code>1</code>, retorne <em>a área do maior retângulo no histograma</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg\" style=\"width: 522px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> heights = [2,1,5,6,2,3]\n<strong>Saída:</strong> 10\n<strong>Explicação:</strong> O histograma acima tem largura de cada barra igual a 1.\nO maior retângulo é mostrado na área vermelha, que tem área = 10 unidades.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg\" style=\"width: 202px; height: 362px;\" />\n<pre>\n<strong>Entrada:</strong> heights = [2,4]\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= heights[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "85",
    "paidOnly": false,
    "title": "Maximal Rectangle",
    "titleSlug": "maximal-rectangle",
    "url": "https://leetcode.com/problems/maximal-rectangle",
    "description_url": "https://leetcode.com/problems/maximal-rectangle/description/",
    "description": "<p>Given a <code>rows x cols</code>&nbsp;binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, find the largest rectangle containing only <code>1</code>&#39;s and return <em>its area</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg\" style=\"width: 402px; height: 322px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The maximal rectangle is shown in the above picture.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[&quot;0&quot;]]\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[&quot;1&quot;]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>rows == matrix.length</code></li>\n\t<li><code>cols == matrix[i].length</code></li>\n\t<li><code>1 &lt;= row, cols &lt;= 200</code></li>\n\t<li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximal-rectangle/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maximalRectangle(self, matrix: List[List[str]]) -> int:\n    if not matrix:\n      return 0\n\n    ans = 0\n    hist = [0] * len(matrix[0])\n\n    def largestRectangleArea(heights: List[int]) -> int:\n      ans = 0\n      stack = []\n\n      for i in range(len(heights) + 1):\n        while stack and (i == len(heights) or heights[stack[-1]] > heights[i]):\n          h = heights[stack.pop()]\n          w = i - stack[-1] - 1 if stack else i\n          ans = max(ans, h * w)\n        stack.append(i)\n\n      return ans\n\n    for row in matrix:\n      for i, num in enumerate(row):\n        hist[i] = 0 if num == '0' else hist[i] + 1\n      ans = max(ans, largestRectangleArea(hist))\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maximalRectangle(char[][] matrix) {\n    if (matrix.length == 0)\n      return 0;\n\n    int ans = 0;\n    int[] hist = new int[matrix[0].length];\n\n    for (char[] row : matrix) {\n      for (int i = 0; i < row.length; ++i)\n        hist[i] = row[i] == '0' ? 0 : hist[i] + 1;\n      ans = Math.max(ans, largestRectangleArea(hist));\n    }\n\n    return ans;\n  }\n\n  private int largestRectangleArea(int[] heights) {\n    int ans = 0;\n    Deque<Integer> stack = new ArrayDeque<>();\n\n    for (int i = 0; i <= heights.length; ++i) {\n      while (!stack.isEmpty() && (i == heights.length || heights[stack.peek()] > heights[i])) {\n        final int h = heights[stack.pop()];\n        final int w = stack.isEmpty() ? i : i - stack.peek() - 1;\n        ans = Math.max(ans, h * w);\n      }\n      stack.push(i);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maximalRectangle(vector<vector<char>>& matrix) {\n    if (matrix.empty())\n      return 0;\n\n    int ans = 0;\n    vector<int> hist(matrix[0].size());\n\n    for (const vector<char>& row : matrix) {\n      for (int i = 0; i < row.size(); ++i)\n        hist[i] = row[i] == '0' ? 0 : hist[i] + 1;\n      ans = max(ans, largestRectangleArea(hist));\n    }\n\n    return ans;\n  }\n\n private:\n  int largestRectangleArea(const vector<int>& heights) {\n    int ans = 0;\n    stack<int> stack;\n\n    for (int i = 0; i <= heights.size(); ++i) {\n      while (!stack.empty() &&\n             (i == heights.size() || heights[stack.top()] > heights[i])) {\n        const int h = heights[stack.top()];\n        stack.pop();\n        const int w = stack.empty() ? i : i - stack.top() - 1;\n        ans = max(ans, h * w);\n      }\n      stack.push(i);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/85.html",
    "category": "Algorithms",
    "acceptance_rate": 53.3782376350199,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Stack",
      "Matrix",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 11090,
    "dislikes": 199,
    "similar_questions": "[{\"title\": \"Largest Rectangle in Histogram\", \"titleSlug\": \"largest-rectangle-in-histogram\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximal Square\", \"titleSlug\": \"maximal-square\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Sorted Submatrices With Maximum Element at Most K\", \"titleSlug\": \"find-sorted-submatrices-with-maximum-element-at-most-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"586.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 586825, \"totalSubmissionRaw\": 1099370, \"acRate\": \"53.4%\"}",
    "title_pt": "Retângulo Máximo",
    "description_pt": "<p>Dada uma <code>rows x cols</code>&nbsp;<code>matrix</code> binária preenchida com <code>0</code>&#39;s e <code>1</code>&#39;s, encontre o maior retângulo contendo apenas <code>1</code>&#39;s e retorne <em>sua área</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/maximal.jpg\" style=\"width: 402px; height: 322px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O retângulo máximo é mostrado na imagem acima.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;0&quot;]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;1&quot;]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>rows == matrix.length</code></li>\n\t<li><code>cols == matrix[i].length</code></li>\n\t<li><code>1 &lt;= row, cols &lt;= 200</code></li>\n\t<li><code>matrix[i][j]</code> é <code>&#39;0&#39;</code> ou <code>&#39;1&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "86",
    "paidOnly": false,
    "title": "Partition List",
    "titleSlug": "partition-list",
    "url": "https://leetcode.com/problems/partition-list",
    "description_url": "https://leetcode.com/problems/partition-list/description/",
    "description": "<p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p>\n\n<p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/partition.jpg\" style=\"width: 662px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,4,3,2,5,2], x = 3\n<strong>Output:</strong> [1,2,2,4,3,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [2,1], x = 2\n<strong>Output:</strong> [1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-200 &lt;= x &lt;= 200</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/partition-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def partition(self, head: ListNode, x: int) -> ListNode:\n    beforeHead = ListNode(0)\n    afterHead = ListNode(0)\n    before = beforeHead\n    after = afterHead\n\n    while head:\n      if head.val < x:\n        before.next = head\n        before = head\n      else:\n        after.next = head\n        after = head\n      head = head.next\n\n    after.next = None\n    before.next = afterHead.next\n\n    return beforeHead.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode partition(ListNode head, int x) {\n    ListNode beforeHead = new ListNode(0);\n    ListNode afterHead = new ListNode(0);\n    ListNode before = beforeHead;\n    ListNode after = afterHead;\n\n    for (; head != null; head = head.next)\n      if (head.val < x) {\n        before.next = head;\n        before = head;\n      } else {\n        after.next = head;\n        after = head;\n      }\n\n    after.next = null;\n    before.next = afterHead.next;\n\n    return beforeHead.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* partition(ListNode* head, int x) {\n    ListNode beforeHead(0);\n    ListNode afterHead(0);\n    ListNode* before = &beforeHead;\n    ListNode* after = &afterHead;\n\n    for (; head; head = head->next)\n      if (head->val < x) {\n        before->next = head;\n        before = head;\n      } else {\n        after->next = head;\n        after = head;\n      }\n\n    after->next = nullptr;\n    before->next = afterHead.next;\n\n    return beforeHead.next;\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/86.html",
    "category": "Algorithms",
    "acceptance_rate": 58.78315404852157,
    "topics": [
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 7677,
    "dislikes": 936,
    "similar_questions": "[{\"title\": \"Partition Array According to Given Pivot\", \"titleSlug\": \"partition-array-according-to-given-pivot\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"761.3K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 761270, \"totalSubmissionRaw\": 1295045, \"acRate\": \"58.8%\"}",
    "title_pt": "Particionar Lista",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada e um valor <code>x</code>, particione-a de modo que todos os nós <strong>menores que</strong> <code>x</code> venham antes dos nós <strong>maiores ou iguais</strong> a <code>x</code>.</p>\n\n<p>Você deve <strong>preservar</strong> a ordem relativa original dos nós em cada uma das duas partições.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/04/partition.jpg\" style=\"width: 662px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,4,3,2,5,2], x = 3\n<strong>Saída:</strong> [1,2,2,4,3,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [2,1], x = 2\n<strong>Saída:</strong> [1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 200]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-200 &lt;= x &lt;= 200</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "87",
    "paidOnly": false,
    "title": "Scramble String",
    "titleSlug": "scramble-string",
    "url": "https://leetcode.com/problems/scramble-string",
    "description_url": "https://leetcode.com/problems/scramble-string/description/",
    "description": "<p>We can scramble a string s to get a string t using the following algorithm:</p>\n\n<ol>\n\t<li>If the length of the string is 1, stop.</li>\n\t<li>If the length of the string is &gt; 1, do the following:\n\t<ul>\n\t\t<li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li>\n\t\t<li><strong>Randomly</strong>&nbsp;decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li>\n\t\t<li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li>\n\t</ul>\n\t</li>\n</ol>\n\n<p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong>, return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> One possible scenario applied on s1 is:\n&quot;great&quot; --&gt; &quot;gr/eat&quot; // divide at random index.\n&quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // random decision is not to swap the two substrings and keep them in order.\n&quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // apply the same algorithm recursively on both substrings. divide at random index each of them.\n&quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // random decision was to swap the first substring and to keep the second substring in the same order.\n&quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // again apply the algorithm recursively, divide &quot;at&quot; to &quot;a/t&quot;.\n&quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // random decision is to keep both substrings in the same order.\nThe algorithm stops now, and the result string is &quot;rgeat&quot; which is s2.\nAs one possible scenario led s1 to be scrambled to s2, we return true.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot;\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot;\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>s1.length == s2.length</code></li>\n\t<li><code>1 &lt;= s1.length &lt;= 30</code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/scramble-string/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach: Dynamic Programming\n\n#### Intuition\n\nWe have a recursive definition of scrambling a string `s`. First, we divide `s` into `x` and `y`. Then we either keep `s` as `x + y` or swap them and get `y + x`. After that, we scramble `x` and `y` independently. Let `x'` denote the scrambled `x` and `y'` denote the scrambled `y`. `s` will eventually become `x' + y'` or `y' + x'`.\n\n![split](../Figures/87/diagram2.drawio.png)\n\nHow do we check whether a given string `t` is a scrambled string of `s`? First, we choose an index and cut `s` into `x` and `y` (`s = x + y`). Then, we see if we can cut `t` into `x'` and `y'` (`t = x' + y'` if we do not swap or `t = y' + x'` if we do). Since verifying that `x'` is a scrambled `x` and `y'` is scrambled `y` are smaller subproblems, we will solve the problem using dynamic programming.\n\nWe have two strings `s1` and `s2`.\n\nFor each given dp state, we need 3 variables: `length`, `i`, and `j`.\n\nEach state will focus on two substrings. The first one will be a substring of `s1`, starting at index `i` with length equal to `length` - let's call this substring `s`. The second one will be a substring of `s2`, starting at index `j` with `length` - let's call this substring `t`.\n\nLet `dp[length][i][j]` be a boolean representing whether `t` is a scrambled version of `s`.\n\nThe base case, as defined by the problem is when `length = 1`. Here we do not have to split strings into smaller ones, so we can easily compare the corresponding characters: `dp[1][i][j]` is `true` when `s1[i]` equals `s2[j]`, and `false` otherwise.\n\nNow we need to write down the transitions of `dp`. We will use the following image as an example during the explanations.\n\n![split](../Figures/87/diagram.drawio.png)\n\nAt each state, we need to perform a split on `s1`. We will consider all possible splits. If we are currently considering a substring with a length of `length`, then we could perform a split at any index `newLength`, where `0 < newLength < length`. (Here, `newLength` represents the length of the left string after the split). A split gives us two new strings:\n\n- A substring of `s1` starting at index `i` and ending with index `i + newLength - 1`. This string has a length of `newLength` (Blue in the picture)\n\n- A substring of `s1` starting at index `i + newLength` and ending at index `i + length - 1`. This string has a length of `length - newLength`. (Yellow in the picture)\n\nFor each split, we have two cases:\n\n* Do not swap the blue and yellow parts. The corresponding substrings of `s2` must be scrambled versions of the substrings we just created by splitting `s1`. This means both `dp[newLength][i][j]` (representing the blue parts) and `dp[length - newLength][i + newLength][j + newLength]` (representing the yellow parts) must be true.\n* Swap the blue and yellow parts. As you can see in the image, this misaligns the blue and yellow parts between `s1` and `s2`, but we still need the parts to match (we still need the blue part of `s1` to be a scrambled version of the blue part of `s2`, same with the yellow part). What are the new starting indices? For blue, it's `s1` starting with `i` and `s2` starting with `j + length - newLength`. For yellow, it's `s1` starting with `i + newLength` and `s2` starting with `j`. Thus, we need both `dp[newLength][i][j+length-newLength]` and `dp[length-newLength][i+newLength][j]` to be `true`.\n\nNow we can formally write down the transitions. For `length > 1`, `dp[length][i][j]` is `true` if and only if for at least one `newLength` where `0 < newLength < length`:\n\n`(dp[newLength][i][j] && dp[length-newLength][i+newLength][j+newLength]) || (dp[newLength][i][j+length-newLength] && dp[length-newLength][i+newLength][j])` is `true`.\n\nLet `n` denote the length of the input strings. The answer to the problem is `dp[n][0][0]`, as starting at index `0` with length `n` is considering the entire input string.\n\n#### Algorithm\n\n1. Iterate `i` from `0` to `n-1`.\n\t* Iterate `j` from `0` to `n-1`.\n\t\t* Set `dp[1][i][j]` to the boolean value of `s1[i] == s2[j]`. (The base case of the DP).\n2. Iterate `length` from `2` to `n`.\n\t* Iterate `i` from `0` to `n + 1 - length`.\n\t\t* Iterate `j` from `0` to `n + 1 - length`.\n\t\t\t* Iterate `newLength` from `1` to `length - 1`.\n\t\t\t\t* If `dp[newLength][i][j] && dp[length-newLength][i+newLength][j+newLength]) || (dp[newLength][i][j+l-newLength] && dp[l-newLength][i+newLength][j]` is `true`, set `dp[length][i][j]` to `true`.\n3. Return `dp[n][0][0]`.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/XJvjmW6h/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"XJvjmW6h\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time complexity: $O(n^4)$.\n\nWe have four nested for loops (for `length`, `i`, `j`, `newLength`), each doing $O(n)$ iterations.\n\n* Space complexity: $O(n^3)$.\n\nWe store the matrix `dp[n+1][n][n]` for dynamic programming.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isScramble(self, s1: str, s2: str) -> bool:\n    if s1 == s2:\n      return True\n    if len(s1) != len(s2):\n      return False\n    if Counter(s1) != Counter(s2):\n      return False\n\n    for i in range(1, len(s1)):\n      if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]):\n        return True\n      if self.isScramble(s1[:i], s2[len(s2) - i:]) and self.isScramble(s1[i:], s2[:len(s2) - i]):\n        return True\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isScramble(String s1, String s2) {\n    if (s1.equals(s2))\n      return true;\n    if (s1.length() != s2.length())\n      return false;\n    final String hashedKey = s1 + \"+\" + s2;\n    if (memo.containsKey(hashedKey))\n      return memo.get(hashedKey);\n\n    int[] count = new int[128];\n\n    for (int i = 0; i < s1.length(); ++i) {\n      ++count[s1.charAt(i)];\n      --count[s2.charAt(i)];\n    }\n\n    for (final int c : count)\n      if (c != 0) {\n        memo.put(hashedKey, false);\n        return false;\n      }\n\n    for (int i = 1; i < s1.length(); ++i) {\n      if (isScramble(s1.substring(0, i), s2.substring(0, i)) &&\n          isScramble(s1.substring(i), s2.substring(i))) {\n        memo.put(hashedKey, true);\n        return true;\n      }\n      if (isScramble(s1.substring(0, i), s2.substring(s2.length() - i)) &&\n          isScramble(s1.substring(i), s2.substring(0, s2.length() - i))) {\n        memo.put(hashedKey, true);\n        return true;\n      }\n    }\n\n    memo.put(hashedKey, false);\n    return false;\n  }\n\n  private Map<String, Boolean> memo = new HashMap<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isScramble(string s1, string s2) {\n    if (s1 == s2)\n      return true;\n    if (s1.length() != s2.length())\n      return false;\n    const string hashedKey = s1 + '+' + s2;\n    if (memo.count(hashedKey))\n      return memo[hashedKey];\n\n    vector<int> count(128);\n\n    for (int i = 0; i < s1.length(); ++i) {\n      ++count[s1[i]];\n      --count[s2[i]];\n    }\n\n    if (any_of(begin(count), end(count), [](int c) { return c != 0; }))\n      return memo[hashedKey] = false;\n\n    for (int i = 1; i < s1.length(); ++i) {\n      if (isScramble(s1.substr(0, i), s2.substr(0, i)) &&\n          isScramble(s1.substr(i), s2.substr(i)))\n        return memo[hashedKey] = true;\n      if (isScramble(s1.substr(0, i), s2.substr(s2.length() - i)) &&\n          isScramble(s1.substr(i), s2.substr(0, s2.length() - i)))\n        return memo[hashedKey] = true;\n    }\n\n    return memo[hashedKey] = false;\n  }\n\n private:\n  unordered_map<string, bool> memo;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/87.html",
    "category": "Algorithms",
    "acceptance_rate": 42.03945931746901,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 3462,
    "dislikes": 1290,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"265.7K\", \"totalSubmission\": \"631.9K\", \"totalAcceptedRaw\": 265662, \"totalSubmissionRaw\": 631936, \"acRate\": \"42.0%\"}",
    "title_pt": "String Embaralhada",
    "description_pt": "<p>Nós podemos embaralhar uma string s para obter uma string t usando o seguinte algoritmo:</p>\n\n<ol>\n\t<li>Se o comprimento da string for 1, pare.</li>\n\t<li>Se o comprimento da string for &gt; 1, faça o seguinte:\n\t<ul>\n\t\t<li>Divida a string em duas substrings não vazias em um índice aleatório; ou seja, se a string for <code>s</code>, divida-a em <code>x</code> e <code>y</code>, onde <code>s = x + y</code>.</li>\n\t\t<li><strong>Aleatoriamente</strong>&nbsp;decida trocar as duas substrings ou mantê-las na mesma ordem. Ou seja, após esta etapa, <code>s</code> pode se tornar <code>s = x + y</code> ou <code>s = y + x</code>.</li>\n\t\t<li>Aplique recursivamente o passo 1 em cada uma das duas substrings <code>x</code> e <code>y</code>.</li>\n\t</ul>\n\t</li>\n</ol>\n\n<p>Dadas duas strings <code>s1</code> e <code>s2</code> de <strong>mesmo comprimento</strong>, retorne <code>true</code> se <code>s2</code> for uma string embaralhada de <code>s1</code>; caso contrário, retorne <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;great&quot;, s2 = &quot;rgeat&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Um cenário possível aplicado em s1 é:\n&quot;great&quot; --&gt; &quot;gr/eat&quot; // dividir em um índice aleatório.\n&quot;gr/eat&quot; --&gt; &quot;gr/eat&quot; // a decisão aleatória é não trocar as duas substrings e mantê-las em ordem.\n&quot;gr/eat&quot; --&gt; &quot;g/r / e/at&quot; // aplique o mesmo algoritmo recursivamente em ambas as substrings. divida cada uma delas em um índice aleatório.\n&quot;g/r / e/at&quot; --&gt; &quot;r/g / e/at&quot; // a decisão aleatória foi trocar a primeira substring e manter a segunda substring na mesma ordem.\n&quot;r/g / e/at&quot; --&gt; &quot;r/g / e/ a/t&quot; // novamente aplique o algoritmo recursivamente, dividindo &quot;at&quot; em &quot;a/t&quot;.\n&quot;r/g / e/ a/t&quot; --&gt; &quot;r/g / e/ a/t&quot; // a decisão aleatória é manter ambas as substrings na mesma ordem.\nO algoritmo para agora, e a string resultante é &quot;rgeat&quot;, que é s2.\nComo um cenário possível levou s1 a ser embaralhada até s2, retornamos true.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot;\n<strong>Saída:</strong> false\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;a&quot;, s2 = &quot;a&quot;\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>s1.length == s2.length</code></li>\n\t<li><code>1 &lt;= s1.length &lt;= 30</code></li>\n\t<li><code>s1</code> e <code>s2</code> consistem em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "88",
    "paidOnly": false,
    "title": "Merge Sorted Array",
    "titleSlug": "merge-sorted-array",
    "url": "https://leetcode.com/problems/merge-sorted-array",
    "description_url": "https://leetcode.com/problems/merge-sorted-array/description/",
    "description": "<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code>, sorted in <strong>non-decreasing order</strong>, and two integers <code>m</code> and <code>n</code>, representing the number of elements in <code>nums1</code> and <code>nums2</code> respectively.</p>\n\n<p><strong>Merge</strong> <code>nums1</code> and <code>nums2</code> into a single array sorted in <strong>non-decreasing order</strong>.</p>\n\n<p>The final sorted array should not be returned by the function, but instead be <em>stored inside the array </em><code>nums1</code>. To accommodate this, <code>nums1</code> has a length of <code>m + n</code>, where the first <code>m</code> elements denote the elements that should be merged, and the last <code>n</code> elements are set to <code>0</code> and should be ignored. <code>nums2</code> has a length of <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\n<strong>Output:</strong> [1,2,2,3,5,6]\n<strong>Explanation:</strong> The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6] with the underlined elements coming from nums1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1], m = 1, nums2 = [], n = 0\n<strong>Output:</strong> [1]\n<strong>Explanation:</strong> The arrays we are merging are [1] and [].\nThe result of the merge is [1].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1\n<strong>Output:</strong> [1]\n<strong>Explanation:</strong> The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>nums1.length == m + n</code></li>\n\t<li><code>nums2.length == n</code></li>\n\t<li><code>0 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>1 &lt;= m + n &lt;= 200</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up: </strong>Can you come up with an algorithm that runs in <code>O(m + n)</code> time?</p>\n",
    "solution_url": "https://leetcode.com/problems/merge-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n    i = m - 1      # nums1's index (actual nums)\n    j = n - 1      # nums2's index\n    k = m + n - 1  # nums1's index (next filled position)\n\n    while j >= 0:\n      if i >= 0 and nums1[i] > nums2[j]:\n        nums1[k] = nums1[i]\n        k -= 1\n        i -= 1\n      else:\n        nums1[k] = nums2[j]\n        k -= 1\n        j -= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void merge(int[] nums1, int m, int[] nums2, int n) {\n    int i = m - 1;     // nums1's index (actual nums)\n    int j = n - 1;     // nums2's index\n    int k = m + n - 1; // nums1's index (next filled position)\n\n    while (j >= 0)\n      if (i >= 0 && nums1[i] > nums2[j])\n        nums1[k--] = nums1[i--];\n      else\n        nums1[k--] = nums2[j--];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n    int i = m - 1;      // nums1's index (actual nums)\n    int j = n - 1;      // nums2's index\n    int k = m + n - 1;  // nums1's index (next filled position)\n\n    while (j >= 0)\n      if (i >= 0 && nums1[i] > nums2[j])\n        nums1[k--] = nums1[i--];\n      else\n        nums1[k--] = nums2[j--];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/88.html",
    "category": "Algorithms",
    "acceptance_rate": 52.704395453856336,
    "topics": [
      "Array",
      "Two Pointers",
      "Sorting"
    ],
    "hints": [
      "You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution?",
      "If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution."
    ],
    "likes": 16918,
    "dislikes": 2345,
    "similar_questions": "[{\"title\": \"Merge Two Sorted Lists\", \"titleSlug\": \"merge-two-sorted-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Squares of a Sorted Array\", \"titleSlug\": \"squares-of-a-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Interval List Intersections\", \"titleSlug\": \"interval-list-intersections\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Take K of Each Character From Left and Right\", \"titleSlug\": \"take-k-of-each-character-from-left-and-right\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.5M\", \"totalSubmission\": \"8.6M\", \"totalAcceptedRaw\": 4543652, \"totalSubmissionRaw\": 8621012, \"acRate\": \"52.7%\"}",
    "title_pt": "Mesclar Array Ordenado",
    "description_pt": "<p>Você recebe dois arrays de inteiros <code>nums1</code> e <code>nums2</code>, ordenados em <strong>ordem não decrescente</strong>, e dois inteiros <code>m</code> e <code>n</code>, representando o número de elementos em <code>nums1</code> e <code>nums2</code> respectivamente.</p>\n\n<p><strong>Mescle</strong> <code>nums1</code> e <code>nums2</code> em um único array ordenado em <strong>ordem não decrescente</strong>.</p>\n\n<p>O array final ordenado não deve ser retornado pela função, mas sim <em>armazenado dentro do array </em><code>nums1</code>. Para acomodar isso, <code>nums1</code> tem comprimento de <code>m + n</code>, em que os primeiros <code>m</code> elementos denotam os elementos que devem ser mesclados, e os últimos <code>n</code> elementos são definidos como <code>0</code> e devem ser ignorados. <code>nums2</code> tem comprimento de <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\n<strong>Saída:</strong> [1,2,2,3,5,6]\n<strong>Explicação:</strong> Os arrays que estamos mesclando são [1,2,3] e [2,5,6].\nO resultado da mesclagem é [<u>1</u>,<u>2</u>,2,<u>3</u>,5,6], com os elementos sublinhados vindo de nums1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1], m = 1, nums2 = [], n = 0\n<strong>Saída:</strong> [1]\n<strong>Explicação:</strong> Os arrays que estamos mesclando são [1] e [].\nO resultado da mesclagem é [1].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [0], m = 0, nums2 = [1], n = 1\n<strong>Saída:</strong> [1]\n<strong>Explicação:</strong> Os arrays que estamos mesclando são [] e [1].\nO resultado da mesclagem é [1].\nObserve que, como m = 0, não há elementos em nums1. O 0 está ali apenas para garantir que o resultado da mesclagem caiba em nums1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>nums1.length == m + n</code></li>\n\t<li><code>nums2.length == n</code></li>\n\t<li><code>0 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>1 &lt;= m + n &lt;= 200</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[j] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra: </strong>Você consegue criar um algoritmo que execute em tempo <code>O(m + n)</code>?</p>",
    "hints_pt": [
      "Dica 1: Você pode resolver este problema facilmente se simplesmente pensar em dois elementos por vez, em vez de dois arrays. Sabemos que cada um dos arrays individuais está ordenado. O que não sabemos é como eles se entrelaçarão. Podemos tomar uma decisão local e chegar a uma solução ótima?",
      "Dica 2: Se você simplesmente considerar um elemento de cada vez dos dois arrays e tomar uma decisão e prosseguir de acordo, você chegará à solução ótima."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "89",
    "paidOnly": false,
    "title": "Gray Code",
    "titleSlug": "gray-code",
    "url": "https://leetcode.com/problems/gray-code",
    "description_url": "https://leetcode.com/problems/gray-code/description/",
    "description": "<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p>\n\n<ul>\n\t<li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li>\n\t<li>The first integer is <code>0</code>,</li>\n\t<li>An integer appears <strong>no more than once</strong> in the sequence,</li>\n\t<li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li>\n\t<li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li>\n</ul>\n\n<p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> [0,1,3,2]\n<strong>Explanation:</strong>\nThe binary representation of [0,1,3,2] is [00,01,11,10].\n- 0<u>0</u> and 0<u>1</u> differ by one bit\n- <u>0</u>1 and <u>1</u>1 differ by one bit\n- 1<u>1</u> and 1<u>0</u> differ by one bit\n- <u>1</u>0 and <u>0</u>0 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n- <u>0</u>0 and <u>1</u>0 differ by one bit\n- 1<u>0</u> and 1<u>1</u> differ by one bit\n- <u>1</u>1 and <u>0</u>1 differ by one bit\n- 0<u>1</u> and 0<u>0</u> differ by one bit\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> [0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 16</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/gray-code/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def grayCode(self, n: int) -> List[int]:\n    ans = [0]\n\n    for i in range(n):\n      for j in reversed(range(len(ans))):\n        ans.append(ans[j] | 1 << i)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> grayCode(int n) {\n    List<Integer> ans = new ArrayList<>();\n    ans.add(0);\n\n    for (int i = 0; i < n; ++i)\n      for (int j = ans.size() - 1; j >= 0; --j)\n        ans.add(ans.get(j) | 1 << i);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> grayCode(int n) {\n    vector<int> ans{0};\n\n    for (int i = 0; i < n; ++i)\n      for (int j = ans.size() - 1; j >= 0; --j)\n        ans.push_back(ans[j] | 1 << i);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/89.html",
    "category": "Algorithms",
    "acceptance_rate": 61.65189276046008,
    "topics": [
      "Math",
      "Backtracking",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 2369,
    "dislikes": 2792,
    "similar_questions": "[{\"title\": \"1-bit and 2-bit Characters\", \"titleSlug\": \"1-bit-and-2-bit-characters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"346.8K\", \"totalSubmission\": \"562.6K\", \"totalAcceptedRaw\": 346846, \"totalSubmissionRaw\": 562589, \"acRate\": \"61.7%\"}",
    "title_pt": "Código Cinza",
    "description_pt": "<p>Uma <strong>sequência de código cinza de n bits</strong> é uma sequência de <code>2<sup>n</sup></code> inteiros em que:</p>\n\n<ul>\n\t<li>Cada inteiro está no intervalo <strong>inclusivo</strong> <code>[0, 2<sup>n</sup> - 1]</code>,</li>\n\t<li>O primeiro inteiro é <code>0</code>,</li>\n\t<li>Um inteiro aparece <strong>no máximo uma vez</strong> na sequência,</li>\n\t<li>A representação binária de cada par de inteiros <strong>adjacentes</strong> difere em <strong>exatamente um bit</strong>, e</li>\n\t<li>A representação binária do <strong>primeiro</strong> e do <strong>último</strong> inteiros difere em <strong>exatamente um bit</strong>.</li>\n</ul>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>qualquer <strong>sequência de código cinza de n bits</strong> válida</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> [0,1,3,2]\n<strong>Explicação:</strong>\nA representação binária de [0,1,3,2] é [00,01,11,10].\n- 0<u>0</u> e 0<u>1</u> diferem por um bit\n- <u>0</u>1 e <u>1</u>1 diferem por um bit\n- 1<u>1</u> e 1<u>0</u> diferem por um bit\n- <u>1</u>0 e <u>0</u>0 diferem por um bit\n[0,2,3,1] também é uma sequência de código cinza válida, cuja representação binária é [00,10,11,01].\n- <u>0</u>0 e <u>1</u>0 diferem por um bit\n- 1<u>0</u> e 1<u>1</u> diferem por um bit\n- <u>1</u>1 e <u>0</u>1 diferem por um bit\n- 0<u>1</u> e 0<u>0</u> diferem por um bit\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [0,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 16</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "90",
    "paidOnly": false,
    "title": "Subsets II",
    "titleSlug": "subsets-ii",
    "url": "https://leetcode.com/problems/subsets-ii",
    "description_url": "https://leetcode.com/problems/subsets-ii/description/",
    "description": "<p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible</em> <span data-keyword=\"subset\"><em>subsets</em></span><em> (the power set)</em>.</p>\n\n<p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,2]\n<strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [0]\n<strong>Output:</strong> [[],[0]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/subsets-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, path: List[int]) -> None:\n      ans.append(path)\n      if s == len(nums):\n        return\n\n      for i in range(s, len(nums)):\n        if i > s and nums[i] == nums[i - 1]:\n          continue\n        dfs(i + 1, path + [nums[i]])\n\n    nums.sort()\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> subsetsWithDup(int[] nums) {\n    List<List<Integer>> ans = new ArrayList<>();\n    Arrays.sort(nums);\n    dfs(nums, 0, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int[] nums, int s, List<Integer> path, List<List<Integer>> ans) {\n    ans.add(new ArrayList<>(path));\n\n    for (int i = s; i < nums.length; ++i) {\n      if (i > s && nums[i] == nums[i - 1])\n        continue;\n      path.add(nums[i]);\n      dfs(nums, i + 1, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> subsetsWithDup(vector<int>& nums) {\n    vector<vector<int>> ans;\n    sort(begin(nums), end(nums));\n    dfs(nums, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& nums, int s, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    ans.push_back(path);\n\n    for (int i = s; i < nums.size(); ++i) {\n      if (i > s && nums[i] == nums[i - 1])\n        continue;\n      path.push_back(nums[i]);\n      dfs(nums, i + 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/90.html",
    "category": "Algorithms",
    "acceptance_rate": 59.2891765742931,
    "topics": [
      "Array",
      "Backtracking",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 10281,
    "dislikes": 363,
    "similar_questions": "[{\"title\": \"Subsets\", \"titleSlug\": \"subsets\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Array Given Subset Sums\", \"titleSlug\": \"find-array-given-subset-sums\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1187784, \"totalSubmissionRaw\": 2003380, \"acRate\": \"59.3%\"}",
    "title_pt": "Subconjuntos II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> que pode conter duplicatas, retorne <em>todos os possíveis</em> <span data-keyword=\"subset\"><em>subconjuntos</em></span><em> (o conjunto potência)</em>.</p>\n\n<p>O conjunto de soluções <strong>não deve</strong> conter subconjuntos duplicados. Retorne a solução em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,2]\n<strong>Saída:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [0]\n<strong>Saída:</strong> [[],[0]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "91",
    "paidOnly": false,
    "title": "Decode Ways",
    "titleSlug": "decode-ways",
    "url": "https://leetcode.com/problems/decode-ways",
    "description_url": "https://leetcode.com/problems/decode-ways/description/",
    "description": "<p>You have intercepted a secret message encoded as a string of numbers. The message is <strong>decoded</strong> via the following mapping:</p>\n\n<p><code>&quot;1&quot; -&gt; &#39;A&#39;<br />\n&quot;2&quot; -&gt; &#39;B&#39;<br />\n...<br />\n&quot;25&quot; -&gt; &#39;Y&#39;<br />\n&quot;26&quot; -&gt; &#39;Z&#39;</code></p>\n\n<p>However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes (<code>&quot;2&quot;</code> and <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p>\n\n<p>For example, <code>&quot;11106&quot;</code> can be decoded into:</p>\n\n<ul>\n\t<li><code>&quot;AAJF&quot;</code> with the grouping <code>(1, 1, 10, 6)</code></li>\n\t<li><code>&quot;KJF&quot;</code> with the grouping <code>(11, 10, 6)</code></li>\n\t<li>The grouping <code>(1, 11, 06)</code> is invalid because <code>&quot;06&quot;</code> is not a valid code (only <code>&quot;6&quot;</code> is valid).</li>\n</ul>\n\n<p>Note: there may be strings that are impossible to decode.<br />\n<br />\nGiven a string s containing only digits, return the <strong>number of ways</strong> to <strong>decode</strong> it. If the entire string cannot be decoded in any valid way, return <code>0</code>.</p>\n\n<p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;12&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>&quot;12&quot; could be decoded as &quot;AB&quot; (1 2) or &quot;L&quot; (12).</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;226&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">3</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>&quot;226&quot; could be decoded as &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), or &quot;BBF&quot; (2 2 6).</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;06&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>&quot;06&quot; cannot be mapped to &quot;F&quot; because of the leading zero (&quot;6&quot; is different from &quot;06&quot;). In this case, the string is not a valid encoding, so return 0.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> contains only digits and may contain leading zero(s).</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/decode-ways/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numDecodings(self, s: str) -> int:\n    n = len(s)\n    # dp[i] := # Of ways to decode s[i..n)\n    dp = [0] * n + [1]\n\n    def isValid(a: chr, b=None) -> bool:\n      if b:\n        return a == '1' or a == '2' and b < '7'\n      return a != '0'\n\n    if isValid(s[-1]):\n      dp[n - 1] = 1\n\n    for i in reversed(range(n - 1)):\n      if isValid(s[i]):\n        dp[i] += dp[i + 1]\n      if isValid(s[i], s[i + 1]):\n        dp[i] += dp[i + 2]\n\n    return dp[0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numDecodings(String s) {\n    final int n = s.length();\n    // dp[i] := # of ways to decode s[i..n)\n    int[] dp = new int[n + 1];\n    dp[n] = 1; // \"\"\n    dp[n - 1] = isValid(s.charAt(n - 1)) ? 1 : 0;\n\n    for (int i = n - 2; i >= 0; --i) {\n      if (isValid(s.charAt(i)))\n        dp[i] += dp[i + 1];\n      if (isValid(s.charAt(i), s.charAt(i + 1)))\n        dp[i] += dp[i + 2];\n    }\n\n    return dp[0];\n  }\n\n  private boolean isValid(char c) {\n    return c != '0';\n  }\n\n  private boolean isValid(char c1, char c2) {\n    return c1 == '1' || c1 == '2' && c2 < '7';\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numDecodings(string s) {\n    const int n = s.length();\n    // dp[i] := # of ways to decode s[i..n)\n    vector<int> dp(n + 1);\n    dp[n] = 1;  // \"\"\n    dp[n - 1] = isValid(s[n - 1]);\n\n    for (int i = n - 2; i >= 0; --i) {\n      if (isValid(s[i]))\n        dp[i] += dp[i + 1];\n      if (isValid(s[i], s[i + 1]))\n        dp[i] += dp[i + 2];\n    }\n\n    return dp[0];\n  }\n\n private:\n  bool isValid(char c) {\n    return c != '0';\n  }\n\n  bool isValid(char c1, char c2) {\n    return c1 == '1' || c1 == '2' && c2 < '7';\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/91.html",
    "category": "Algorithms",
    "acceptance_rate": 36.395583605584356,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 12370,
    "dislikes": 4574,
    "similar_questions": "[{\"title\": \"Decode Ways II\", \"titleSlug\": \"decode-ways-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Separate Numbers\", \"titleSlug\": \"number-of-ways-to-separate-numbers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Number of Texts\", \"titleSlug\": \"count-number-of-texts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 1445891, \"totalSubmissionRaw\": 3972727, \"acRate\": \"36.4%\"}",
    "title_pt": "Decodificação de Mensagens",
    "description_pt": "<p>Você interceptou uma mensagem secreta codificada como uma string de números. A mensagem é <strong>decodificada</strong> por meio do seguinte mapeamento:</p>\n\n<p><code>&quot;1&quot; -&gt; &#39;A&#39;<br />\n&quot;2&quot; -&gt; &#39;B&#39;<br />\n...<br />\n&quot;25&quot; -&gt; &#39;Y&#39;<br />\n&quot;26&quot; -&gt; &#39;Z&#39;</code></p>\n\n<p>No entanto, ao decodificar a mensagem, você percebe que existem muitas maneiras diferentes de decodificá-la porque alguns códigos estão contidos em outros códigos (<code>&quot;2&quot;</code> e <code>&quot;5&quot;</code> vs <code>&quot;25&quot;</code>).</p>\n\n<p>Por exemplo, <code>&quot;11106&quot;</code> pode ser decodificada em:</p>\n\n<ul>\n\t<li><code>&quot;AAJF&quot;</code> com o agrupamento <code>(1, 1, 10, 6)</code></li>\n\t<li><code>&quot;KJF&quot;</code> com o agrupamento <code>(11, 10, 6)</code></li>\n\t<li>O agrupamento <code>(1, 11, 06)</code> é inválido porque <code>&quot;06&quot;</code> não é um código válido (somente <code>&quot;6&quot;</code> é válido).</li>\n</ul>\n\n<p>Nota: pode haver strings que são impossíveis de decodificar.<br />\n<br />\nDada uma string s contendo apenas dígitos, retorne o <strong>número de maneiras</strong> de <strong>decodificá-la</strong>. Se a string inteira não puder ser decodificada de nenhuma maneira válida, retorne <code>0</code>.</p>\n\n<p>Os casos de teste são gerados de forma que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;12&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>&quot;12&quot; poderia ser decodificada como &quot;AB&quot; (1 2) ou &quot;L&quot; (12).</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;226&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">3</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>&quot;226&quot; poderia ser decodificada como &quot;BZ&quot; (2 26), &quot;VF&quot; (22 6), ou &quot;BBF&quot; (2 2 6).</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;06&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>&quot;06&quot; não pode ser mapeada para &quot;F&quot; por causa do zero à esquerda (&quot;6&quot; é diferente de &quot;06&quot;). Neste caso, a string não é uma codificação válida, então retorne 0.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> contém apenas dígitos e pode conter zero(s) à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "92",
    "paidOnly": false,
    "title": "Reverse Linked List II",
    "titleSlug": "reverse-linked-list-ii",
    "url": "https://leetcode.com/problems/reverse-linked-list-ii",
    "description_url": "https://leetcode.com/problems/reverse-linked-list-ii/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list and two integers <code>left</code> and <code>right</code> where <code>left &lt;= right</code>, reverse the nodes of the list from position <code>left</code> to position <code>right</code>, and return <em>the reversed list</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5], left = 2, right = 4\n<strong>Output:</strong> [1,4,3,2,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [5], left = 1, right = 1\n<strong>Output:</strong> [5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is <code>n</code>.</li>\n\t<li><code>1 &lt;= n &lt;= 500</code></li>\n\t<li><code>-500 &lt;= Node.val &lt;= 500</code></li>\n\t<li><code>1 &lt;= left &lt;= right &lt;= n</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you do it in one pass?",
    "solution_url": "https://leetcode.com/problems/reverse-linked-list-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n    if left == 1:\n      return self.reverseN(head, right)\n\n    head.next = self.reverseBetween(head.next, left - 1, right - 1)\n    return head\n\n  def reverseN(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n    if n == 1:\n      return head\n\n    newHead = self.reverseN(head.next, n - 1)\n    headNext = head.next\n    head.next = headNext.next\n    headNext.next = head\n    return newHead",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode reverseBetween(ListNode head, int left, int right) {\n    if (left == 1)\n      return reverseN(head, right);\n\n    head.next = reverseBetween(head.next, left - 1, right - 1);\n\n    return head;\n  }\n\n  private ListNode reverseN(ListNode head, int n) {\n    if (n == 1)\n      return head;\n\n    ListNode newHead = reverseN(head.next, n - 1);\n    ListNode headNext = head.next;\n    head.next = headNext.next;\n    headNext.next = head;\n\n    return newHead;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* reverseBetween(ListNode* head, int left, int right) {\n    if (left == 1)\n      return reverseN(head, right);\n\n    head->next = reverseBetween(head->next, left - 1, right - 1);\n\n    return head;\n  }\n\n private:\n  ListNode* reverseN(ListNode* head, int n) {\n    if (n == 1)\n      return head;\n\n    ListNode* newHead = reverseN(head->next, n - 1);\n    ListNode* headNext = head->next;\n    head->next = headNext->next;\n    headNext->next = head;\n\n    return newHead;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/92.html",
    "category": "Algorithms",
    "acceptance_rate": 49.43273757786056,
    "topics": [
      "Linked List"
    ],
    "hints": [],
    "likes": 12219,
    "dislikes": 706,
    "similar_questions": "[{\"title\": \"Reverse Linked List\", \"titleSlug\": \"reverse-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1081127, \"totalSubmissionRaw\": 2187069, \"acRate\": \"49.4%\"}",
    "title_pt": "Inverter Sublista em Lista Encadeada II",
    "description_pt": "<p>Dada a <code>head</code> de uma lista encadeada simplesmente encadeada e dois inteiros <code>left</code> e <code>right</code> onde <code>left &lt;= right</code>, reverta os nós da lista da posição <code>left</code> até a posição <code>right</code> e retorne <em>a lista invertida</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev2ex2.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5], left = 2, right = 4\n<strong>Saída:</strong> [1,4,3,2,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [5], left = 1, right = 1\n<strong>Saída:</strong> [5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista é <code>n</code>.</li>\n\t<li><code>1 &lt;= n &lt;= 500</code></li>\n\t<li><code>-500 &lt;= Node.val &lt;= 500</code></li>\n\t<li><code>1 &lt;= left &lt;= right &lt;= n</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria fazer isso em uma única passada?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "93",
    "paidOnly": false,
    "title": "Restore IP Addresses",
    "titleSlug": "restore-ip-addresses",
    "url": "https://leetcode.com/problems/restore-ip-addresses",
    "description_url": "https://leetcode.com/problems/restore-ip-addresses/description/",
    "description": "<p>A <strong>valid IP address</strong> consists of exactly four integers separated by single dots. Each integer is between <code>0</code> and <code>255</code> (<strong>inclusive</strong>) and cannot have leading zeros.</p>\n\n<ul>\n\t<li>For example, <code>&quot;0.1.2.201&quot;</code> and <code>&quot;192.168.1.1&quot;</code> are <strong>valid</strong> IP addresses, but <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> and <code>&quot;192.168@1.1&quot;</code> are <strong>invalid</strong> IP addresses.</li>\n</ul>\n\n<p>Given a string <code>s</code> containing only digits, return <em>all possible valid IP addresses that can be formed by inserting dots into </em><code>s</code>. You are <strong>not</strong> allowed to reorder or remove any digits in <code>s</code>. You may return the valid IP addresses in <strong>any</strong> order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;25525511135&quot;\n<strong>Output:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;0000&quot;\n<strong>Output:</strong> [&quot;0.0.0.0&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;101023&quot;\n<strong>Output:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>s</code> consists of digits only.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/restore-ip-addresses/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Approach 1: Backtracking\n\n#### Intuition\n\n\nSince a valid IP address consists of 4 integers, that means we need to place 3 dots. We can try putting dots at all possible different positions using backtracking. If an invalid number is formed then we backtrack to try out another combination.\n\n> Backtracking can be defined as a general algorithmic technique that considers searching every possible combination to solve a computational problem. It incrementally builds candidates to the solution and abandons a candidate (\"backtracks\") when it determines that the candidate cannot lead to the solution.\n\nWe will recursively enumerate all the possibilities and whenever we get a new integer because of a dot (or 2 integers for the last dot), we check whether the integer(s) is valid, i.e the integer cannot have leading 0s other than being 0 itself and it's no larger than 255.\nThere are 3 possibilities to add each dot, namely it can be added after 1, 2, or 3 digits from the last dot or the beginning of the string, so there are at most $3 ^ 3 = 27$ possibilities to add all 3 dots.\n\nAn optimization is to return an empty result if the input string's length is longer than 12 since each integer can have 3 digits at most (any more and it would either have leading zeroes or be greater than 255).\n\nWe can create a helper function `valid(s, start, length)` to check whether the substring from index `start` to `start + length` is a valid number from range 0-255. The logic is to check both the conditions (the caller guarantees that the length is in the range of [1, 3]):\n\n1. If the substring's first character is `0` (i.e. `s[start]` is '0'), then `length` must be 1.\n2. If `length` is `3`, the substring should no larger than \"255\" lexically. If the length is 1 or 2 and the first case was not triggered, then it will be in the acceptable range.\n\n#### Algorithm\n\nCreate a function `helper` which takes the original string `s`, the processing index `startIndex` (i.e we only consider the substring starting from `startIndex` and the prefix part is already separated into valid integers.), a list of integers `dots` which saves distances for the dots we have added so far and a list of strings `ans` to save the answers.\n\n1. Set `remainingLength` to `length of s - startIndex` which is the string length we want to process.\n2. Set `remainingNumberOfIntegers` to `4 - dots.length`. This is how many integers we have left to form.\n3. Return if `remainingLength` is larger than `remainingNumberOfIntegers * 3` or smaller than `remainingNumberOfIntegers`, since each integer has 1-3 digits. Also note that this catches the case where `s.length() > 12` since at the very beginning `remainingLength` is `s.length()` and `remainingNumberOfIntegers` is 4.\n4. If `remainingNumberOfIntegers = 1`,\n    * if the last integer `s.substring(startIndex, startIndex + remainingLength)` is valid\n        * Create an empty string to save this answer using the following steps.\n        * Set `last` to `0`.\n        * Iterate over all elements `dot` in the list `dots`.\n            * Append `s.substring(last, last + dot)` and a '.' into the answer string.\n            * Increase `last` by `dot` and repeat these steps for each dot.\n       * Append `s.substring(last, s.length)`. This is the final integer after the last dot.\n       * Add the answer string into `ans`.\n    * Return.\n5. Iterate over `curPos` from `1` to `min(3, remainingLength)`. `curPos` is the number of digits we are including before placing a dot.\n    * Place a dot by adding `curPos` into `dots`.\n    * If the integer `s.substring(startIndex, startIndex + curPos)` is valid\n        * Call helper(s, startIndex + curPos, dots, ans)\n    * Remove the dot that we placed to backtrack.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/DYStKNxi/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"DYStKNxi\"></iframe>\n\n\n#### Complexity Analysis\n\nLet's assume we need to separate the input string into $N$ integers, each integer is at most $M$ digits.\n\n* Time complexity: $O(M ^ N \\cdot N)$.\n\n There are at most $M ^ {N - 1}$ possibilities, and for each possibility checking whether all parts are valid takes $O(M \\cdot N)$ time, so the final time complexity is $O(M ^ {N - 1}) \\cdot O(M \\cdot N)$ = $O(M ^ N \\cdot N)$.\n\nFor this question, M = 3, N = 4, so the time complexity is $O(1)$.\n\n* Space complexity: $O(M \\cdot N)$.\n\n  For each possibility, we save (N - 1) numbers (the number of digits before each dot) which takes $O(N)$ space. And we need temporary space to save a solution before putting it into the answer list. The length of each solution string is $M \\cdot N + M - 1$ = $O(M \\cdot N)$, so the total space complexity is $O(M \\cdot N)$ if we don't take the output space into consideration.\n\nFor this question, M = 3, N = 4, so the space complexity is $O(1)$.\n\n\n### Approach 2: Iterative\n\n#### Intuition\nWe need to separate the input string into 4 integers, so we can enumerate the length of the first 3 integers, `len1`, `len2`, `len3`. We could iterate over `len1`, `len2`, `len3` with 3 nested loops and the last integer is the remaining part after separating out the first 3.\n\nWe can make the ranges of `len1`, `len2`, `len3` tighter:\n\n* `len1` should be in the range `[max(1, s.length() - 9), min(3, s.length() - 3]` since we need to separate 3 more integers after it and the length of each integer is in [1..3].\n* Similarly, `len2` should be in the range `[max(1, s.length() - len1 - 6, min(3, s.length() - len1 - 2]`\n* `len3` should be in the range `[max(1, s.length() - len1 - len2 - 3), min(3, s.length() - len1 - len2 - 1]`\n\nIn this way, the last part's length is always in the range of `[1..3]`, then we can split each substring out based on the lengths and check whether they are valid. Each integer can be validated before starting the loop of the next part to prevent wasting time.\n\n\n#### Algorithm\n\n1. Initialize an array of strings `ans`.\n2. Iterate over the range of `len1`, the length of the first integer.\n    * If the first integer is valid, then we iterate over `len2`'s range. \n        * If the second integer is also valid, then we iterate over `len3`'s range.\n           * If both third and fourth integers are valid, concatenate all four integers together with a character `'.'` between any 2 neighbors, and add the result string to `ans`.\n3. Return `ans`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/mcmi5hLS/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"mcmi5hLS\"></iframe>\n\n\n#### Complexity Analysis\n\n\nLet's assume we need to separate the input string into $N$ integers, each integer is at most $M$ digits.\n\n* Time complexity: $O(M ^ N \\cdot N)$.\n\n  We have $(N - 1)$ nested loops and each of them iterates at most $M$ times, so the total number of iterations is at most  $M ^ {N - 1}$ .\n\n  In each iteration we split $N$ substrings out to check whether they are valid, each substring's length is at most $M$, so the time complexity to separate out all of them is $O(M \\cdot N)$.\n\nFor this question, M = 3, N = 4, so the time complexity is $O(1)$.\n\n* Space complexity: $O(M \\cdot N)$.\n \nThe algorithm saves (N - 1) numbers (the number of digits before each dot) which takes $O(N)$ space. And we need temporary space to save a solution before putting it into the answer list. The length of each solution string is $M \\cdot N + M - 1$ = $O(M \\cdot N)$, so the total space complexity is $O(M \\cdot N)$ if we don't take the output space into consideration.\n\nFor this question, M = 3, N = 4, so the space complexity is $O(1)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def restoreIpAddresses(self, s: str) -> List[str]:\n    ans = []\n\n    def dfs(start: int, path: List[int]) -> None:\n      if len(path) == 4 and start == len(s):\n        ans.append(path[0] + '.' + path[1] + '.' + path[2] + '.' + path[3])\n        return\n      if len(path) == 4 or start == len(s):\n        return\n\n      for length in range(1, 4):\n        if start + length > len(s):\n          return  # Out of bound\n        if length > 1 and s[start] == '0':\n          return  # Leading '0'\n        num = s[start: start + length]\n        if int(num) > 255:\n          return\n        dfs(start + length, path + [num])\n\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> restoreIpAddresses(final String s) {\n    List<String> ans = new ArrayList<>();\n    dfs(s, 0, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(final String s, int start, List<String> path, List<String> ans) {\n    if (path.size() == 4 && start == s.length()) {\n      ans.add(String.join(\".\", path));\n      return;\n    }\n    if (path.size() == 4 || start == s.length())\n      return;\n\n    for (int length = 1; length <= 3; ++length) {\n      if (start + length > s.length()) // Out of bound\n        return;\n      if (length > 1 && s.charAt(start) == '0') // Leading '0'\n        return;\n      final String num = s.substring(start, start + length);\n      if (Integer.parseInt(num) > 255)\n        return;\n      path.add(num);\n      dfs(s, start + length, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> restoreIpAddresses(const string& s) {\n    vector<string> ans;\n    dfs(s, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const string& s, int start, vector<string>&& path,\n           vector<string>& ans) {\n    if (path.size() == 4 && start == s.length()) {\n      ans.push_back(path[0] + \".\" + path[1] + \".\" + path[2] + \".\" + path[3]);\n      return;\n    }\n    if (path.size() == 4 || start == s.length())\n      return;\n\n    for (int length = 1; length <= 3; ++length) {\n      if (start + length > s.length())\n        return;  // Out of bound\n      if (length > 1 && s[start] == '0')\n        return;  // Leading '0'\n      const string& num = s.substr(start, length);\n      if (stoi(num) > 255)\n        return;\n      path.push_back(num);\n      dfs(s, start + length, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/93.html",
    "category": "Algorithms",
    "acceptance_rate": 52.89732572841894,
    "topics": [
      "String",
      "Backtracking"
    ],
    "hints": [],
    "likes": 5414,
    "dislikes": 806,
    "similar_questions": "[{\"title\": \"IP to CIDR\", \"titleSlug\": \"ip-to-cidr\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"533.8K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 533823, \"totalSubmissionRaw\": 1009170, \"acRate\": \"52.9%\"}",
    "title_pt": "Restaurar Endereços IP",
    "description_pt": "<p>Um <strong>endereço IP válido</strong> consiste exatamente de quatro inteiros separados por pontos simples. Cada inteiro está entre <code>0</code> e <code>255</code> (<strong>inclusive</strong>) e não pode ter zeros à esquerda.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;0.1.2.201&quot;</code> e <code>&quot;192.168.1.1&quot;</code> são endereços IP <strong>válidos</strong>, mas <code>&quot;0.011.255.245&quot;</code>, <code>&quot;192.168.1.312&quot;</code> e <code>&quot;192.168@1.1&quot;</code> são endereços IP <strong>inválidos</strong>.</li>\n</ul>\n\n<p>Dada uma string <code>s</code> contendo apenas dígitos, retorne <em>todos os possíveis endereços IP válidos que podem ser formados inserindo pontos em </em><code>s</code>. Você <strong>não</strong> pode reordenar ou remover quaisquer dígitos em <code>s</code>. Você pode retornar os endereços IP válidos em <strong>qualquer</strong> ordem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;25525511135&quot;\n<strong>Saída:</strong> [&quot;255.255.11.135&quot;,&quot;255.255.111.35&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;0000&quot;\n<strong>Saída:</strong> [&quot;0.0.0.0&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;101023&quot;\n<strong>Saída:</strong> [&quot;1.0.10.23&quot;,&quot;1.0.102.3&quot;,&quot;10.1.0.23&quot;,&quot;10.10.2.3&quot;,&quot;101.0.2.3&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>s</code> consiste apenas de dígitos.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "94",
    "paidOnly": false,
    "title": "Binary Tree Inorder Traversal",
    "titleSlug": "binary-tree-inorder-traversal",
    "url": "https://leetcode.com/problems/binary-tree-inorder-traversal",
    "description_url": "https://leetcode.com/problems/binary-tree-inorder-traversal/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes&#39; values</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,3,2]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[4,2,6,5,7,1,3,9,8]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?",
    "solution_url": "https://leetcode.com/problems/binary-tree-inorder-traversal/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Recursive Approach\n\nThe first method to solve this problem is using recursion. This is the classical method and is straightforward. We can define a helper function to implement recursion.\n\n<iframe src=\"https://leetcode.com/playground/E5pBkUup/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"E5pBkUup\"></iframe>\n\n**Complexity Analysis**\n\nTime complexity: $$O(n)$$\n\n  - The time complexity is $$O(n)$$ because the recursive function is $$T(n) = 2 \\cdot T(n/2)+1$$.\n\nSpace complexity: $$O(n)$$\n\n  - The worst case space required is $$O(n)$$, and in the average case it's $$O(\\log n)$$ where $$n$$ is number of nodes.\n  \n<br />\n\n---\n\n### Approach 2: Iterating method using Stack\n\nThe strategy is very similiar to the first method, the different is using stack.\n\nHere is an illustration:\n\n!?!../Documents/94_Binary.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/9k44r9CB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"9k44r9CB\"></iframe>\n\n**Complexity Analysis**\n\nTime complexity: $$O(n)$$\n\nSpace complexity: $$O(n)$$\n\n<br />\n\n---\n\n### Approach 3: Morris Traversal\n\n\nIn this method, we have to use a new data structure - Threaded Binary Tree, and the strategy is as follows:\n\n\n>Step 1: Initialize current as root\n>\n>Step 2: While current is not NULL,\n>\n>     If current does not have left child\n>\n>         a. Add current’s value\n>\n>         b. Go to the right, i.e., current = current.right\n>\n>     Else\n>\n>         a. In current's left subtree, make current the right child of the rightmost node\n>\n>         b. Go to this left child, i.e., current = current.left\n\n\nFor example:\n```\n\n          1\n        /   \\\n       2     3\n      / \\   /\n     4   5 6\n\n```\nFirst, 1 is the root, so initialize 1 as current, 1 has left child which is 2, the current's left subtree is\n\n```\n         2\n        / \\\n       4   5\n```\n So in this subtree, the rightmost node is 5, then make the current(1) as the right child of 5. Set current = current.left (current = 2).\nThe tree now looks like:\n```\n         2\n        / \\\n       4   5\n            \\\n             1\n              \\\n               3\n              /\n             6\n```\nFor current 2, which has left child 4, we can continue with the same process as we did above\n```\n        4\n         \\\n          2\n           \\\n            5\n             \\\n              1\n               \\\n                3\n               /\n              6\n```\n then add 4 because it has no left child, then add 2, 5, 1, 3 one by one, for node 3 which has left child 6, do the same as above.\nFinally, the inorder traversal is [4,2,5,1,6,3].\n\nFor more details, please check\n[Threaded binary tree](https://en.wikipedia.org/wiki/Threaded_binary_tree) and\n[Explanation of Morris Method](https://stackoverflow.com/questions/5502916/explain-morris-inorder-tree-traversal-without-using-stacks-or-recursion)\n\n\n<iframe src=\"https://leetcode.com/playground/fVkds6Bx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"fVkds6Bx\"></iframe>\n\n**Complexity Analysis**\n\nTime complexity: $$O(n)$$\n\n  - To prove that the time complexity is $$O(n)$$, the biggest problem lies in finding the time complexity of finding the predecessor nodes of all the nodes in the binary tree. Intuitively, the complexity is $$O(n \\log n)$$, because to find the predecessor node for a single node related to the height of the tree. But in fact, finding the predecessor nodes for all nodes only needs $$O(n)$$ time. Because a binary Tree with $$n$$ nodes has $$n-1$$ edges, the whole processing for each edges up to 2 times, one is to locate a node, and the other is to find the predecessor node. So the complexity is $$O(n)$$.\n\nSpace complexity: $$O(1)$$\n\n  - Extra space is only allocated for the ArrayList of size $$n$$, however the output does not count towards the space complexity.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n    ans = []\n    stack = []\n\n    while root or stack:\n      while root:\n        stack.append(root)\n        root = root.left\n      root = stack.pop()\n      ans.append(root.val)\n      root = root.right\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> inorderTraversal(TreeNode root) {\n    List<Integer> ans = new ArrayList<>();\n    Deque<TreeNode> stack = new ArrayDeque<>();\n\n    while (root != null || !stack.isEmpty()) {\n      while (root != null) {\n        stack.push(root);\n        root = root.left;\n      }\n      root = stack.pop();\n      ans.add(root.val);\n      root = root.right;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> inorderTraversal(TreeNode* root) {\n    vector<int> ans;\n    stack<TreeNode*> stack;\n\n    while (root || !stack.empty()) {\n      while (root) {\n        stack.push(root);\n        root = root->left;\n      }\n      root = stack.top(), stack.pop();\n      ans.push_back(root->val);\n      root = root->right;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/94.html",
    "category": "Algorithms",
    "acceptance_rate": 78.3925412664811,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 14095,
    "dislikes": 839,
    "similar_questions": "[{\"title\": \"Validate Binary Search Tree\", \"titleSlug\": \"validate-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Preorder Traversal\", \"titleSlug\": \"binary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Postorder Traversal\", \"titleSlug\": \"binary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Element in a BST\", \"titleSlug\": \"kth-smallest-element-in-a-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Closest Binary Search Tree Value II\", \"titleSlug\": \"closest-binary-search-tree-value-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Inorder Successor in BST\", \"titleSlug\": \"inorder-successor-in-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Convert Binary Search Tree to Sorted Doubly Linked List\", \"titleSlug\": \"convert-binary-search-tree-to-sorted-doubly-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Distance Between BST Nodes\", \"titleSlug\": \"minimum-distance-between-bst-nodes\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.1M\", \"totalSubmission\": \"3.9M\", \"totalAcceptedRaw\": 3090661, \"totalSubmissionRaw\": 3942545, \"acRate\": \"78.4%\"}",
    "title_pt": "Percurso em Ordem de Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>o percurso em ordem dos valores de seus nós</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,3,2]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[4,2,6,5,7,1,3,9,8]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> A solução recursiva é trivial, você consegue fazê-la iterativamente?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "95",
    "paidOnly": false,
    "title": "Unique Binary Search Trees II",
    "titleSlug": "unique-binary-search-trees-ii",
    "url": "https://leetcode.com/problems/unique-binary-search-trees-ii",
    "description_url": "https://leetcode.com/problems/unique-binary-search-trees-ii/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg\" style=\"width: 600px; height: 148px;\" />\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/unique-binary-search-trees-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nGiven an integer `n`, our task is to return all unique BSTs (binary search trees) that have exactly `n` nodes of unique values from `1` to `n`.\n\n---\n\n### Approach 1: Recursive Dynamic Programming\n\n#### Intuition\n\nIn each node of a binary search tree (BST), all values in the left subtree are smaller and all values in the right subtree are greater.\n\nTo find all the possible permutations of BSTs with `n` nodes, we can lock one node as the `root` node and split `n - 1` nodes between the left and right subtrees in all the possible ways. Let's say we place a node with value `i` as the root node and place `i - 1` nodes having values from `1` to `i - 1` in the left subtree. (If `i == 1`, the left child is null). Similarly, we place the remaining `n - i` nodes having values from `i + 1` to `n` in the right subtree. (If `i == n`, the right child is null).\n\nNow, we create a list of nodes called `leftSubTrees` for all the possible BSTs that could be the left subtree. Similarly, we create a list of nodes called `rightSubTrees` for all the BSTs that could be the right subtree. \n\n> In a BST, every subtree is also a BST.\n\nWe iterate over both the lists and for each node pair `l` in `leftSubTrees` and `r` in `rightSubTrees`, we create a new `root` node with value `i` and set the left and right child of `root` to `l` and `r` respectively to form all the BSTs with the root node as `i`.\n\nWe can iterate over the root's value from `i = 1` to `n` and repeat the process for each root value to get all the BSTs.\n\nYou may notice that the subproblem of finding the arrays `leftSubTrees` and `rightSubTrees` are similar to the original problem. We can implement this approach using recursion as we are breaking down a problem with `n` nodes to smaller, repetitive subproblems with `i - 1` and `n - i` nodes (for `i = 1` till `n`) to compute the answer for `n` nodes. We only need the range of node values as the parameters to create the BSTs with nodes having values in that range.\n\nWe implement a recursive function `allPossibleBST(start, end)` where `start` and `end` correspond to the range of node values that should be present in the BSTs created by this call. For a root node with value `i`, we will find all the left subtrees using `leftSubTrees = allPossibleBST(start, i - 1)` and also compute all the right subtrees using `rightSubTrees = allPossibleBST(i + 1, right)`. Finally, we iterate over all pairs between `leftSubTrees` and `rightSubTrees` and create a new root with value `i` for each pair.\n\nThe base case of this function is when `start > end`. We have no values in our range and thus we will return `null` (an empty tree).\n\nHere is a visual representation of the recursion tree with `3` nodes:\n\n![img](../Figures/95/95-1.png)\n\nSeveral subproblems, such as `allPossibleBST(1, 1)`, `allPossibleBST(3, 3)`, etc., are solved multiple times in the small partial recursion tree shown above. If we draw the entire recursion tree, we can see that there are many subproblems that are solved repeatedly.\n\nTo avoid this issue, we store the solution of the subproblem in a hashmap that stores the mapping from a range of nodes values to the list of root nodes of all possible BSTs that can be formed with the same number of nodes. When we encounter the same subproblem again, we simply refer to this map to get the required list of `TreeNode`. This is called **memoization**.\n\n#### Algorithm\n\n1. Create a hash map `memo` where `memo[(start, end)]` contains the list of root nodes of all possible BSTs with the range of node values from `start` to `end`.\n2. We implement a recursive function `allPossibleBST` which takes the starting range of node values `start`, ending range `end`, and `memo` as parameters. It returns a list of `TreeNode` corresponding to all the BSTs that can be formed with this range of node values. We call `allPossibleBST(1, n, memo)` and perform the following:\n    - We declare a list of `TreeNode` called `res` to store the list of root nodes of all possible BSTs.\n    - If `start > end`, we push `null` to `res` and return it.\n    - If we already have solved this subproblem, i.e., `memo` contains the pair `(start, end)`, we return `memo[(start, end)]`.\n    - Select the root node value from `i = start` to `end` incrementing `i` by `1` after each iteration. We recursively call `leftSubtrees = llPossibleBST(start, i - 1, memo)` and `rightSubTrees = allPossibleBST(i + 1, end, memo)`. We iterate over all pairs between `leftSubtrees` and `rightSubTrees` and create a new root with value `i` for each pair. We push `root` of the new formed BST into `res`.\n    - Set `memo[(start, end)] = res` and return `res`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/FiZegYw8/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"FiZegYw8\"></iframe>\n\n#### Complexity Analysis\n\nNote, the time and space complexity of this problem is difficult to derive. In an interview, you should do your best to find an upper bound. The level of analysis here would not be expected in an interview.\n\nThe number of unique BSTs that can be formed with `n` nodes is $G(n)$ where $G(n)$ is the $n^{th}$ [Catalan number](https://en.wikipedia.org/wiki/Catalan_number). $G(n) = O(\\dfrac{4^{n}}{n^{1.5}})$.\n\n* Time complexity: $O(\\dfrac{4^n}{\\sqrt{n}})$.\n    - There are $G(n) = \\dfrac{4^n}{n^{1.5}}$ BSTs in our answer. Each of these BSTs has $n$ nodes, so it cost us $O(n)$ to build each one. This gives us a time complexity of $O(n \\cdot G(n)) = O(\\dfrac{4^n}{\\sqrt{n}})$.\n\n* Space complexity: $O(\\sum_{k=1}^{n}{[(n - k + 1) \\cdot  \\dfrac{4^k}{\\sqrt{k}}]})$.\n\n    We use some space for the recursion call stack, but the majority of the space used by the algorithm is storing the lists of BSTs in `memo`. Let's analyze how many nodes are stored in `memo`.\n\n    The number of nodes in a range `start, end` is `end - start + 1`. Let $k = \\text{end} - \\text{start} + 1$ represent this formula.\n\n    There are $n$ states `start, end` with one node, that is $k = 1$.\n\n    There are $n - 1$ states `start, end` with two nodes, that is $k = 2$.\n\n    There are $n - 2$ states `start, end` with three nodes, that is $k = 3$.\n\n    This continues until there is only one state with $n$ nodes (the original input). In general, a value of $k$ has $n - k + 1$ states.\n\n    For a given state with value $k$, there are $G(k) = \\dfrac{4^k}{k^{1.5}}$ BSTs. Each of these BSTs has $k$ nodes, and thus takes up $k \\cdot G(k) = \\dfrac{4^k}{\\sqrt{k}}$ space in `memo`.\n\n    A given value $k$ has $n - k + 1$ states and thus takes up $(n - k + 1) \\cdot  \\dfrac{4^k}{\\sqrt{k}}$ space. In our algorithm, $k$ ranges from $1$ to $n$.\n\n    The space complexity is the summation for all values of $k$:\n\n    $\\Large{\\sum_{k=1}^{n}{[(n - k + 1) \\cdot  \\dfrac{4^k}{\\sqrt{k}}]}}$\n\n    This is a difficult sum to compute and involves higher-level mathematics. Using a program like WolframAlpha, we find that the sum is equal to:\n\n    $4^{1 + n} \\cdot \\Phi(4, -0.5, 1 + n) - 4^{1 + n} \\cdot (1 + n) \\cdot \\Phi(4, 0.5, 1 + n) - \\text{Li}_{-0.5}(4) + \\text{Li}_{0.5}(4) + n \\cdot \\text{Li}_{0.5}(4)$\n\n    Where $\\Phi$ is the [Lerch transcendent](https://en.wikipedia.org/wiki/Lerch_zeta_function) and $\\text{Li}_n(x)$ is the [polylogarithm function](https://en.wikipedia.org/wiki/Polylogarithm). Needless to say, computing this sum by hand is not necessary in an interview. Even reaching the summation expression would likely impress any interviewer.\n\n---\n\n### Approach 2: Iterative Dynamic Programming\n\n#### Intuition\n\nWe used memoization in the preceding approach to store the answers to subproblems in order to solve a larger problem. We can also use a bottom-up approach to solve such problems without using recursion. We build answers to subproblems iteratively first, then use them to build answers to larger problems.\n\nWe create a 3D list `dp[n + 1][n + 1]` where `dp[i][j]` will store a list of all BSTs that have node values ranging from `i` to `j`. Note that `dp[i][j] = allPossibleBST(i, j)` from the previous approach.\n\nWhen `i = j`, the range contains only one node with value `i`. We push a single node with value `i` in the list `dp[i][i]` for all the values of `i` from `1` to `n`. This acts as the base case of our solution while we move in bottom to top manner.\n\nWe form the answer with a smaller number of nodes having consecutive node values and move on to form answers for a bigger number of nodes. We run an outer loop from `numberOfNodes = 2` to `numberOfNodes = n` incrementing `numberOfNodes` by `1` after each iteration. This loop controls the total number of nodes under consideration.\n\nWe further need to choose a node value we start with. Let's call it `start`. As we have `numberOfNodes` nodes under consideration with consecutive values, the maximum node value in such a BST would be `end = start + numberOfNodes - 1`. We will move `start` from `1` to `n - numberOfNodes + 1`.\n\nNow we have the `start` value and the `end` value, we can implement the same logic that we did in the `allPossibleBST` function from the previous approach. Lock a value `i`, find all left and right subtrees, and then iterate over each `left, right` pair and create a new root with value `i` for each pair.\n\nAs we move from bottom to top, we will have a list of all the root nodes for all BSTs for every range of node values with lesser nodes.\n\nLocking a value `i` as the root node, we can find all left subtrees in `dp[start][i - 1]` and all right subtrees in `dp[i + 1][end]`. If `i == start`, the left subtree would be empty. Similarly, if `i == end`, the right subtree would be empty. We can handle these cases separately.\n\nWe run an outer loop from `numberOfNodes = 2` to `n`. We run an inner loop that selects the starting node value. It runs from `start = 1` to `n - numberOfNodes + 1`. We define `end = start + numberOfNodes - 1`. We run a third nested loop that selects the root of the BSTs under consideration. It runs from `i = start` to `end`.\n\nWe then iterate over the both the lists of left and right subtrees. For each root node `l` of the left subtree and `r` of the right subtree, we create a new `root` node with value `i` and set the left and right child to `l` and `r` respectively to form all the BSTs with root node as `i`. We also push each BST into `dp[start][end]` to be used later to build answer for other `dp` states with larger number of nodes.\n\n#### Algorithm\n\n1. Create a 3D list `dp[n + 1][n + 1]` where `dp[i][j]` will store a list of root nodes for all possible BSTs using `j - i + 1` nodes with values from `i` to `j` nodes.\n2. We initialize each list `dp[i][i]` to a `TreeNode` having value `i` for `i = 0` to `n`.\n3. Iterate from `numberOfNodes = 2` till `numberOfNodes = n` incrementing `numberOfNodes` by `1` after each iteration. We start an inner loop from `start = 1` to `n - numberOfNodes + 1` incrementing `start` by `1`. We create an integer variable `end = start + numberOfNodes - 1` which stores the highest node value of the BSTs that will be formed. We run another loop from `i = start` to `end` to use all the permutations as the root node value. We perform the following in this loop:\n    - We create a list of `TreeNode` called `leftSubtrees` which will store all the BSTs that can be formed with node values from `start` to `i - 1`. If `i == start`, we just add `null` to `leftSubtrees`, else `leftSubtrees == dp[start][i - 1]`.\n    - Similarly, we create a list of `TreeNode` called `rightSubtrees` which will store all the BSTs that can be formed with node values from `i + 1` to `end`. If `i == end`, we just add `null` to `rightSubtrees`, else `rightSubtrees == dp[i + 1][end]`.\n    - We form a new BST by creating a new node which acts as a root node with value `i`. For each element `left` in `leftSubtrees` and `right` in `rightSubtrees`, we set `root.left = left` and `root.right = right`. Finally, we add `root` to `dp[start][end]`.\n4. Return `dp[1][n]`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/hj8MdGva/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"hj8MdGva\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(\\dfrac{4^n}{\\sqrt{n}})$.\n    - The time complexity of this approach will be similar to the **time complexity** of the first approach because we are iterating over the same `dp` states in bottom-up manner as compared to the previous approach where we used top-down approach with memoization.\n\n* Space complexity: $O(\\sum_{k=1}^{n}{[(n - k + 1) \\cdot  \\dfrac{4^k}{\\sqrt{k}}]})$.\n    - The space complexity would also be the number of BSTs stored in the `dp` list which is equal to the number of BSTs stored in `memo` in the worst-case. Hence, we have the same space complexity as the first approach.\n\n---\n\n### Approach 3: Dynamic Programming with Space Optimization\n\n#### Intuition\n\nWe used a 3D list where we used `dp[start][end]` to store all the BSTs having `end - start + 1` nodes with range from `start` to `end`. Let's think if we can reduce the 3D `dp` list to a 2D list.\n\nIf we compare all the BSTs that can be created from a set of consecutive values from `start` to `end` to those that can be created with the same number of nodes from a set of values starting at `1` and ending at `end - start + 1`, we will find that **the structure of all the BSTs created with the above two ranges would be identical**. The only difference is an offset of `start - 1` in the node values.\n\nHere's a visual representation of BSTs with 3 nodes from range `[1, 3]` and all BSTs with range `[4, 6]`:\n\n![img](../Figures/95/95-2.png)\n\nWe can see the structure of all the BSTs created with the above two ranges are identical.\n\nSo, we can just store the BSTs for all the ranges starting from `1` and add the offset to convert them to required ranges.\n\nWe create a 2D list `dp[n + 1]` where `dp[i]` will store a list of all BSTs with `i` nodes having values from `1` to `i`. `dp[n]` would be the answer to the problem. Similar to the above approach, we will move in bottom to top manner.\n\nWe push a `null` node (empty tree) to `dp[0]` which acts as the base case.\n\nTo get the list of root nodes for all possible BSTs with `numberOfNodes` nodes, we would split the `numberOfNodes` nodes with `i - 1` nodes with values `1` to `i - 1` in the left subtree, a root node with value `i` and the remaining `numberOfNodes - i` nodes with values `i + 1` to `numberOfNodes` in the right subtree where `1 <= i <= numberOfNodes`. Note that we do not need the starting of the range here, unlike the previous approach. It is always `1`. \n\nAs we are executing in bottom-up manner and figuring out the answer for `numberOfNodes` nodes, we will already have the list of root nodes for all BSTs with `i - 1` and `numberOfNodes - i` nodes (for all values of `i = 1` to `numberOfNodes`).\n\nHowever, you may realize that `dp[i - 1]` will give all the BSTs having values from `1` to `i - 1` which is exactly what we want but `dp[numberOfNodes - i]` will give all the BSTs having values from `1` to `numberOfNodes - i` which isn't what we want. We want the right subtree to have `numberOfNodes - i` nodes but the range of nodes should be from `i + 1` to `numberOfNodes`. If we add the offset `(i + 1) - 1 = i` to all the nodes, it would solve this as we would now have trees with `numberOfNodes - i` nodes from values `i + 1` to `numberOfNodes`. Let us form the BSTs now.\n\nSimilar to the previous approach, we create a new instance of `TreeNode` called `root` with the value `i`. We set the left child of `root` to an element in `dp[i - 1]`.\n\nNow, let's set the right child of `root`. We know every element in `dp[numberOfNodes - i]` is a root node that stores a BST with `numberOfNodes - 1` nodes having values from `1` to `numberOfNodes - i`. To set the right child of `root`, we create a new tree exactly similar to the tree stored by an element of `dp[numberOfNodes - i]` but increment all the node values of the new tree by `i`. We then set the right child of `root` to this newer tree.\n\nThe required tree with `i` offset can be created by using a recursive function `clone` in which we pass a `TreeNode node` which corresponds to an element in `dp[numberOfNodes - i]` and an integer `offset`. We create a new `TreeNode clonedNode` with value `node.val + offset`. We then recursively set the left and the right child of `clonedNode` by performing `clonedNode.left = clone(node.left, offset)` and `clonedNode.right = clone(node.right, offset)`. Finally, return `clonedNode`.\n\nIt is important to note that we are creating new trees to set the right child of `root` to preserve the original trees as it might be used directly (as `dp[i - 1]`) in some other iteration of `i` and `numberOfNodes`.\n\n#### Algorithm\n\n1. Create a list `dp[n + 1]` where `dp[i]` will store a list of root nodes for all possible BSTs using `i` nodes. We initialize each list `dp[i]` to an empty list for `i = 0` to `n`.\n2. We push a `null` node (empty tree) into `dp[0]` because with `n = 0` we can't have any BST. This forms the base case.\n3. Iterate from `numberOfNodes = 1` till `numberOfNodes = n` incrementing `numberOfNodes` by `1` after each iteration. We start an inner loop from `i = 1` to `numberOfNodes` incrementing `i` by `1`. We perform the following in this loop:\n    - Create a variable `j = numberOfNodes - i - 1`. It presents the number of nodes in the right subtree under consideration.\n    - We can form a new BST by creating a new node which acts as a root node with value `i`. We assign its left child to any element in `dp[i]` and right child to a new tree where tree is similar to an element in `dp[j]` but all node values are incremented by `i`. As a result, we need two loops to iterate through the lists `dp[i]` and `dp[j]`. We create a new `root` node with value `i`. For each element `left` in `dp[i]` and `right` in `dp[j]`, we set `root.left = left` and `root.right = clone(right, i)`. Finally, we add `root` to `dp[numberOfNodes]`.\n4. Return `dp[n]`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/a8x29E6y/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"a8x29E6y\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(\\dfrac{4^n}{\\sqrt{n}})$.\n    - In this approach we are not storing all the BSTs with all the ranges. We are just storing BSTs starting from range `1`. However, we are creating all the BSTs for all the ranges from `[start, end]` (for `1 <= start, end  <= 1`) using the `clone` method by iterating over the BSTs starting with range `1`.\n    - As a result, the time complexity should be similar to the previous approach as we are generating the same number of BSTs.\n\n* Space complexity: $O(\\sum_{k=1}^{n}\\dfrac{4^k}{{\\sqrt{k}}})$.\n    - For any state `dp[k]`, we are storing all the BSTs that can be formed with $k$ nodes. We know there are $G(k)$ BSTs that can be formed with $k$ nodes. As we have $1$ to $n$ states, the total space consumed would be $O(\\sum_{k=1}^{n} k \\cdot G(k))$ = $O(\\sum_{k=1}^{n}\\dfrac{4^k}{{\\sqrt{k}}})$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def generateTrees(self, n: int) -> List[TreeNode]:\n    if n == 0:\n      return []\n\n    def generateTrees(mini: int, maxi: int) -> List[Optional[int]]:\n      if mini > maxi:\n        return [None]\n\n      ans = []\n\n      for i in range(mini, maxi + 1):\n        for left in generateTrees(mini, i - 1):\n          for right in generateTrees(i + 1, maxi):\n            ans.append(TreeNode(i))\n            ans[-1].left = left\n            ans[-1].right = right\n\n      return ans\n\n    return generateTrees(1, n)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<TreeNode> generateTrees(int n) {\n    if (n == 0)\n      return new ArrayList<>();\n    return generateTrees(1, n);\n  }\n\n  private List<TreeNode> generateTrees(int min, int max) {\n    if (min > max)\n      return Arrays.asList((TreeNode) null);\n\n    List<TreeNode> ans = new ArrayList<>();\n\n    for (int i = min; i <= max; ++i)\n      for (TreeNode left : generateTrees(min, i - 1))\n        for (TreeNode right : generateTrees(i + 1, max)) {\n          ans.add(new TreeNode(i));\n          ans.get(ans.size() - 1).left = left;\n          ans.get(ans.size() - 1).right = right;\n        }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<TreeNode*> generateTrees(int n) {\n    if (n == 0)\n      return {};\n    return generateTrees(1, n);\n  }\n\n private:\n  vector<TreeNode*> generateTrees(int min, int max) {\n    if (min > max)\n      return {nullptr};\n\n    vector<TreeNode*> ans;\n\n    for (int i = min; i <= max; ++i)\n      for (TreeNode* left : generateTrees(min, i - 1))\n        for (TreeNode* right : generateTrees(i + 1, max)) {\n          ans.push_back(new TreeNode(i));\n          ans.back()->left = left;\n          ans.back()->right = right;\n        }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/95.html",
    "category": "Algorithms",
    "acceptance_rate": 60.20474173548841,
    "topics": [
      "Dynamic Programming",
      "Backtracking",
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 7758,
    "dislikes": 560,
    "similar_questions": "[{\"title\": \"Unique Binary Search Trees\", \"titleSlug\": \"unique-binary-search-trees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Different Ways to Add Parentheses\", \"titleSlug\": \"different-ways-to-add-parentheses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"510K\", \"totalSubmission\": \"847.1K\", \"totalAcceptedRaw\": 510004, \"totalSubmissionRaw\": 847116, \"acRate\": \"60.2%\"}",
    "title_pt": "Árvores Binárias de Busca Únicas II",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>todas as <strong>BST&#39;</strong>s (árvores binárias de busca) estruturalmente únicas, que tenham exatamente </em><code>n</code><em> nós com valores únicos de</em> <code>1</code> <em>até</em> <code>n</code>. Retorne a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg\" style=\"width: 600px; height: 148px;\" />\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "96",
    "paidOnly": false,
    "title": "Unique Binary Search Trees",
    "titleSlug": "unique-binary-search-trees",
    "url": "https://leetcode.com/problems/unique-binary-search-trees",
    "description_url": "https://leetcode.com/problems/unique-binary-search-trees/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>the number of structurally unique <strong>BST&#39;</strong>s (binary search trees) which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg\" style=\"width: 600px; height: 148px;\" />\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 5\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 19</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/unique-binary-search-trees/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numTrees(self, n: int) -> int:\n    # G[i] := # Of unique BST's that store values 1..i\n    G = [1, 1] + [0] * (n - 1)\n\n    for i in range(2, n + 1):\n      for j in range(i):\n        G[i] += G[j] * G[i - j - 1]\n\n    return G[n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numTrees(int n) {\n    // G[i] := # of unique BST's that store values 1..i\n    int[] G = new int[n + 1];\n    G[0] = 1;\n    G[1] = 1;\n\n    for (int i = 2; i <= n; ++i)\n      for (int j = 0; j < i; ++j)\n        G[i] += G[j] * G[i - j - 1];\n\n    return G[n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numTrees(int n) {\n    // G[i] := # of unique BST's that store values 1..i\n    vector<int> G(n + 1);\n    G[0] = 1;\n    G[1] = 1;\n\n    for (int i = 2; i <= n; ++i)\n      for (int j = 0; j < i; ++j)\n        G[i] += G[j] * G[i - j - 1];\n\n    return G[n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/96.html",
    "category": "Algorithms",
    "acceptance_rate": 62.35452793516797,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 10668,
    "dislikes": 428,
    "similar_questions": "[{\"title\": \"Unique Binary Search Trees II\", \"titleSlug\": \"unique-binary-search-trees-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"756.8K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 756808, \"totalSubmissionRaw\": 1213719, \"acRate\": \"62.4%\"}",
    "title_pt": "Árvores Binárias de Busca Únicas",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>o número de </em><strong>BST&#39;</strong><em>s (árvores binárias de busca) estruturalmente únicas que têm exatamente </em><code>n</code><em> nós com valores únicos de</em> <code>1</code> <em>até</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg\" style=\"width: 600px; height: 148px;\" />\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 5\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 19</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "97",
    "paidOnly": false,
    "title": "Interleaving String",
    "titleSlug": "interleaving-string",
    "url": "https://leetcode.com/problems/interleaving-string",
    "description_url": "https://leetcode.com/problems/interleaving-string/description/",
    "description": "<p>Given strings <code>s1</code>, <code>s2</code>, and <code>s3</code>, find whether <code>s3</code> is formed by an <strong>interleaving</strong> of <code>s1</code> and <code>s2</code>.</p>\n\n<p>An <strong>interleaving</strong> of two strings <code>s</code> and <code>t</code> is a configuration where <code>s</code> and <code>t</code> are divided into <code>n</code> and <code>m</code> <span data-keyword=\"substring-nonempty\">substrings</span> respectively, such that:</p>\n\n<ul>\n\t<li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li>\n\t<li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li>\n\t<li><code>|n - m| &lt;= 1</code></li>\n\t<li>The <strong>interleaving</strong> is <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> or <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li>\n</ul>\n\n<p><strong>Note:</strong> <code>a + b</code> is the concatenation of strings <code>a</code> and <code>b</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg\" style=\"width: 561px; height: 203px;\" />\n<pre>\n<strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> One way to obtain s3 is:\nSplit s1 into s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, and s2 into s2 = &quot;dbbc&quot; + &quot;a&quot;.\nInterleaving the two splits, we get &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;.\nSince s3 can be obtained by interleaving s1 and s2, we return true.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Notice how it is impossible to interleave s2 with any other string to obtain s3.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot;\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= s3.length &lt;= 200</code></li>\n\t<li><code>s1</code>, <code>s2</code>, and <code>s3</code> consist of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve it using only <code>O(s2.length)</code> additional memory space?</p>\n",
    "solution_url": "https://leetcode.com/problems/interleaving-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n    m = len(s1)\n    n = len(s2)\n    if m + n != len(s3):\n      return False\n\n    # dp[i][j] := true if s3[0..i + j) is formed by the interleaving of\n    #             s1[0..i) and s2[0..j)\n    dp = [[False] * (n + 1) for _ in range(m + 1)]\n    dp[0][0] = True\n\n    for i in range(1, m + 1):\n      dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]\n\n    for j in range(1, n + 1):\n      dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]\n\n    for i in range(1, m + 1):\n      for j in range(1, n + 1):\n        dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or \\\n            (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1])\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isInterleave(String s1, String s2, String s3) {\n    final int m = s1.length();\n    final int n = s2.length();\n    if (m + n != s3.length())\n      return false;\n\n    // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of\n    //             s1[0..i) and s2[0..j)\n    boolean[][] dp = new boolean[m + 1][n + 1];\n    dp[0][0] = true;\n\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1);\n\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = dp[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) ||\n                   dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);\n\n    return dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isInterleave(string s1, string s2, string s3) {\n    const int m = s1.length();\n    const int n = s2.length();\n    if (m + n != s3.length())\n      return false;\n\n    // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of\n    //             s1[0..i) and s2[0..j)\n    vector<vector<bool>> dp(m + 1, vector<bool>(n + 1));\n    dp[0][0] = true;\n\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1];\n\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1];\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] ||\n                   dp[i][j - 1] && s2[j - 1] == s3[i + j - 1];\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/97.html",
    "category": "Algorithms",
    "acceptance_rate": 42.028952697829745,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 8515,
    "dislikes": 528,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"649.8K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 649783, \"totalSubmissionRaw\": 1546037, \"acRate\": \"42.0%\"}",
    "title_pt": "String Intercalada",
    "description_pt": "<p>Dadas as strings <code>s1</code>, <code>s2</code> e <code>s3</code>, descubra se <code>s3</code> é formada por uma <strong>intercalação</strong> de <code>s1</code> e <code>s2</code>.</p>\n\n<p>Uma <strong>intercalação</strong> de duas strings <code>s</code> e <code>t</code> é uma configuração na qual <code>s</code> e <code>t</code> são divididas em <code>n</code> e <code>m</code> <span data-keyword=\"substring-nonempty\">substrings</span>, respectivamente, de modo que:</p>\n\n<ul>\n\t<li><code>s = s<sub>1</sub> + s<sub>2</sub> + ... + s<sub>n</sub></code></li>\n\t<li><code>t = t<sub>1</sub> + t<sub>2</sub> + ... + t<sub>m</sub></code></li>\n\t<li><code>|n - m| &lt;= 1</code></li>\n\t<li>A <strong>intercalação</strong> é <code>s<sub>1</sub> + t<sub>1</sub> + s<sub>2</sub> + t<sub>2</sub> + s<sub>3</sub> + t<sub>3</sub> + ...</code> ou <code>t<sub>1</sub> + s<sub>1</sub> + t<sub>2</sub> + s<sub>2</sub> + t<sub>3</sub> + s<sub>3</sub> + ...</code></li>\n</ul>\n\n<p><strong>Nota:</strong> <code>a + b</code> é a concatenação das strings <code>a</code> e <code>b</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/02/interleave.jpg\" style=\"width: 561px; height: 203px;\" />\n<pre>\n<strong>Entrada:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbcbcac&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Uma forma de obter s3 é:\nDivida s1 em s1 = &quot;aa&quot; + &quot;bc&quot; + &quot;c&quot;, e s2 em s2 = &quot;dbbc&quot; + &quot;a&quot;.\nIntercalando as duas divisões, obtemos &quot;aa&quot; + &quot;dbbc&quot; + &quot;bc&quot; + &quot;a&quot; + &quot;c&quot; = &quot;aadbbcbcac&quot;.\nComo s3 pode ser obtida pela intercalação de s1 e s2, retornamos true.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;aabcc&quot;, s2 = &quot;dbbca&quot;, s3 = &quot;aadbbbaccc&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Observe como é impossível intercalar s2 com qualquer outra string para obter s3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;&quot;, s2 = &quot;&quot;, s3 = &quot;&quot;\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s1.length, s2.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= s3.length &lt;= 200</code></li>\n\t<li><code>s1</code>, <code>s2</code> e <code>s3</code> consistem de letras minúsculas do alfabeto inglês.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue resolvê-lo usando apenas <code>O(s2.length)</code> de espaço adicional na memória?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "98",
    "paidOnly": false,
    "title": "Validate Binary Search Tree",
    "titleSlug": "validate-binary-search-tree",
    "url": "https://leetcode.com/problems/validate-binary-search-tree",
    "description_url": "https://leetcode.com/problems/validate-binary-search-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p>\n\n<p>A <strong>valid BST</strong> is defined as follows:</p>\n\n<ul>\n\t<li>The left <span data-keyword=\"subtree\">subtree</span> of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li>\n\t<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li>\n\t<li>Both the left and right subtrees must also be binary search trees.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg\" style=\"width: 302px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [2,1,3]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg\" style=\"width: 422px; height: 292px;\" />\n<pre>\n<strong>Input:</strong> root = [5,1,4,null,null,3,6]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The root node&#39;s value is 5 but its right child&#39;s value is 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/validate-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isValidBST(self, root: Optional[TreeNode]) -> bool:\n    def isValidBST(root: Optional[TreeNode],\n                   minNode: Optional[TreeNode], maxNode: Optional[TreeNode]) -> bool:\n      if not root:\n        return True\n      if minNode and root.val <= minNode.val:\n        return False\n      if maxNode and root.val >= maxNode.val:\n        return False\n\n      return isValidBST(root.left, minNode, root) and \\\n          isValidBST(root.right, root, maxNode)\n\n    return isValidBST(root, None, None)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isValidBST(TreeNode root) {\n    return isValidBST(root, null, null);\n  }\n\n  private boolean isValidBST(TreeNode root, TreeNode minNode, TreeNode maxNode) {\n    if (root == null)\n      return true;\n    if (minNode != null && root.val <= minNode.val)\n      return false;\n    if (maxNode != null && root.val >= maxNode.val)\n      return false;\n\n    return isValidBST(root.left, minNode, root) &&\n           isValidBST(root.right, root, maxNode);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isValidBST(TreeNode* root) {\n    return isValidBST(root, nullptr, nullptr);\n  }\n\n private:\n  bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) {\n    if (root == nullptr)\n      return true;\n    if (minNode && root->val <= minNode->val)\n      return false;\n    if (maxNode && root->val >= maxNode->val)\n      return false;\n\n    return isValidBST(root->left, minNode, root) &&\n           isValidBST(root->right, root, maxNode);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/98.html",
    "category": "Algorithms",
    "acceptance_rate": 34.25135635093836,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 17551,
    "dislikes": 1408,
    "similar_questions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Mode in Binary Search Tree\", \"titleSlug\": \"find-mode-in-binary-search-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"8.3M\", \"totalAcceptedRaw\": 2830875, \"totalSubmissionRaw\": 8265005, \"acRate\": \"34.3%\"}",
    "title_pt": "Validar Árvore Binária de Busca",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, <em>determine se ela é uma árvore binária de busca (BST) válida</em>.</p>\n\n<p>Uma <strong>BST válida</strong> é definida da seguinte forma:</p>\n\n<ul>\n\t<li>A <span data-keyword=\"subtree\">subárvore</span> esquerda de um nó contém apenas nós com chaves <strong>menores que</strong> a chave do nó.</li>\n\t<li>A subárvore direita de um nó contém apenas nós com chaves <strong>maiores que</strong> a chave do nó.</li>\n\t<li>As subárvores esquerda e direita também devem ser árvores binárias de busca.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg\" style=\"width: 302px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,1,3]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg\" style=\"width: 422px; height: 292px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,1,4,null,null,3,6]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> O valor do nó raiz é 5, mas o valor de seu filho direito é 4.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "99",
    "paidOnly": false,
    "title": "Recover Binary Search Tree",
    "titleSlug": "recover-binary-search-tree",
    "url": "https://leetcode.com/problems/recover-binary-search-tree",
    "description_url": "https://leetcode.com/problems/recover-binary-search-tree/description/",
    "description": "<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [1,3,null,null,2]\n<strong>Output:</strong> [3,1,null,null,2]\n<strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg\" style=\"width: 581px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,1,4,null,null,2]\n<strong>Output:</strong> [2,1,4,null,null,3]\n<strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?",
    "solution_url": "https://leetcode.com/problems/recover-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def recoverTree(self, root: Optional[TreeNode]) -> None:\n    def swap(x: Optional[TreeNode], y: Optional[TreeNode]) -> None:\n      temp = x.val\n      x.val = y.val\n      y.val = temp\n\n    def inorder(root: Optional[TreeNode]) -> None:\n      if not root:\n        return\n\n      inorder(root.left)\n\n      if self.pred and root.val < self.pred.val:\n        self.y = root\n        if not self.x:\n          self.x = self.pred\n        else:\n          return\n      self.pred = root\n\n      inorder(root.right)\n\n    inorder(root)\n    swap(self.x, self.y)\n\n  pred = None\n  x = None  # 1st wrong node\n  y = None  # 2nd wrong node",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void recoverTree(TreeNode root) {\n    inorder(root);\n    swap(x, y);\n  }\n\n  private TreeNode pred = null;\n  private TreeNode x = null;\n  private TreeNode y = null;\n\n  private void inorder(TreeNode root) {\n    if (root == null)\n      return;\n\n    inorder(root.left);\n\n    if (pred != null && root.val < pred.val) {\n      y = root;\n      if (x == null)\n        x = pred;\n      else\n        return;\n    }\n    pred = root;\n\n    inorder(root.right);\n  }\n\n  private void swap(TreeNode x, TreeNode y) {\n    final int temp = x.val;\n    x.val = y.val;\n    y.val = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void recoverTree(TreeNode* root) {\n    inorder(root);\n    swap(x, y);\n  }\n\n private:\n  TreeNode* pred = nullptr;\n  TreeNode* x = nullptr;  // 1st wrong node\n  TreeNode* y = nullptr;  // 2nd wrond node\n\n  void inorder(TreeNode* root) {\n    if (root == nullptr)\n      return;\n\n    inorder(root->left);\n\n    if (pred && root->val < pred->val) {\n      y = root;\n      if (x == nullptr)\n        x = pred;\n      else\n        return;\n    }\n    pred = root;\n\n    inorder(root->right);\n  }\n\n  void swap(TreeNode* x, TreeNode* y) {\n    const int temp = x->val;\n    x->val = y->val;\n    y->val = temp;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/99.html",
    "category": "Algorithms",
    "acceptance_rate": 55.9961952299303,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8202,
    "dislikes": 267,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"539.8K\", \"totalSubmission\": \"964K\", \"totalAcceptedRaw\": 539824, \"totalSubmissionRaw\": 964038, \"acRate\": \"56.0%\"}",
    "title_pt": "Recuperar Árvore Binária de Busca",
    "description_pt": "<p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,3,null,null,2]\n<strong>Saída:</strong> [3,1,null,null,2]\n<strong>Explicação:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg\" style=\"width: 581px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,1,4,null,null,2]\n<strong>Saída:</strong> [2,1,4,null,null,3]\n<strong>Explicação:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "100",
    "paidOnly": false,
    "title": "Same Tree",
    "titleSlug": "same-tree",
    "url": "https://leetcode.com/problems/same-tree",
    "description_url": "https://leetcode.com/problems/same-tree/description/",
    "description": "<p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p>\n\n<p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg\" style=\"width: 622px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> p = [1,2,3], q = [1,2,3]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg\" style=\"width: 382px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> p = [1,2], q = [1,null,2]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg\" style=\"width: 622px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> p = [1,2,1], q = [1,1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/same-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n    if not p or not q:\n      return p == q\n    return p.val == q.val and \\\n        self.isSameTree(p.left, q.left) and \\\n        self.isSameTree(p.right, q.right)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isSameTree(TreeNode p, TreeNode q) {\n    if (p == null || q == null)\n      return p == q;\n    return p.val == q.val &&\n           isSameTree(p.left, q.left) &&\n           isSameTree(p.right, q.right);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isSameTree(TreeNode* p, TreeNode* q) {\n    if (!p || !q)\n      return p == q;\n    return p->val == q->val &&\n           isSameTree(p->left, q->left) &&\n           isSameTree(p->right, q->right);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/100.html",
    "category": "Algorithms",
    "acceptance_rate": 64.89753287118538,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 12159,
    "dislikes": 263,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 2773690, \"totalSubmissionRaw\": 4273953, \"acRate\": \"64.9%\"}",
    "title_pt": "Mesma Árvore",
    "description_pt": "<p>Dadas as raízes de duas árvores binárias <code>p</code> e <code>q</code>, escreva uma função para verificar se elas são iguais ou não.</p>\n\n<p>Duas árvores binárias são consideradas iguais se forem estruturalmente idênticas, e os nós tiverem o mesmo valor.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg\" style=\"width: 622px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> p = [1,2,3], q = [1,2,3]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg\" style=\"width: 382px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> p = [1,2], q = [1,null,2]\n<strong>Saída:</strong> false\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg\" style=\"width: 622px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> p = [1,2,1], q = [1,1,2]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em ambas as árvores está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "101",
    "paidOnly": false,
    "title": "Symmetric Tree",
    "titleSlug": "symmetric-tree",
    "url": "https://leetcode.com/problems/symmetric-tree",
    "description_url": "https://leetcode.com/problems/symmetric-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg\" style=\"width: 354px; height: 291px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,2,3,4,4,3]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg\" style=\"width: 308px; height: 258px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,2,null,3,null,3]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it both recursively and iteratively?",
    "solution_url": "https://leetcode.com/problems/symmetric-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n    def isSymmetric(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n      if not p or not q:\n        return p == q\n\n      return p.val == q.val and \\\n          isSymmetric(p.left, q.right) and \\\n          isSymmetric(p.right, q.left)\n\n    return isSymmetric(root, root)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isSymmetric(TreeNode root) {\n    return isSymmetric(root, root);\n  }\n\n  private boolean isSymmetric(TreeNode p, TreeNode q) {\n    if (p == null || q == null)\n      return p == q;\n\n    return p.val == q.val && isSymmetric(p.left, q.right) && isSymmetric(p.right, q.left);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isSymmetric(TreeNode* root) {\n    return isSymmetric(root, root);\n  }\n\n private:\n  bool isSymmetric(TreeNode* p, TreeNode* q) {\n    if (!p || !q)\n      return p == q;\n\n    return p->val == q->val &&\n           isSymmetric(p->left, q->right) &&\n           isSymmetric(p->right, q->left);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/101.html",
    "category": "Algorithms",
    "acceptance_rate": 59.06521613495559,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 16040,
    "dislikes": 414,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"2.4M\", \"totalSubmission\": \"4.1M\", \"totalAcceptedRaw\": 2432404, \"totalSubmissionRaw\": 4118174, \"acRate\": \"59.1%\"}",
    "title_pt": "Árvore Simétrica",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, <em>verifique se ela é um espelho de si mesma</em> (isto é, simétrica em torno de seu centro).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg\" style=\"width: 354px; height: 291px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,2,3,4,4,3]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg\" style=\"width: 308px; height: 258px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,2,null,3,null,3]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 1000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue resolvê-lo tanto recursivamente quanto iterativamente?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "102",
    "paidOnly": false,
    "title": "Binary Tree Level Order Traversal",
    "titleSlug": "binary-tree-level-order-traversal",
    "url": "https://leetcode.com/problems/binary-tree-level-order-traversal",
    "description_url": "https://leetcode.com/problems/binary-tree-level-order-traversal/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [[3],[9,20],[15,7]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-level-order-traversal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n    if not root:\n      return []\n\n    ans = []\n    q = deque([root])\n\n    while q:\n      currLevel = []\n      for _ in range(len(q)):\n        node = q.popleft()\n        currLevel.append(node.val)\n        if node.left:\n          q.append(node.left)\n        if node.right:\n          q.append(node.right)\n      ans.append(currLevel)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> levelOrder(TreeNode root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<List<Integer>> ans = new ArrayList<>();\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      List<Integer> currLevel = new ArrayList<>();\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode node = q.poll();\n        currLevel.add(node.val);\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n      }\n      ans.add(currLevel);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> levelOrder(TreeNode* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<vector<int>> ans;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      vector<int> currLevel;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode* node = q.front();\n        q.pop();\n        currLevel.push_back(node->val);\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n      }\n      ans.push_back(currLevel);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/102.html",
    "category": "Algorithms",
    "acceptance_rate": 70.33556426582695,
    "topics": [
      "Tree",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [
      "Use a queue to perform BFS."
    ],
    "likes": 16132,
    "dislikes": 345,
    "similar_questions": "[{\"title\": \"Binary Tree Zigzag Level Order Traversal\", \"titleSlug\": \"binary-tree-zigzag-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Level Order Traversal II\", \"titleSlug\": \"binary-tree-level-order-traversal-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Depth of Binary Tree\", \"titleSlug\": \"minimum-depth-of-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Vertical Order Traversal\", \"titleSlug\": \"binary-tree-vertical-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Average of Levels in Binary Tree\", \"titleSlug\": \"average-of-levels-in-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Level Order Traversal\", \"titleSlug\": \"n-ary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Cousins in Binary Tree\", \"titleSlug\": \"cousins-in-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Sort a Binary Tree by Level\", \"titleSlug\": \"minimum-number-of-operations-to-sort-a-binary-tree-by-level\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Divide Nodes Into the Maximum Number of Groups\", \"titleSlug\": \"divide-nodes-into-the-maximum-number-of-groups\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 2800020, \"totalSubmissionRaw\": 3980953, \"acRate\": \"70.3%\"}",
    "title_pt": "Travessia em Ordem de Nível de Árvore Binária",
    "description_pt": "<p>Dado o <code>root</code> de uma árvore binária, retorne <em>a travessia em ordem de nível dos valores dos seus nós</em>. (isto é, da esquerda para a direita, nível por nível).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> [[3],[9,20],[15,7]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 2000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Use uma fila para realizar BFS."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "103",
    "paidOnly": false,
    "title": "Binary Tree Zigzag Level Order Traversal",
    "titleSlug": "binary-tree-zigzag-level-order-traversal",
    "url": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal",
    "description_url": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the zigzag level order traversal of its nodes&#39; values</em>. (i.e., from left to right, then right to left for the next level and alternate between).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [[3],[20,9],[15,7]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n    if not root:\n      return []\n\n    ans = []\n    q = deque([root])\n    isLeftToRight = True\n\n    while q:\n      currLevel = []\n      for _ in range(len(q)):\n        if isLeftToRight:\n          node = q.popleft()\n          currLevel.append(node.val)\n          if node.left:\n            q.append(node.left)\n          if node.right:\n            q.append(node.right)\n        else:\n          node = q.pop()\n          currLevel.append(node.val)\n          if node.right:\n            q.appendleft(node.right)\n          if node.left:\n            q.appendleft(node.left)\n      ans.append(currLevel)\n      isLeftToRight = not isLeftToRight\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> zigzagLevelOrder(TreeNode root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<List<Integer>> ans = new ArrayList<>();\n    Deque<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n    boolean isLeftToRight = true;\n\n    while (!q.isEmpty()) {\n      List<Integer> currLevel = new ArrayList<>();\n      for (int sz = q.size(); sz > 0; --sz)\n        if (isLeftToRight) {\n          TreeNode node = q.pollFirst();\n          currLevel.add(node.val);\n          if (node.left != null)\n            q.addLast(node.left);\n          if (node.right != null)\n            q.addLast(node.right);\n        } else {\n          TreeNode node = q.pollLast();\n          currLevel.add(node.val);\n          if (node.right != null)\n            q.addFirst(node.right);\n          if (node.left != null)\n            q.addFirst(node.left);\n        }\n      ans.add(currLevel);\n      isLeftToRight = !isLeftToRight;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> zigzagLevelOrder(TreeNode* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<vector<int>> ans;\n    deque<TreeNode*> q{{root}};\n    bool isLeftToRight = true;\n\n    while (!q.empty()) {\n      vector<int> currLevel;\n      for (int sz = q.size(); sz > 0; --sz)\n        if (isLeftToRight) {\n          TreeNode* node = q.front();\n          q.pop_front();\n          currLevel.push_back(node->val);\n          if (node->left)\n            q.push_back(node->left);\n          if (node->right)\n            q.push_back(node->right);\n        } else {\n          TreeNode* node = q.back();\n          q.pop_back();\n          currLevel.push_back(node->val);\n          if (node->right)\n            q.push_front(node->right);\n          if (node->left)\n            q.push_front(node->left);\n        }\n      ans.push_back(currLevel);\n      isLeftToRight = !isLeftToRight;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/103.html",
    "category": "Algorithms",
    "acceptance_rate": 61.4461237779013,
    "topics": [
      "Tree",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 11384,
    "dislikes": 331,
    "similar_questions": "[{\"title\": \"Binary Tree Level Order Traversal\", \"titleSlug\": \"binary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Grid Traversal With Skip\", \"titleSlug\": \"zigzag-grid-traversal-with-skip\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1466938, \"totalSubmissionRaw\": 2387366, \"acRate\": \"61.4%\"}",
    "title_pt": "Travessia Ziguezague por Nível de Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a travessia em ordem de nível em zigue-zague dos valores de seus nós</em>. (isto é, da esquerda para a direita, depois da direita para a esquerda para o próximo nível, alternando entre eles).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> [[3],[20,9],[15,7]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 2000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "104",
    "paidOnly": false,
    "title": "Maximum Depth of Binary Tree",
    "titleSlug": "maximum-depth-of-binary-tree",
    "url": "https://leetcode.com/problems/maximum-depth-of-binary-tree",
    "description_url": "https://leetcode.com/problems/maximum-depth-of-binary-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p>\n\n<p>A binary tree&#39;s <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg\" style=\"width: 400px; height: 277px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,2]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-depth-of-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxDepth(self, root: Optional[TreeNode]) -> int:\n    if not root:\n      return 0\n    return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxDepth(TreeNode root) {\n    if (root == null)\n      return 0;\n    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxDepth(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    return 1 + max(maxDepth(root->left), maxDepth(root->right));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/104.html",
    "category": "Algorithms",
    "acceptance_rate": 77.01293798488177,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 13511,
    "dislikes": 262,
    "similar_questions": "[{\"title\": \"Balanced Binary Tree\", \"titleSlug\": \"balanced-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Depth of Binary Tree\", \"titleSlug\": \"minimum-depth-of-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Depth of N-ary Tree\", \"titleSlug\": \"maximum-depth-of-n-ary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Time Needed to Inform All Employees\", \"titleSlug\": \"time-needed-to-inform-all-employees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Amount of Time for Binary Tree to Be Infected\", \"titleSlug\": \"amount-of-time-for-binary-tree-to-be-infected\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Height of Binary Tree After Subtree Removal Queries\", \"titleSlug\": \"height-of-binary-tree-after-subtree-removal-queries\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.9M\", \"totalSubmission\": \"5.1M\", \"totalAcceptedRaw\": 3947331, \"totalSubmissionRaw\": 5125551, \"acRate\": \"77.0%\"}",
    "title_pt": "Máxima Profundidade de uma Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>sua profundidade máxima</em>.</p>\n\n<p>A <strong>profundidade máxima</strong>&nbsp;de uma árvore binária é o número de nós ao longo do caminho mais longo da raiz até o nó folha mais distante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg\" style=\"width: 400px; height: 277px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,2]\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "105",
    "paidOnly": false,
    "title": "Construct Binary Tree from Preorder and Inorder Traversal",
    "titleSlug": "construct-binary-tree-from-preorder-and-inorder-traversal",
    "url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal",
    "description_url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/",
    "description": "<p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\n<strong>Output:</strong> [3,9,20,null,null,15,7]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> preorder = [-1], inorder = [-1]\n<strong>Output:</strong> [-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= preorder.length &lt;= 3000</code></li>\n\t<li><code>inorder.length == preorder.length</code></li>\n\t<li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li>\n\t<li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li>\n\t<li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li>\n\t<li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li>\n\t<li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:\n    inToIndex = {num: i for i, num in enumerate(inorder)}\n\n    def build(preStart: int, preEnd: int, inStart: int, inEnd: int) -> Optional[TreeNode]:\n      if preStart > preEnd:\n        return None\n\n      rootVal = preorder[preStart]\n      rootInIndex = inToIndex[rootVal]\n      leftSize = rootInIndex - inStart\n\n      root = TreeNode(rootVal)\n      root.left = build(preStart + 1, preStart + leftSize,\n                        inStart, rootInIndex - 1)\n      root.right = build(preStart + leftSize + 1,\n                         preEnd, rootInIndex + 1, inEnd)\n      return root\n\n    return build(0, len(preorder) - 1, 0, len(inorder) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode buildTree(int[] preorder, int[] inorder) {\n    Map<Integer, Integer> inToIndex = new HashMap<>();\n\n    for (int i = 0; i < inorder.length; ++i)\n      inToIndex.put(inorder[i], i);\n\n    return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, inToIndex);\n  }\n\n  private TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart,\n                         int inEnd, Map<Integer, Integer> inToIndex) {\n    if (preStart > preEnd)\n      return null;\n\n    final int rootVal = preorder[preStart];\n    final int rootInIndex = inToIndex.get(rootVal);\n    final int leftSize = rootInIndex - inStart;\n\n    TreeNode root = new TreeNode(rootVal);\n    root.left = build(preorder, preStart + 1, preStart + leftSize, inorder, inStart,\n                      rootInIndex - 1, inToIndex);\n    root.right = build(preorder, preStart + leftSize + 1, preEnd, inorder, rootInIndex + 1, inEnd,\n                       inToIndex);\n\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n    unordered_map<int, int> inToIndex;\n\n    for (int i = 0; i < inorder.size(); ++i)\n      inToIndex[inorder[i]] = i;\n\n    return build(preorder, 0, preorder.size() - 1, inorder, 0,\n                 inorder.size() - 1, inToIndex);\n  }\n\n private:\n  TreeNode* build(const vector<int>& preorder, int preStart, int preEnd,\n                  const vector<int>& inorder, int inStart, int inEnd,\n                  const unordered_map<int, int>& inToIndex) {\n    if (preStart > preEnd)\n      return nullptr;\n\n    const int rootVal = preorder[preStart];\n    const int rootInIndex = inToIndex.at(rootVal);\n    const int leftSize = rootInIndex - inStart;\n\n    TreeNode* root = new TreeNode(rootVal);\n    root->left = build(preorder, preStart + 1, preStart + leftSize, inorder,\n                       inStart, rootInIndex - 1, inToIndex);\n    root->right = build(preorder, preStart + leftSize + 1, preEnd, inorder,\n                        rootInIndex + 1, inEnd, inToIndex);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/105.html",
    "category": "Algorithms",
    "acceptance_rate": 66.59871435839734,
    "topics": [
      "Array",
      "Hash Table",
      "Divide and Conquer",
      "Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 15822,
    "dislikes": 577,
    "similar_questions": "[{\"title\": \"Construct Binary Tree from Inorder and Postorder Traversal\", \"titleSlug\": \"construct-binary-tree-from-inorder-and-postorder-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1547193, \"totalSubmissionRaw\": 2323165, \"acRate\": \"66.6%\"}",
    "title_pt": "Construir Árvore Binária a partir das Percursos em Preordem e Emordem",
    "description_pt": "<p>Dados dois arrays de inteiros <code>preorder</code> e <code>inorder</code>, onde <code>preorder</code> é o percurso em preordem de uma árvore binária e <code>inorder</code> é o percurso em ordem da mesma árvore, construa e retorne <em>a árvore binária</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\n<strong>Saída:</strong> [3,9,20,null,null,15,7]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> preorder = [-1], inorder = [-1]\n<strong>Saída:</strong> [-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= preorder.length &lt;= 3000</code></li>\n\t<li><code>inorder.length == preorder.length</code></li>\n\t<li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li>\n\t<li><code>preorder</code> e <code>inorder</code> consistem em valores <strong>únicos</strong>.</li>\n\t<li>Cada valor de <code>inorder</code> também aparece em <code>preorder</code>.</li>\n\t<li><code>preorder</code> é <strong>garantido</strong> ser o percurso em preordem da árvore.</li>\n\t<li><code>inorder</code> é <strong>garantido</strong> ser o percurso em ordem da árvore.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "106",
    "paidOnly": false,
    "title": "Construct Binary Tree from Inorder and Postorder Traversal",
    "titleSlug": "construct-binary-tree-from-inorder-and-postorder-traversal",
    "url": "https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal",
    "description_url": "https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/",
    "description": "<p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\n<strong>Output:</strong> [3,9,20,null,null,15,7]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> inorder = [-1], postorder = [-1]\n<strong>Output:</strong> [-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= inorder.length &lt;= 3000</code></li>\n\t<li><code>postorder.length == inorder.length</code></li>\n\t<li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li>\n\t<li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li>\n\t<li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li>\n\t<li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li>\n\t<li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n    inToIndex = {num: i for i, num in enumerate(inorder)}\n\n    def build(inStart: int, inEnd: int, postStart: int, postEnd: int) -> Optional[TreeNode]:\n      if inStart > inEnd:\n        return None\n\n      rootVal = postorder[postEnd]\n      rootInIndex = inToIndex[rootVal]\n      leftSize = rootInIndex - inStart\n\n      root = TreeNode(rootVal)\n      root.left = build(inStart, rootInIndex - 1,  postStart,\n                        postStart + leftSize - 1)\n      root.right = build(rootInIndex + 1, inEnd,  postStart + leftSize,\n                         postEnd - 1)\n      return root\n\n    return build(0, len(inorder) - 1, 0, len(postorder) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode buildTree(int[] inorder, int[] postorder) {\n    Map<Integer, Integer> inToIndex = new HashMap<>();\n\n    for (int i = 0; i < inorder.length; ++i)\n      inToIndex.put(inorder[i], i);\n\n    return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, inToIndex);\n  }\n\n  TreeNode build(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd,\n                 Map<Integer, Integer> inToIndex) {\n    if (inStart > inEnd)\n      return null;\n\n    final int rootVal = postorder[postEnd];\n    final int rootInIndex = inToIndex.get(rootVal);\n    final int leftSize = rootInIndex - inStart;\n\n    TreeNode root = new TreeNode(rootVal);\n    root.left = build(inorder, inStart, rootInIndex - 1, postorder, postStart,\n                      postStart + leftSize - 1, inToIndex);\n    root.right = build(inorder, rootInIndex + 1, inEnd, postorder, postStart + leftSize,\n                       postEnd - 1, inToIndex);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {\n    unordered_map<int, int> inToIndex;\n\n    for (int i = 0; i < inorder.size(); ++i)\n      inToIndex[inorder[i]] = i;\n\n    return build(inorder, 0, inorder.size() - 1, postorder, 0,\n                 postorder.size() - 1, inToIndex);\n  }\n\n private:\n  TreeNode* build(const vector<int>& inorder, int inStart, int inEnd,\n                  const vector<int>& postorder, int postStart, int postEnd,\n                  const unordered_map<int, int>& inToIndex) {\n    if (inStart > inEnd)\n      return nullptr;\n\n    const int rootVal = postorder[postEnd];\n    const int rootInIndex = inToIndex.at(rootVal);\n    const int leftSize = rootInIndex - inStart;\n\n    TreeNode* root = new TreeNode(rootVal);\n    root->left = build(inorder, inStart, rootInIndex - 1, postorder, postStart,\n                       postStart + leftSize - 1, inToIndex);\n    root->right = build(inorder, rootInIndex + 1, inEnd, postorder,\n                        postStart + leftSize, postEnd - 1, inToIndex);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/106.html",
    "category": "Algorithms",
    "acceptance_rate": 65.76414282864023,
    "topics": [
      "Array",
      "Hash Table",
      "Divide and Conquer",
      "Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8365,
    "dislikes": 142,
    "similar_questions": "[{\"title\": \"Construct Binary Tree from Preorder and Inorder Traversal\", \"titleSlug\": \"construct-binary-tree-from-preorder-and-inorder-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"794.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 794371, \"totalSubmissionRaw\": 1207909, \"acRate\": \"65.8%\"}",
    "title_pt": "Construir Árvore Binária a Partir das Traversais Inorder e Postorder",
    "description_pt": "<p>Dadas dois arrays inteiros <code>inorder</code> e <code>postorder</code>, em que <code>inorder</code> é a travessia inorder de uma árvore binária e <code>postorder</code> é a travessia postorder da mesma árvore, construa e retorne <em>a árvore binária</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\n<strong>Saída:</strong> [3,9,20,null,null,15,7]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> inorder = [-1], postorder = [-1]\n<strong>Saída:</strong> [-1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= inorder.length &lt;= 3000</code></li>\n\t<li><code>postorder.length == inorder.length</code></li>\n\t<li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li>\n\t<li><code>inorder</code> e <code>postorder</code> consistem de valores <strong>únicos</strong>.</li>\n\t<li>Cada valor de <code>postorder</code> também aparece em <code>inorder</code>.</li>\n\t<li><code>inorder</code> tem sua travessia inorder da árvore <strong>garantida</strong>.</li>\n\t<li><code>postorder</code> tem sua travessia postorder da árvore <strong>garantida</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "107",
    "paidOnly": false,
    "title": "Binary Tree Level Order Traversal II",
    "titleSlug": "binary-tree-level-order-traversal-ii",
    "url": "https://leetcode.com/problems/binary-tree-level-order-traversal-ii",
    "description_url": "https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the bottom-up level order traversal of its nodes&#39; values</em>. (i.e., from left to right, level by level from leaf to root).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [[15,7],[9,20],[3]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-level-order-traversal-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:\n    if not root:\n      return []\n\n    ans = []\n    q = deque([root])\n\n    while q:\n      currLevel = []\n      for _ in range(len(q)):\n        node = q.popleft()\n        currLevel.append(node.val)\n        if node.left:\n          q.append(node.left)\n        if node.right:\n          q.append(node.right)\n      ans.append(currLevel)\n\n    return ans[::-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> levelOrderBottom(TreeNode root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<List<Integer>> ans = new ArrayList<>();\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      List<Integer> currLevel = new ArrayList<>();\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode node = q.poll();\n        currLevel.add(node.val);\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n      }\n      ans.add(currLevel);\n    }\n\n    Collections.reverse(ans);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> levelOrderBottom(TreeNode* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<vector<int>> ans;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      vector<int> currLevel;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode* node = q.front();\n        q.pop();\n        currLevel.push_back(node->val);\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n      }\n      ans.push_back(currLevel);\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/107.html",
    "category": "Algorithms",
    "acceptance_rate": 65.8038982064003,
    "topics": [
      "Tree",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5008,
    "dislikes": 326,
    "similar_questions": "[{\"title\": \"Binary Tree Level Order Traversal\", \"titleSlug\": \"binary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Average of Levels in Binary Tree\", \"titleSlug\": \"average-of-levels-in-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"731.2K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 731231, \"totalSubmissionRaw\": 1111228, \"acRate\": \"65.8%\"}",
    "title_pt": "Travessia de Nível de Árvore Binária de Baixo para Cima",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a travessia em ordem de nível de baixo para cima dos valores de seus nós</em>. (isto é, da esquerda para a direita, nível por nível da folha até a raiz).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> [[15,7],[9,20],[3]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 2000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "108",
    "paidOnly": false,
    "title": "Convert Sorted Array to Binary Search Tree",
    "titleSlug": "convert-sorted-array-to-binary-search-tree",
    "url": "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree",
    "description_url": "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/",
    "description": "<p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword=\"height-balanced\"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg\" style=\"width: 302px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> nums = [-10,-3,0,5,9]\n<strong>Output:</strong> [0,-3,9,-10,null,5]\n<strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg\" style=\"width: 302px; height: 222px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree.jpg\" style=\"width: 342px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> nums = [1,3]\n<strong>Output:</strong> [3,1]\n<strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:\n    def build(l: int, r: int) -> Optional[TreeNode]:\n      if l > r:\n        return None\n\n      m = (l + r) // 2\n      return TreeNode(nums[m],\n                      build(l, m - 1),\n                      build(m + 1, r))\n\n    return build(0, len(nums) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode sortedArrayToBST(int[] nums) {\n    return build(nums, 0, nums.length - 1);\n  }\n\n  private TreeNode build(int[] nums, int l, int r) {\n    if (l > r)\n      return null;\n\n    final int m = (l + r) / 2;\n    return new TreeNode(nums[m],\n                        build(nums, l, m - 1),\n                        build(nums, m + 1, r));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* sortedArrayToBST(vector<int>& nums) {\n    return build(nums, 0, nums.size() - 1);\n  }\n\n private:\n  TreeNode* build(const vector<int>& nums, int l, int r) {\n    if (l > r)\n      return nullptr;\n\n    const int m = (l + r) / 2;\n    return new TreeNode(nums[m],\n                        build(nums, l, m - 1),\n                        build(nums, m + 1, r));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/108.html",
    "category": "Algorithms",
    "acceptance_rate": 73.918163426827,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 11434,
    "dislikes": 601,
    "similar_questions": "[{\"title\": \"Convert Sorted List to Binary Search Tree\", \"titleSlug\": \"convert-sorted-list-to-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1464441, \"totalSubmissionRaw\": 1981166, \"acRate\": \"73.9%\"}",
    "title_pt": "Converter Array Ordenado em Árvore Binária de Busca",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> cujos elementos estão ordenados em <strong>ordem crescente</strong>, converta <em>ele em uma </em><span data-keyword=\"height-balanced\"><strong><em>height-balanced</em></strong></span> <em>árvore binária de busca</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg\" style=\"width: 302px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [-10,-3,0,5,9]\n<strong>Saída:</strong> [0,-3,9,-10,null,5]\n<strong>Explicação:</strong> [0,-10,5,null,-3,null,9] também é aceito:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg\" style=\"width: 302px; height: 222px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/18/btree.jpg\" style=\"width: 342px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [1,3]\n<strong>Saída:</strong> [3,1]\n<strong>Explicação:</strong> [1,null,3] e [3,1] são ambas BSTs height-balanced.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> está ordenado em ordem <strong>estritamente crescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "109",
    "paidOnly": false,
    "title": "Convert Sorted List to Binary Search Tree",
    "titleSlug": "convert-sorted-list-to-binary-search-tree",
    "url": "https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree",
    "description_url": "https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list where elements are sorted in <strong>ascending order</strong>, convert <em>it to a </em><span data-keyword=\"height-balanced\"><strong><em>height-balanced</em></strong></span> <em>binary search tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/linked.jpg\" style=\"width: 500px; height: 388px;\" />\n<pre>\n<strong>Input:</strong> head = [-10,-3,0,5,9]\n<strong>Output:</strong> [0,-3,9,-10,null,5]\n<strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in <code>head</code> is in the range <code>[0, 2 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def sortedListToBST(self, head: ListNode) -> TreeNode:\n    def findMid(head: ListNode) -> ListNode:\n      prev = None\n      slow = head\n      fast = head\n\n      while fast and fast.next:\n        prev = slow\n        slow = slow.next\n        fast = fast.next.next\n      prev.next = None\n\n      return slow\n\n    if not head:\n      return None\n    if not head.next:\n      return TreeNode(head.val)\n\n    mid = findMid(head)\n    root = TreeNode(mid.val)\n    root.left = self.sortedListToBST(head)\n    root.right = self.sortedListToBST(mid.next)\n\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode sortedListToBST(ListNode head) {\n    if (head == null)\n      return null;\n    if (head.next == null)\n      return new TreeNode(head.val);\n\n    ListNode mid = findMid(head);\n    TreeNode root = new TreeNode(mid.val);\n    root.left = sortedListToBST(head);\n    root.right = sortedListToBST(mid.next);\n\n    return root;\n  }\n\n  private ListNode findMid(ListNode head) {\n    ListNode prev = null;\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (fast != null && fast.next != null) {\n      prev = slow;\n      slow = slow.next;\n      fast = fast.next.next;\n    }\n    prev.next = null;\n\n    return slow;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* sortedListToBST(ListNode* head) {\n    if (head == nullptr)\n      return nullptr;\n    if (!head->next)\n      return new TreeNode(head->val);\n\n    ListNode* mid = findMid(head);\n    TreeNode* root = new TreeNode(mid->val);\n    root->left = sortedListToBST(head);\n    root->right = sortedListToBST(mid->next);\n\n    return root;\n  }\n\n private:\n  ListNode* findMid(ListNode* head) {\n    ListNode* prev = nullptr;\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (fast && fast->next) {\n      prev = slow;\n      slow = slow->next;\n      fast = fast->next->next;\n    }\n    prev->next = nullptr;\n\n    return slow;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/109.html",
    "category": "Algorithms",
    "acceptance_rate": 64.28284940157447,
    "topics": [
      "Linked List",
      "Divide and Conquer",
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 7654,
    "dislikes": 167,
    "similar_questions": "[{\"title\": \"Convert Sorted Array to Binary Search Tree\", \"titleSlug\": \"convert-sorted-array-to-binary-search-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Create Binary Tree From Descriptions\", \"titleSlug\": \"create-binary-tree-from-descriptions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"602.6K\", \"totalSubmission\": \"937.5K\", \"totalAcceptedRaw\": 602625, \"totalSubmissionRaw\": 937459, \"acRate\": \"64.3%\"}",
    "title_pt": "Converter Lista Encadeada Ordenada em Árvore Binária de Busca",
    "description_pt": "<p>Dada a <code>head</code> de uma lista encadeada simplesmente ligada em que os elementos estão ordenados em <strong>ordem crescente</strong>, converta <em>isso em uma </em><span data-keyword=\"height-balanced\"><strong><em>height-balanced</em></strong></span> <em>árvore binária de busca</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/17/linked.jpg\" style=\"width: 500px; height: 388px;\" />\n<pre>\n<strong>Entrada:</strong> head = [-10,-3,0,5,9]\n<strong>Saída:</strong> [0,-3,9,-10,null,5]\n<strong>Explicação:</strong> Uma resposta possível é [0,-3,9,-10,null,5], que representa a BST height-balanced mostrada.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em <code>head</code> está no intervalo <code>[0, 2 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "110",
    "paidOnly": false,
    "title": "Balanced Binary Tree",
    "titleSlug": "balanced-binary-tree",
    "url": "https://leetcode.com/problems/balanced-binary-tree",
    "description_url": "https://leetcode.com/problems/balanced-binary-tree/description/",
    "description": "<p>Given a binary tree, determine if it is <span data-keyword=\"height-balanced\"><strong>height-balanced</strong></span>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg\" style=\"width: 342px; height: 221px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg\" style=\"width: 452px; height: 301px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,2,3,3,null,null,4,4]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/balanced-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isBalanced(self, root: Optional[TreeNode]) -> bool:\n    if not root:\n      return True\n\n    def maxDepth(root: Optional[TreeNode]) -> int:\n      if not root:\n        return 0\n      return 1 + max(maxDepth(root.left), maxDepth(root.right))\n\n    return abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 and \\\n        self.isBalanced(root.left) and self.isBalanced(root.right)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isBalanced(TreeNode root) {\n    if (root == null)\n      return true;\n    return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&\n           isBalanced(root.left) &&\n           isBalanced(root.right);\n  }\n\n  private int maxDepth(TreeNode root) {\n    if (root == null)\n      return 0;\n    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isBalanced(TreeNode* root) {\n    if (root == nullptr)\n      return true;\n    return abs(maxDepth(root->left) - maxDepth(root->right)) <= 1 &&\n           isBalanced(root->left) && isBalanced(root->right);\n  }\n\n private:\n  int maxDepth(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    return 1 + max(maxDepth(root->left), maxDepth(root->right));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/110.html",
    "category": "Algorithms",
    "acceptance_rate": 55.08700639142806,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 11331,
    "dislikes": 764,
    "similar_questions": "[{\"title\": \"Maximum Depth of Binary Tree\", \"titleSlug\": \"maximum-depth-of-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"K-th Largest Perfect Subtree Size in Binary Tree\", \"titleSlug\": \"k-th-largest-perfect-subtree-size-in-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check Balanced String\", \"titleSlug\": \"check-balanced-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 1920103, \"totalSubmissionRaw\": 3485581, \"acRate\": \"55.1%\"}",
    "title_pt": "Árvore Binária Balanceada",
    "description_pt": "<p>Dada uma árvore binária, determine se ela é <span data-keyword=\"height-balanced\"><strong>balanceada em altura</strong></span>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg\" style=\"width: 342px; height: 221px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/06/balance_2.jpg\" style=\"width: 452px; height: 301px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,2,3,3,null,null,4,4]\n<strong>Saída:</strong> false\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 5000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "111",
    "paidOnly": false,
    "title": "Minimum Depth of Binary Tree",
    "titleSlug": "minimum-depth-of-binary-tree",
    "url": "https://leetcode.com/problems/minimum-depth-of-binary-tree",
    "description_url": "https://leetcode.com/problems/minimum-depth-of-binary-tree/description/",
    "description": "<p>Given a binary tree, find its minimum depth.</p>\n\n<p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p>\n\n<p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg\" style=\"width: 432px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6]\n<strong>Output:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-depth-of-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minDepth(self, root: Optional[TreeNode]) -> int:\n    if not root:\n      return 0\n    if not root.left:\n      return self.minDepth(root.right) + 1\n    if not root.right:\n      return self.minDepth(root.left) + 1\n    return min(self.minDepth(root.left), self.minDepth(root.right)) + 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minDepth(TreeNode root) {\n    if (root == null)\n      return 0;\n    if (root.left == null)\n      return minDepth(root.right) + 1;\n    if (root.right == null)\n      return minDepth(root.left) + 1;\n    return Math.min(minDepth(root.left), minDepth(root.right)) + 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minDepth(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    if (root->left == nullptr)\n      return minDepth(root->right) + 1;\n    if (root->right == nullptr)\n      return minDepth(root->left) + 1;\n    return min(minDepth(root->left), minDepth(root->right)) + 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/111.html",
    "category": "Algorithms",
    "acceptance_rate": 50.45012217677971,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 7544,
    "dislikes": 1339,
    "similar_questions": "[{\"title\": \"Binary Tree Level Order Traversal\", \"titleSlug\": \"binary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Depth of Binary Tree\", \"titleSlug\": \"maximum-depth-of-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.8M\", \"totalAcceptedRaw\": 1421909, \"totalSubmissionRaw\": 2818449, \"acRate\": \"50.5%\"}",
    "title_pt": "Profundidade Mínima de uma Árvore Binária",
    "description_pt": "<p>Dada uma árvore binária, encontre sua profundidade mínima.</p>\n\n<p>A profundidade mínima é o número de nós ao longo do caminho mais curto da raiz até o nó folha mais próximo.</p>\n\n<p><strong>Nota:</strong>&nbsp;Uma folha é um nó sem filhos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg\" style=\"width: 432px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [2,null,3,null,4,null,5,null,6]\n<strong>Saída:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "112",
    "paidOnly": false,
    "title": "Path Sum",
    "titleSlug": "path-sum",
    "url": "https://leetcode.com/problems/path-sum",
    "description_url": "https://leetcode.com/problems/path-sum/description/",
    "description": "<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p>\n\n<p>A <strong>leaf</strong> is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg\" style=\"width: 500px; height: 356px;\" />\n<pre>\n<strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The root-to-leaf path with the target sum is shown.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3], targetSum = 5\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There are two root-to-leaf paths in the tree:\n(1 --&gt; 2): The sum is 3.\n(1 --&gt; 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [], targetSum = 0\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/path-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def hasPathSum(self, root: TreeNode, summ: int) -> bool:\n    if not root:\n      return False\n    if root.val == summ and not root.left and not root.right:\n      return True\n    return self.hasPathSum(root.left, summ - root.val) or \\\n        self.hasPathSum(root.right, summ - root.val)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean hasPathSum(TreeNode root, int sum) {\n    if (root == null)\n      return false;\n    if (root.val == sum && root.left == null && root.right == null)\n      return true;\n    return hasPathSum(root.left, sum - root.val) ||\n           hasPathSum(root.right, sum - root.val);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool hasPathSum(TreeNode* root, int sum) {\n    if (root == nullptr)\n      return false;\n    if (root->val == sum && root->left == nullptr && root->right == nullptr)\n      return true;\n    return hasPathSum(root->left, sum - root->val) ||\n           hasPathSum(root->right, sum - root->val);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/112.html",
    "category": "Algorithms",
    "acceptance_rate": 52.80950275276898,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 10177,
    "dislikes": 1176,
    "similar_questions": "[{\"title\": \"Path Sum II\", \"titleSlug\": \"path-sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Maximum Path Sum\", \"titleSlug\": \"binary-tree-maximum-path-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sum Root to Leaf Numbers\", \"titleSlug\": \"sum-root-to-leaf-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum III\", \"titleSlug\": \"path-sum-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum IV\", \"titleSlug\": \"path-sum-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"3.4M\", \"totalAcceptedRaw\": 1799749, \"totalSubmissionRaw\": 3407999, \"acRate\": \"52.8%\"}",
    "title_pt": "Soma de Caminho",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária e um inteiro <code>targetSum</code>, retorne <code>true</code> se a árvore tiver um caminho da <strong>raiz até a folha</strong> tal que a soma de todos os valores ao longo do caminho seja igual a <code>targetSum</code>.</p>\n\n<p>Uma <strong>folha</strong> é um nó sem filhos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg\" style=\"width: 500px; height: 356px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O caminho da raiz até a folha com a soma alvo é mostrado.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3], targetSum = 5\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Há dois caminhos da raiz até a folha na árvore:\n(1 --&gt; 2): A soma é 3.\n(1 --&gt; 3): A soma é 4.\nNão existe nenhum caminho da raiz até a folha com soma = 5.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [], targetSum = 0\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Como a árvore está vazia, não há caminhos da raiz até a folha.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "113",
    "paidOnly": false,
    "title": "Path Sum II",
    "titleSlug": "path-sum-ii",
    "url": "https://leetcode.com/problems/path-sum-ii",
    "description_url": "https://leetcode.com/problems/path-sum-ii/description/",
    "description": "<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p>\n\n<p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg\" style=\"width: 500px; height: 356px;\" />\n<pre>\n<strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n<strong>Output:</strong> [[5,4,11,2],[5,8,4,5]]\n<strong>Explanation:</strong> There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\" style=\"width: 212px; height: 181px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3], targetSum = 5\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1,2], targetSum = 0\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/path-sum-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def pathSum(self, root: TreeNode, summ: int) -> List[List[int]]:\n    ans = []\n\n    def dfs(root: TreeNode, summ: int, path: List[int]) -> None:\n      if not root:\n        return\n      if root.val == summ and not root.left and not root.right:\n        ans.append(path + [root.val])\n        return\n\n      dfs(root.left, summ - root.val, path + [root.val])\n      dfs(root.right, summ - root.val, path + [root.val])\n\n    dfs(root, summ, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> pathSum(TreeNode root, int sum) {\n    List<List<Integer>> ans = new ArrayList<>();\n    dfs(root, sum, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ans) {\n    if (root == null)\n      return;\n    if (root.val == sum && root.left == null && root.right == null) {\n      path.add(root.val);\n      ans.add(new ArrayList<>(path));\n      path.remove(path.size() - 1);\n      return;\n    }\n\n    path.add(root.val);\n    dfs(root.left, sum - root.val, path, ans);\n    dfs(root.right, sum - root.val, path, ans);\n    path.remove(path.size() - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> pathSum(TreeNode* root, int sum) {\n    vector<vector<int>> ans;\n    dfs(root, sum, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(TreeNode* root, int sum, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (root == nullptr)\n      return;\n    if (root->val == sum && root->left == nullptr && root->right == nullptr) {\n      path.push_back(root->val);\n      ans.push_back(path);\n      path.pop_back();\n      return;\n    }\n\n    path.push_back(root->val);\n    dfs(root->left, sum - root->val, move(path), ans);\n    dfs(root->right, sum - root->val, move(path), ans);\n    path.pop_back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/113.html",
    "category": "Algorithms",
    "acceptance_rate": 60.33447592074766,
    "topics": [
      "Backtracking",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8287,
    "dislikes": 164,
    "similar_questions": "[{\"title\": \"Path Sum\", \"titleSlug\": \"path-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Paths\", \"titleSlug\": \"binary-tree-paths\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Path Sum III\", \"titleSlug\": \"path-sum-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum IV\", \"titleSlug\": \"path-sum-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Step-By-Step Directions From a Binary Tree Node to Another\", \"titleSlug\": \"step-by-step-directions-from-a-binary-tree-node-to-another\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1008924, \"totalSubmissionRaw\": 1672222, \"acRate\": \"60.3%\"}",
    "title_pt": "Soma de Caminhos II",
    "description_pt": "<p>Dado a <code>root</code> de uma árvore binária e um inteiro <code>targetSum</code>, retorne <em>todos os caminhos <strong>da raiz até a folha</strong> em que a soma dos valores dos nós no caminho é igual a </em><code>targetSum</code><em>. Cada caminho deve ser retornado como uma lista dos <strong>valores</strong> dos nós, não referências de nós</em>.</p>\n\n<p>Um caminho <strong>da raiz até a folha</strong> é um caminho que começa na raiz e termina em qualquer nó folha. Uma <strong>folha</strong> é um nó sem filhos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg\" style=\"width: 500px; height: 356px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n<strong>Saída:</strong> [[5,4,11,2],[5,8,4,5]]\n<strong>Explicação:</strong> Existem dois caminhos cuja soma é igual a targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg\" style=\"width: 212px; height: 181px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3], targetSum = 5\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,2], targetSum = 0\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 5000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "114",
    "paidOnly": false,
    "title": "Flatten Binary Tree to Linked List",
    "titleSlug": "flatten-binary-tree-to-linked-list",
    "url": "https://leetcode.com/problems/flatten-binary-tree-to-linked-list",
    "description_url": "https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, flatten the tree into a &quot;linked list&quot;:</p>\n\n<ul>\n\t<li>The &quot;linked list&quot; should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li>\n\t<li>The &quot;linked list&quot; should be in the same order as a <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR\" target=\"_blank\"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg\" style=\"width: 500px; height: 226px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,5,3,4,null,6]\n<strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?",
    "solution_url": "https://leetcode.com/problems/flatten-binary-tree-to-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def flatten(self, root: Optional[TreeNode]) -> None:\n    if not root:\n      return\n\n    self.flatten(root.left)\n    self.flatten(root.right)\n\n    left = root.left  # Flattened left\n    right = root.right  # Flattened right\n\n    root.left = None\n    root.right = left\n\n    # Connect the original right subtree\n    # To the end of new right subtree\n    rightmost = root\n    while rightmost.right:\n      rightmost = rightmost.right\n    rightmost.right = right",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void flatten(TreeNode root) {\n    if (root == null)\n      return;\n\n    flatten(root.left);\n    flatten(root.right);\n\n    TreeNode left = root.left;   // Flattened left\n    TreeNode right = root.right; // Flattened right\n\n    root.left = null;\n    root.right = left;\n\n    // Connect the original right subtree\n    // To the end of new right subtree\n    TreeNode rightmost = root;\n    while (rightmost.right != null)\n      rightmost = rightmost.right;\n    rightmost.right = right;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void flatten(TreeNode* root) {\n    if (root == nullptr)\n      return;\n\n    flatten(root->left);\n    flatten(root->right);\n\n    TreeNode* const left = root->left;    // Flattened left\n    TreeNode* const right = root->right;  // Flattened right\n\n    root->left = nullptr;\n    root->right = left;\n\n    // Connect the original right subtree\n    // To the end of new right subtree\n    TreeNode* rightmost = root;\n    while (rightmost->right)\n      rightmost = rightmost->right;\n    rightmost->right = right;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/114.html",
    "category": "Algorithms",
    "acceptance_rate": 68.23024388204568,
    "topics": [
      "Linked List",
      "Stack",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [
      "If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal."
    ],
    "likes": 12933,
    "dislikes": 580,
    "similar_questions": "[{\"title\": \"Flatten a Multilevel Doubly Linked List\", \"titleSlug\": \"flatten-a-multilevel-doubly-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Correct a Binary Tree\", \"titleSlug\": \"correct-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1175070, \"totalSubmissionRaw\": 1722216, \"acRate\": \"68.2%\"}",
    "title_pt": "Achatar Árvore Binária em Lista Encadeada",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, achate a árvore em uma &quot;lista encadeada&quot;:</p>\n\n<ul>\n\t<li>A &quot;lista encadeada&quot; deve usar a mesma classe <code>TreeNode</code>, em que o ponteiro do filho <code>right</code> aponta para o próximo nó na lista e o ponteiro do filho <code>left</code> é sempre <code>null</code>.</li>\n\t<li>A &quot;lista encadeada&quot; deve estar na mesma ordem de uma <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR\" target=\"_blank\"><strong>travessia em pré-ordem</strong><strong> da árvore</strong></a> binária.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg\" style=\"width: 500px; height: 226px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,5,3,4,null,6]\n<strong>Saída:</strong> [1,null,2,null,3,null,4,null,5,null,6]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [0]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 2000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue achatar a árvore in-place (com <code>O(1)</code> de espaço extra)?",
    "hints_pt": [
      "Dica 1: Se você notar com atenção na árvore achatada, o filho direito de cada nó aponta para o próximo nó de uma travessia em pré-ordem."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "115",
    "paidOnly": false,
    "title": "Distinct Subsequences",
    "titleSlug": "distinct-subsequences",
    "url": "https://leetcode.com/problems/distinct-subsequences",
    "description_url": "https://leetcode.com/problems/distinct-subsequences/description/",
    "description": "<p>Given two strings s and t, return <i>the number of distinct</i> <b><i>subsequences</i></b><i> of </i>s<i> which equals </i>t.</p>\n\n<p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nAs shown below, there are 3 ways you can generate &quot;rabbit&quot; from s.\n<code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code>\n<code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code>\n<code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code>\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot;\n<strong>Output:</strong> 5\n<strong>Explanation:</strong>\nAs shown below, there are 5 ways you can generate &quot;bag&quot; from s.\n<code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code>\n<code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code>\n<code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code>\n<code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code>\n<code>babg<strong><u>bag</u></strong></code></pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li>\n\t<li><code>s</code> and <code>t</code> consist of English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/distinct-subsequences/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numDistinct(self, s: str, t: str) -> int:\n    m = len(s)\n    n = len(t)\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n    for i in range(m + 1):\n      dp[i][0] = 1\n\n    for i in range(1, m + 1):\n      for j in range(1, n + 1):\n        if s[i - 1] == t[j - 1]:\n          dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]\n        else:\n          dp[i][j] = dp[i - 1][j]\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numDistinct(String s, String t) {\n    final int m = s.length();\n    final int n = t.length();\n    long[][] dp = new long[m + 1][n + 1];\n\n    for (int i = 0; i <= m; ++i)\n      dp[i][0] = 1;\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (s.charAt(i - 1) == t.charAt(j - 1))\n          dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j];\n\n    return (int) dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numDistinct(string s, string t) {\n    const int m = s.length();\n    const int n = t.length();\n    vector<vector<long>> dp(m + 1, vector<long>(n + 1));\n\n    for (int i = 0; i <= m; ++i)\n      dp[i][0] = 1;\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (s[i - 1] == t[j - 1])\n          dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j];\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/115.html",
    "category": "Algorithms",
    "acceptance_rate": 49.87629696579403,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 6957,
    "dislikes": 308,
    "similar_questions": "[{\"title\": \"Number of Unique Good Subsequences\", \"titleSlug\": \"number-of-unique-good-subsequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"533.6K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 533621, \"totalSubmissionRaw\": 1069893, \"acRate\": \"49.9%\"}",
    "title_pt": "Subsequências Distintas",
    "description_pt": "<p>Dadas duas strings s e t, retorne <i>o número de</i> <b><i>subsequências</i></b><i> distintas de </i>s<i> que são iguais a </i>t.</p>\n\n<p>Os casos de teste são gerados de forma que a resposta caiba em um inteiro com sinal de 32 bits.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;rabbbit&quot;, t = &quot;rabbit&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>\nComo mostrado abaixo, existem 3 maneiras de gerar &quot;rabbit&quot; a partir de s.\n<code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code>\n<code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code>\n<code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code>\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;babgbag&quot;, t = &quot;bag&quot;\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong>\nComo mostrado abaixo, existem 5 maneiras de gerar &quot;bag&quot; a partir de s.\n<code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code>\n<code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code>\n<code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code>\n<code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code>\n<code>babg<strong><u>bag</u></strong></code></pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li>\n\t<li><code>s</code> e <code>t</code> consistem de letras ইংlesas.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "116",
    "paidOnly": false,
    "title": "Populating Next Right Pointers in Each Node",
    "titleSlug": "populating-next-right-pointers-in-each-node",
    "url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node",
    "description_url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/",
    "description": "<p>You are given a <strong>perfect binary tree</strong> where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:</p>\n\n<pre>\nstruct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n</pre>\n\n<p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p>\n\n<p>Initially, all next pointers are set to <code>NULL</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/02/14/116_sample.png\" style=\"width: 500px; height: 171px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,5,6,7]\n<strong>Output:</strong> [1,#,2,3,#,4,5,6,7,#]\n<strong>Explanation: </strong>Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 2<sup>12</sup> - 1]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong></p>\n\n<ul>\n\t<li>You may only use constant extra space.</li>\n\t<li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':\n    if not root:\n      return None\n\n    def connectTwoNodes(p, q) -> None:\n      if not p:\n        return\n      p.next = q\n      connectTwoNodes(p.left, p.right)\n      connectTwoNodes(q.left, q.right)\n      connectTwoNodes(p.right, q.left)\n\n    connectTwoNodes(root.left, root.right)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node connect(Node root) {\n    if (root == null)\n      return null;\n    connectTwoNodes(root.left, root.right);\n    return root;\n  }\n\n  private void connectTwoNodes(Node p, Node q) {\n    if (p == null)\n      return;\n    p.next = q;\n    connectTwoNodes(p.left, p.right);\n    connectTwoNodes(q.left, q.right);\n    connectTwoNodes(p.right, q.left);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* connect(Node* root) {\n    if (root == nullptr)\n      return nullptr;\n    connectTwoNodes(root->left, root->right);\n    return root;\n  }\n\n private:\n  void connectTwoNodes(Node* p, Node* q) {\n    if (p == nullptr)\n      return;\n    p->next = q;\n    connectTwoNodes(p->left, p->right);\n    connectTwoNodes(q->left, q->right);\n    connectTwoNodes(p->right, q->left);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/116.html",
    "category": "Algorithms",
    "acceptance_rate": 65.26072030691452,
    "topics": [
      "Linked List",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 10084,
    "dislikes": 316,
    "similar_questions": "[{\"title\": \"Populating Next Right Pointers in Each Node II\", \"titleSlug\": \"populating-next-right-pointers-in-each-node-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Right Side View\", \"titleSlug\": \"binary-tree-right-side-view\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Cycle Length Queries in a Tree\", \"titleSlug\": \"cycle-length-queries-in-a-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 1196876, \"totalSubmissionRaw\": 1833993, \"acRate\": \"65.3%\"}",
    "title_pt": "Preencher Ponteiros Next à Direita em Cada Nó",
    "description_pt": "<p>Você recebe uma <strong>árvore binária perfeita</strong> na qual todas as folhas estão no mesmo nível, e todo pai tem dois filhos. A árvore binária tem a seguinte definição:</p>\n\n<pre>\nstruct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n</pre>\n\n<p>Preencha cada ponteiro next para apontar para seu próximo nó à direita. Se não houver próximo nó à direita, o ponteiro next deve ser definido como <code>NULL</code>.</p>\n\n<p>Inicialmente, todos os ponteiros next estão definidos como <code>NULL</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/02/14/116_sample.png\" style=\"width: 500px; height: 171px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,5,6,7]\n<strong>Saída:</strong> [1,#,2,3,#,4,5,6,7,#]\n<strong>Explicação: </strong>Dada a árvore binária perfeita acima (Figura A), sua função deve preencher cada ponteiro next para apontar para seu próximo nó à direita, exatamente como na Figura B. A saída serializada está em ordem de nível, conforme conectada pelos ponteiros next, com &#39;#&#39; significando o fim de cada nível.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 2<sup>12</sup> - 1]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Você pode usar apenas espaço extra constante.</li>\n\t<li>A abordagem recursiva é válida. Você pode assumir que o espaço implícito da pilha não conta como espaço extra para este problema.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "117",
    "paidOnly": false,
    "title": "Populating Next Right Pointers in Each Node II",
    "titleSlug": "populating-next-right-pointers-in-each-node-ii",
    "url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii",
    "description_url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/",
    "description": "<p>Given a binary tree</p>\n\n<pre>\nstruct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n</pre>\n\n<p>Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to <code>NULL</code>.</p>\n\n<p>Initially, all next pointers are set to <code>NULL</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/02/15/117_sample.png\" style=\"width: 500px; height: 171px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,5,null,7]\n<strong>Output:</strong> [1,#,2,3,#,4,5,7,#]\n<strong>Explanation: </strong>Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with &#39;#&#39; signifying the end of each level.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 6000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong></p>\n\n<ul>\n\t<li>You may only use constant extra space.</li>\n\t<li>The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def connect(self, root: 'Node') -> 'Node':\n    node = root  # The node just above current needling\n\n    while node:\n      dummy = Node(0)  # Dummy node before needling\n      # Needle children of node\n      needle = dummy\n      while node:\n        if node.left:  # Needle left child\n          needle.next = node.left\n          needle = needle.next\n        if node.right:  # Needle right child\n          needle.next = node.right\n          needle = needle.next\n        node = node.next\n      node = dummy.next  # Move node to the next level\n\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node connect(Node root) {\n    Node node = root; // The node just above current needling\n\n    while (node != null) {\n      Node dummy = new Node(); // Dummy node before needling\n      // Needle children of node\n      for (Node needle = dummy; node != null; node = node.next) {\n        if (node.left != null) { // Needle left child\n          needle.next = node.left;\n          needle = needle.next;\n        }\n        if (node.right != null) { // Needle right child\n          needle.next = node.right;\n          needle = needle.next;\n        }\n      }\n      node = dummy.next; // Move node to the next level\n    }\n\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* connect(Node* root) {\n    Node* node = root;  // The node just above current needling\n\n    while (node) {\n      Node dummy(0);  // Dummy node before needling\n      // Needle children of node\n      for (Node* needle = &dummy; node; node = node->next) {\n        if (node->left) {  // Needle left child\n          needle->next = node->left;\n          needle = needle->next;\n        }\n        if (node->right) {  // Needle right child\n          needle->next = node->right;\n          needle = needle->next;\n        }\n      }\n      node = dummy.next;  // Move node to the next level\n    }\n\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/117.html",
    "category": "Algorithms",
    "acceptance_rate": 55.363329510271754,
    "topics": [
      "Linked List",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 6037,
    "dislikes": 335,
    "similar_questions": "[{\"title\": \"Populating Next Right Pointers in Each Node\", \"titleSlug\": \"populating-next-right-pointers-in-each-node\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"745.3K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 745301, \"totalSubmissionRaw\": 1346201, \"acRate\": \"55.4%\"}",
    "title_pt": "Preenchendo os Ponteiros Next à Direita em Cada Nó II",
    "description_pt": "<p>Dada uma árvore binária</p>\n\n<pre>\nstruct Node {\n  int val;\n  Node *left;\n  Node *right;\n  Node *next;\n}\n</pre>\n\n<p>Preencha cada ponteiro next para apontar para seu próximo nó à direita. Se não houver próximo nó à direita, o ponteiro next deve ser definido como <code>NULL</code>.</p>\n\n<p>Inicialmente, todos os ponteiros next são definidos como <code>NULL</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/02/15/117_sample.png\" style=\"width: 500px; height: 171px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,5,null,7]\n<strong>Saída:</strong> [1,#,2,3,#,4,5,7,#]\n<strong>Explicação: </strong>Dada a árvore binária acima (Figura A), sua função deve preencher cada ponteiro next para apontar para seu próximo nó à direita, assim como na Figura B. A saída serializada está em ordem de nível conforme conectada pelos ponteiros next, com &#39;#&#39; significando o fim de cada nível.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 6000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Você pode usar apenas espaço extra constante.</li>\n\t<li>A abordagem recursiva é aceitável. Você pode assumir que o espaço implícito da pilha não conta como espaço extra para este problema.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "118",
    "paidOnly": false,
    "title": "Pascal's Triangle",
    "titleSlug": "pascals-triangle",
    "url": "https://leetcode.com/problems/pascals-triangle",
    "description_url": "https://leetcode.com/problems/pascals-triangle/description/",
    "description": "<p>Given an integer <code>numRows</code>, return the first numRows of <strong>Pascal&#39;s triangle</strong>.</p>\n\n<p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif\" style=\"height:240px; width:260px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> numRows = 5\n<strong>Output:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> numRows = 1\n<strong>Output:</strong> [[1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numRows &lt;= 30</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/pascals-triangle/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def generate(self, numRows: int) -> List[List[int]]:\n    ans = []\n\n    for i in range(numRows):\n      ans.append([1] * (i + 1))\n\n    for i in range(2, numRows):\n      for j in range(1, len(ans[i]) - 1):\n        ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> generate(int numRows) {\n    List<List<Integer>> ans = new ArrayList<>();\n\n    for (int i = 0; i < numRows; ++i) {\n      Integer[] temp = new Integer[i + 1];\n      Arrays.fill(temp, 1);\n      ans.add(Arrays.asList(temp));\n    }\n\n    for (int i = 2; i < numRows; ++i)\n      for (int j = 1; j < ans.get(i).size() - 1; ++j)\n        ans.get(i).set(j, ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> generate(int numRows) {\n    vector<vector<int>> ans;\n\n    for (int i = 0; i < numRows; ++i)\n      ans.push_back(vector<int>(i + 1, 1));\n\n    for (int i = 2; i < numRows; ++i)\n      for (int j = 1; j < ans[i].size() - 1; ++j)\n        ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/118.html",
    "category": "Algorithms",
    "acceptance_rate": 76.82287854746444,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 13737,
    "dislikes": 509,
    "similar_questions": "[{\"title\": \"Pascal's Triangle II\", \"titleSlug\": \"pascals-triangle-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Check If Digits Are Equal in String After Operations II\", \"titleSlug\": \"check-if-digits-are-equal-in-string-after-operations-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 2099302, \"totalSubmissionRaw\": 2732651, \"acRate\": \"76.8%\"}",
    "title_pt": "Triângulo de Pascal",
    "description_pt": "<p>Dado um inteiro <code>numRows</code>, retorne as primeiras numRows linhas do <strong>triângulo de Pascal</strong>.</p>\n\n<p>No <strong>triângulo de Pascal</strong>, cada número é a soma dos dois números diretamente acima dele, como mostrado:</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif\" style=\"height:240px; width:260px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> numRows = 5\n<strong>Saída:</strong> [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> numRows = 1\n<strong>Saída:</strong> [[1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numRows &lt;= 30</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "119",
    "paidOnly": false,
    "title": "Pascal's Triangle II",
    "titleSlug": "pascals-triangle-ii",
    "url": "https://leetcode.com/problems/pascals-triangle-ii",
    "description_url": "https://leetcode.com/problems/pascals-triangle-ii/description/",
    "description": "<p>Given an integer <code>rowIndex</code>, return the <code>rowIndex<sup>th</sup></code> (<strong>0-indexed</strong>) row of the <strong>Pascal&#39;s triangle</strong>.</p>\n\n<p>In <strong>Pascal&#39;s triangle</strong>, each number is the sum of the two numbers directly above it as shown:</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif\" style=\"height:240px; width:260px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> rowIndex = 3\n<strong>Output:</strong> [1,3,3,1]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> rowIndex = 0\n<strong>Output:</strong> [1]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> rowIndex = 1\n<strong>Output:</strong> [1,1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= rowIndex &lt;= 33</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you optimize your algorithm to use only <code>O(rowIndex)</code> extra space?</p>\n",
    "solution_url": "https://leetcode.com/problems/pascals-triangle-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getRow(self, rowIndex: int) -> List[int]:\n    ans = [1] * (rowIndex + 1)\n\n    for i in range(2, rowIndex + 1):\n      for j in range(1, i):\n        ans[i - j] += ans[i - j - 1]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> getRow(int rowIndex) {\n    Integer[] ans = new Integer[rowIndex + 1];\n    Arrays.fill(ans, 1);\n\n    for (int i = 2; i < rowIndex + 1; ++i)\n      for (int j = 1; j < i; ++j)\n        ans[i - j] += ans[i - j - 1];\n\n    return Arrays.asList(ans);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> getRow(int rowIndex) {\n    vector<int> ans(rowIndex + 1, 1);\n\n    for (int i = 2; i < rowIndex + 1; ++i)\n      for (int j = 1; j < i; ++j)\n        ans[i - j] += ans[i - j - 1];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/119.html",
    "category": "Algorithms",
    "acceptance_rate": 65.80036741882904,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 5035,
    "dislikes": 358,
    "similar_questions": "[{\"title\": \"Pascal's Triangle\", \"titleSlug\": \"pascals-triangle\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Triangular Sum of an Array\", \"titleSlug\": \"find-triangular-sum-of-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1041934, \"totalSubmissionRaw\": 1583478, \"acRate\": \"65.8%\"}",
    "title_pt": "Triângulo de Pascal II",
    "description_pt": "<p>Dado um inteiro <code>rowIndex</code>, retorne a <code>rowIndex<sup>th</sup></code> linha (<strong>indexado em 0</strong>) do <strong>triângulo de Pascal</strong>.</p>\n\n<p>No <strong>triângulo de Pascal</strong>, cada número é a soma dos dois números diretamente acima dele, como mostrado:</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif\" style=\"height:240px; width:260px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> rowIndex = 3\n<strong>Saída:</strong> [1,3,3,1]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> rowIndex = 0\n<strong>Saída:</strong> [1]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> rowIndex = 1\n<strong>Saída:</strong> [1,1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= rowIndex &lt;= 33</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você poderia otimizar seu algoritmo para usar apenas <code>O(rowIndex)</code> de espaço extra?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "120",
    "paidOnly": false,
    "title": "Triangle",
    "titleSlug": "triangle",
    "url": "https://leetcode.com/problems/triangle",
    "description_url": "https://leetcode.com/problems/triangle/description/",
    "description": "<p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p>\n\n<p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> The triangle looks like:\n   <u>2</u>\n  <u>3</u> 4\n 6 <u>5</u> 7\n4 <u>1</u> 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> triangle = [[-10]]\n<strong>Output:</strong> -10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= triangle.length &lt;= 200</code></li>\n\t<li><code>triangle[0].length == 1</code></li>\n\t<li><code>triangle[i].length == triangle[i - 1].length + 1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?",
    "solution_url": "https://leetcode.com/problems/triangle/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minimumTotal(self, triangle: List[List[int]]) -> int:\n    for i in reversed(range(len(triangle) - 1)):\n      for j in range(i + 1):\n        triangle[i][j] += min(triangle[i + 1][j],\n                              triangle[i + 1][j + 1])\n\n    return triangle[0][0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minimumTotal(List<List<Integer>> triangle) {\n    for (int i = triangle.size() - 2; i >= 0; --i)\n      for (int j = 0; j <= i; ++j)\n        triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j),\n                                                                 triangle.get(i + 1).get(j + 1)));\n    return triangle.get(0).get(0);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minimumTotal(vector<vector<int>>& triangle) {\n    for (int i = triangle.size() - 2; i >= 0; --i)\n      for (int j = 0; j <= i; ++j)\n        triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]);\n    return triangle[0][0];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/120.html",
    "category": "Algorithms",
    "acceptance_rate": 59.02941335243557,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 9988,
    "dislikes": 577,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"973.2K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 973194, \"totalSubmissionRaw\": 1648665, \"acRate\": \"59.0%\"}",
    "title_pt": "Triângulo",
    "description_pt": "<p>Dado um array <code>triangle</code>, retorne <em>a soma mínima de um caminho do topo até a base</em>.</p>\n\n<p>Para cada passo, você pode mover-se para um número adjacente da linha abaixo. Mais formalmente, se você estiver no índice <code>i</code> na linha atual, você pode mover-se para o índice <code>i</code> ou para o índice <code>i + 1</code> na próxima linha.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\n<strong>Saída:</strong> 11\n<strong>Explicação:</strong> O triângulo se parece com:\n   <u>2</u>\n  <u>3</u> 4\n 6 <u>5</u> 7\n4 <u>1</u> 8 3\nA soma mínima de um caminho do topo até a base é 2 + 3 + 5 + 1 = 11 (sublinhado acima).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> triangle = [[-10]]\n<strong>Saída:</strong> -10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= triangle.length &lt;= 200</code></li>\n\t<li><code>triangle[0].length == 1</code></li>\n\t<li><code>triangle[i].length == triangle[i - 1].length + 1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você poderia&nbsp;fazer isso usando apenas <code>O(n)</code> de espaço extra, onde <code>n</code> é o número total de linhas no triângulo?",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "121",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock",
    "titleSlug": "best-time-to-buy-and-sell-stock",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/",
    "description": "<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>\n\n<p>You want to maximize your profit by choosing a <strong>single day</strong> to buy one stock and choosing a <strong>different day in the future</strong> to sell that stock.</p>\n\n<p>Return <em>the maximum profit you can achieve from this transaction</em>. If you cannot achieve any profit, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [7,1,5,3,6,4]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [7,6,4,3,1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> In this case, no transactions are done and the max profit = 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, prices: List[int]) -> int:\n    sellOne = 0\n    holdOne = -math.inf\n\n    for price in prices:\n      sellOne = max(sellOne, holdOne + price)\n      holdOne = max(holdOne, -price)\n\n    return sellOne",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int[] prices) {\n    int sellOne = 0;\n    int holdOne = Integer.MIN_VALUE;\n\n    for (final int price : prices) {\n      sellOne = Math.max(sellOne, holdOne + price);\n      holdOne = Math.max(holdOne, -price);\n    }\n\n    return sellOne;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(vector<int>& prices) {\n    int sellOne = 0;\n    int holdOne = INT_MIN;\n\n    for (const int price : prices) {\n      sellOne = max(sellOne, holdOne + price);\n      holdOne = max(holdOne, -price);\n    }\n\n    return sellOne;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/121.html",
    "category": "Algorithms",
    "acceptance_rate": 55.085600883554385,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 33097,
    "dislikes": 1278,
    "similar_questions": "[{\"title\": \"Maximum Subarray\", \"titleSlug\": \"maximum-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock II\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock III\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock IV\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock with Cooldown\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-with-cooldown\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Beauty in the Array\", \"titleSlug\": \"sum-of-beauty-in-the-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Difference Between Increasing Elements\", \"titleSlug\": \"maximum-difference-between-increasing-elements\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Profit From Trading Stocks\", \"titleSlug\": \"maximum-profit-from-trading-stocks\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"6.3M\", \"totalSubmission\": \"11.4M\", \"totalAcceptedRaw\": 6305340, \"totalSubmissionRaw\": 11446456, \"acRate\": \"55.1%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ações",
    "description_pt": "<p>Você recebe um array <code>prices</code> em que <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia.</p>\n\n<p>Você quer maximizar seu lucro escolhendo um <strong>único dia</strong> para comprar uma ação e escolhendo um <strong>dia diferente no futuro</strong> para vender essa ação.</p>\n\n<p>Retorne <em>o lucro máximo que você pode obter com essa transação</em>. Se você não puder obter nenhum lucro, retorne <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [7,1,5,3,6,4]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Compre no dia 2 (price = 1) e venda no dia 5 (price = 6), lucro = 6-1 = 5.\nObserve que comprar no dia 2 e vender no dia 1 não é permitido porque você deve comprar antes de vender.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [7,6,4,3,1]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Neste caso, nenhuma transação é realizada e o lucro máximo = 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "122",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock II",
    "titleSlug": "best-time-to-buy-and-sell-stock-ii",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/",
    "description": "<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>\n\n<p>On each day, you may decide to buy and/or sell the stock. You can only hold <strong>at most one</strong> share of the stock at any time. However, you can buy it then immediately sell it on the <strong>same day</strong>.</p>\n\n<p>Find and return <em>the <strong>maximum</strong> profit you can achieve</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [7,1,5,3,6,4]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1,2,3,4,5]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [7,6,4,3,1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, prices: List[int]) -> int:\n    sell = 0\n    hold = -math.inf\n\n    for price in prices:\n      sell = max(sell, hold + price)\n      hold = max(hold, sell - price)\n\n    return sell",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int[] prices) {\n    int sell = 0;\n    int hold = Integer.MIN_VALUE;\n\n    for (final int price : prices) {\n      sell = Math.max(sell, hold + price);\n      hold = Math.max(hold, sell - price);\n    }\n\n    return sell;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(vector<int>& prices) {\n    int sell = 0;\n    int hold = INT_MIN;\n\n    for (const int price : prices) {\n      sell = max(sell, hold + price);\n      hold = max(hold, sell - price);\n    }\n\n    return sell;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/122.html",
    "category": "Algorithms",
    "acceptance_rate": 69.29255345303243,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy"
    ],
    "hints": [],
    "likes": 14450,
    "dislikes": 2764,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock\", \"titleSlug\": \"best-time-to-buy-and-sell-stock\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock III\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock IV\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock with Cooldown\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-with-cooldown\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock with Transaction Fee\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-with-transaction-fee\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Profit From Trading Stocks\", \"titleSlug\": \"maximum-profit-from-trading-stocks\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"3.6M\", \"totalAcceptedRaw\": 2494354, \"totalSubmissionRaw\": 3599745, \"acRate\": \"69.3%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ações II",
    "description_pt": "<p>Você recebe um array de inteiros <code>prices</code> em que <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia.</p>\n\n<p>Em cada dia, você pode decidir comprar e/ou vender a ação. Você só pode manter, em qualquer momento, <strong>no máximo uma</strong> ação. No entanto, você pode comprá-la e então vendê-la imediatamente no <strong>mesmo dia</strong>.</p>\n\n<p>Encontre e retorne <em>o <strong>máximo</strong> lucro que você pode obter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [7,1,5,3,6,4]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Compre no dia 2 (preço = 1) e venda no dia 3 (preço = 5), lucro = 5-1 = 4.\nDepois compre no dia 4 (preço = 3) e venda no dia 5 (preço = 6), lucro = 6-3 = 3.\nO lucro total é 4 + 3 = 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1,2,3,4,5]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Compre no dia 1 (preço = 1) e venda no dia 5 (preço = 5), lucro = 5-1 = 4.\nO lucro total é 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [7,6,4,3,1]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Não há maneira de obter um lucro positivo, então nunca compramos a ação para alcançar o lucro máximo de 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "123",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock III",
    "titleSlug": "best-time-to-buy-and-sell-stock-iii",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/",
    "description": "<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>\n\n<p>Find the maximum profit you can achieve. You may complete <strong>at most two transactions</strong>.</p>\n\n<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [3,3,5,0,0,3,1,4]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1,2,3,4,5]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [7,6,4,3,1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> In this case, no transaction is done, i.e. max profit = 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, prices: List[int]) -> int:\n    sellTwo = 0\n    holdTwo = -math.inf\n    sellOne = 0\n    holdOne = -math.inf\n\n    for price in prices:\n      sellTwo = max(sellTwo, holdTwo + price)\n      holdTwo = max(holdTwo, sellOne - price)\n      sellOne = max(sellOne, holdOne + price)\n      holdOne = max(holdOne, -price)\n\n    return sellTwo",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int[] prices) {\n    int sellTwo = 0;\n    int holdTwo = Integer.MIN_VALUE;\n    int sellOne = 0;\n    int holdOne = Integer.MIN_VALUE;\n\n    for (final int price : prices) {\n      sellTwo = Math.max(sellTwo, holdTwo + price);\n      holdTwo = Math.max(holdTwo, sellOne - price);\n      sellOne = Math.max(sellOne, holdOne + price);\n      holdOne = Math.max(holdOne, -price);\n    }\n\n    return sellTwo;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(vector<int>& prices) {\n    int sellTwo = 0;\n    int holdTwo = INT_MIN;\n    int sellOne = 0;\n    int holdOne = INT_MIN;\n\n    for (const int price : prices) {\n      sellTwo = max(sellTwo, holdTwo + price);\n      holdTwo = max(holdTwo, sellOne - price);\n      sellOne = max(sellOne, holdOne + price);\n      holdOne = max(holdOne, -price);\n    }\n\n    return sellTwo;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/123.html",
    "category": "Algorithms",
    "acceptance_rate": 50.75605708946027,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 10115,
    "dislikes": 206,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock\", \"titleSlug\": \"best-time-to-buy-and-sell-stock\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock II\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock IV\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Sum of 3 Non-Overlapping Subarrays\", \"titleSlug\": \"maximum-sum-of-3-non-overlapping-subarrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Profit From Trading Stocks\", \"titleSlug\": \"maximum-profit-from-trading-stocks\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximize Win From Two Segments\", \"titleSlug\": \"maximize-win-from-two-segments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"770.2K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 770203, \"totalSubmissionRaw\": 1517465, \"acRate\": \"50.8%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ação III",
    "description_pt": "<p>Você recebe um array <code>prices</code> em que <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia.</p>\n\n<p>Encontre o lucro máximo que você pode obter. Você pode realizar <strong>no máximo duas transações</strong>.</p>\n\n<p><strong>Nota:</strong> Você não pode participar de múltiplas transações simultaneamente (ou seja, você deve vender a ação antes de comprar novamente).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [3,3,5,0,0,3,1,4]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Compre no dia 4 (price = 0) e venda no dia 6 (price = 3), lucro = 3-0 = 3.\nDepois compre no dia 7 (price = 1) e venda no dia 8 (price = 4), lucro = 4-1 = 3.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1,2,3,4,5]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Compre no dia 1 (price = 1) e venda no dia 5 (price = 5), lucro = 5-1 = 4.\nObserve que você não pode comprar no dia 1, comprar no dia 2 e vendê-las depois, pois você estaria realizando múltiplas transações ao mesmo tempo. Você deve vender antes de comprar novamente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [7,6,4,3,1]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Neste caso, nenhuma transação é realizada, ou seja, lucro máximo = 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "124",
    "paidOnly": false,
    "title": "Binary Tree Maximum Path Sum",
    "titleSlug": "binary-tree-maximum-path-sum",
    "url": "https://leetcode.com/problems/binary-tree-maximum-path-sum",
    "description_url": "https://leetcode.com/problems/binary-tree-maximum-path-sum/description/",
    "description": "<p>A <strong>path</strong> in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence <strong>at most once</strong>. Note that the path does not need to pass through the root.</p>\n\n<p>The <strong>path sum</strong> of a path is the sum of the node&#39;s values in the path.</p>\n\n<p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>path sum</strong> of any <strong>non-empty</strong> path</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg\" style=\"width: 322px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The optimal path is 2 -&gt; 1 -&gt; 3 with a path sum of 2 + 1 + 3 = 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg\" />\n<pre>\n<strong>Input:</strong> root = [-10,9,20,null,null,15,7]\n<strong>Output:</strong> 42\n<strong>Explanation:</strong> The optimal path is 15 -&gt; 20 -&gt; 7 with a path sum of 15 + 20 + 7 = 42.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-maximum-path-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxPathSum(self, root: Optional[TreeNode]) -> int:\n    ans = -math.inf\n\n    def maxPathSumDownFrom(root: Optional[TreeNode]) -> int:\n      nonlocal ans\n      if not root:\n        return 0\n\n      l = max(0, maxPathSumDownFrom(root.left))\n      r = max(0, maxPathSumDownFrom(root.right))\n      ans = max(ans, root.val + l + r)\n      return root.val + max(l, r)\n\n    maxPathSumDownFrom(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxPathSum(TreeNode root) {\n    maxPathSumDownFrom(root);\n    return ans;\n  }\n\n  private int ans = Integer.MIN_VALUE;\n\n  // root->val + 0/1 of its subtrees\n  private int maxPathSumDownFrom(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    final int l = Math.max(maxPathSumDownFrom(root.left), 0);\n    final int r = Math.max(maxPathSumDownFrom(root.right), 0);\n    ans = Math.max(ans, root.val + l + r);\n    return root.val + Math.max(l, r);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxPathSum(TreeNode* root) {\n    int ans = INT_MIN;\n    maxPathSumDownFrom(root, ans);\n    return ans;\n  }\n\n private:\n  // root->val + 0/1 of its subtrees\n  int maxPathSumDownFrom(TreeNode* root, int& ans) {\n    if (root == nullptr)\n      return 0;\n\n    const int l = max(0, maxPathSumDownFrom(root->left, ans));\n    const int r = max(0, maxPathSumDownFrom(root->right, ans));\n    ans = max(ans, root->val + l + r);\n    return root->val + max(l, r);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/124.html",
    "category": "Algorithms",
    "acceptance_rate": 41.12580758963126,
    "topics": [
      "Dynamic Programming",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 17496,
    "dislikes": 768,
    "similar_questions": "[{\"title\": \"Path Sum\", \"titleSlug\": \"path-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum Root to Leaf Numbers\", \"titleSlug\": \"sum-root-to-leaf-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum IV\", \"titleSlug\": \"path-sum-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Univalue Path\", \"titleSlug\": \"longest-univalue-path\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Time Needed to Inform All Employees\", \"titleSlug\": \"time-needed-to-inform-all-employees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Difference Between Maximum and Minimum Price Sum\", \"titleSlug\": \"difference-between-maximum-and-minimum-price-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"3.8M\", \"totalAcceptedRaw\": 1562075, \"totalSubmissionRaw\": 3798274, \"acRate\": \"41.1%\"}",
    "title_pt": "Soma Máxima de Caminho em Árvore Binária",
    "description_pt": "<p>Um <strong>caminho</strong> em uma árvore binária é uma sequência de nós em que cada par de nós adjacentes na sequência possui uma aresta conectando-os. Um nó pode aparecer na sequência <strong>no máximo uma vez</strong>. Note que o caminho não precisa passar pela raiz.</p>\n\n<p>A <strong>soma do caminho</strong> de um caminho é a soma dos valores dos nós no caminho.</p>\n\n<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a soma máxima de caminho de qualquer caminho <strong>não vazio</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx1.jpg\" style=\"width: 322px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O caminho ótimo é 2 -&gt; 1 -&gt; 3, com uma soma de caminho de 2 + 1 + 3 = 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/exx2.jpg\" />\n<pre>\n<strong>Entrada:</strong> root = [-10,9,20,null,null,15,7]\n<strong>Saída:</strong> 42\n<strong>Explicação:</strong> O caminho ótimo é 15 -&gt; 20 -&gt; 7, com uma soma de caminho de 15 + 20 + 7 = 42.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "125",
    "paidOnly": false,
    "title": "Valid Palindrome",
    "titleSlug": "valid-palindrome",
    "url": "https://leetcode.com/problems/valid-palindrome",
    "description_url": "https://leetcode.com/problems/valid-palindrome/description/",
    "description": "<p>A phrase is a <strong>palindrome</strong> if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.</p>\n\n<p>Given a string <code>s</code>, return <code>true</code><em> if it is a <strong>palindrome</strong>, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;A man, a plan, a canal: Panama&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> &quot;amanaplanacanalpanama&quot; is a palindrome.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;race a car&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> &quot;raceacar&quot; is not a palindrome.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot; &quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> s is an empty string &quot;&quot; after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists only of printable ASCII characters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-palindrome/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPalindrome(self, s: str) -> bool:\n    l = 0\n    r = len(s) - 1\n\n    while l < r:\n      while l < r and not s[l].isalnum():\n        l += 1\n      while l < r and not s[r].isalnum():\n        r -= 1\n      if s[l].lower() != s[r].lower():\n        return False\n      l += 1\n      r -= 1\n\n    return True",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPalindrome(String s) {\n    int l = 0;\n    int r = s.length() - 1;\n\n    while (l < r) {\n      while (l < r && !Character.isLetterOrDigit(s.charAt(l)))\n        ++l;\n      while (l < r && !Character.isLetterOrDigit(s.charAt(r)))\n        --r;\n      if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r)))\n        return false;\n      ++l;\n      --r;\n    }\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPalindrome(string s) {\n    int l = 0;\n    int r = s.length() - 1;\n\n    while (l < r) {\n      while (l < r && !isalnum(s[l]))\n        ++l;\n      while (l < r && !isalnum(s[r]))\n        --r;\n      if (tolower(s[l]) != tolower(s[r]))\n        return false;\n      ++l;\n      --r;\n    }\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/125.html",
    "category": "Algorithms",
    "acceptance_rate": 50.69565963099466,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 10292,
    "dislikes": 8541,
    "similar_questions": "[{\"title\": \"Palindrome Linked List\", \"titleSlug\": \"palindrome-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome II\", \"titleSlug\": \"valid-palindrome-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Product of the Length of Two Palindromic Subsequences\", \"titleSlug\": \"maximum-product-of-the-length-of-two-palindromic-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find First Palindromic String in the Array\", \"titleSlug\": \"find-first-palindromic-string-in-the-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome IV\", \"titleSlug\": \"valid-palindrome-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Palindromes After Operations\", \"titleSlug\": \"maximum-palindromes-after-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.2M\", \"totalSubmission\": \"8.2M\", \"totalAcceptedRaw\": 4173536, \"totalSubmissionRaw\": 8232558, \"acRate\": \"50.7%\"}",
    "title_pt": "Palíndromo Válido",
    "description_pt": "<p>Uma frase é um <strong>palíndromo</strong> se, após converter todas as letras maiúsculas para letras minúsculas e remover todos os caracteres não alfanuméricos, ela for lida da mesma forma de frente para trás e de trás para frente. Caracteres alfanuméricos incluem letras e números.</p>\n\n<p>Dada uma string <code>s</code>, retorne <code>true</code><em> se ela for um <strong>palíndromo</strong>, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;A man, a plan, a canal: Panama&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> &quot;amanaplanacanalpanama&quot; é um palíndromo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;race a car&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> &quot;raceacar&quot; não é um palíndromo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot; &quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> s é uma string vazia &quot;&quot; após remover os caracteres não alfanuméricos.\nComo uma string vazia é lida da mesma forma de frente para trás e de trás para frente, ela é um palíndromo.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste apenas em caracteres ASCII imprimíveis.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "126",
    "paidOnly": false,
    "title": "Word Ladder II",
    "titleSlug": "word-ladder-ii",
    "url": "https://leetcode.com/problems/word-ladder-ii",
    "description_url": "https://leetcode.com/problems/word-ladder-ii/description/",
    "description": "<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p>\n\n<ul>\n\t<li>Every adjacent pair of words differs by a single letter.</li>\n\t<li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>\n\t<li><code>s<sub>k</sub> == endWord</code></li>\n</ul>\n\n<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>all the <strong>shortest transformation sequences</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]\n<strong>Output:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]]\n<strong>Explanation:</strong>&nbsp;There are 2 shortest transformation sequences:\n&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;\n&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]\n<strong>Output:</strong> []\n<strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= beginWord.length &lt;= 5</code></li>\n\t<li><code>endWord.length == beginWord.length</code></li>\n\t<li><code>1 &lt;= wordList.length &lt;= 500</code></li>\n\t<li><code>wordList[i].length == beginWord.length</code></li>\n\t<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>\n\t<li><code>beginWord != endWord</code></li>\n\t<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>\n\t<li>The <strong>sum</strong> of all shortest transformation sequences does not exceed <code>10<sup>5</sup></code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-ladder-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n    wordSet = set(wordList)\n    if endWord not in wordList:\n      return []\n\n    # {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n    graph: Dict[str, List[str]] = defaultdict(list)\n\n    # Build graph from beginWord -> endWord\n    if not self._bfs(beginWord, endWord, wordSet, graph):\n      return []\n\n    ans = []\n\n    self._dfs(graph, beginWord, endWord, [beginWord], ans)\n    return ans\n\n  def _bfs(self, beginWord: str, endWord: str, wordSet: Set[str], graph: Dict[str, List[str]]) -> bool:\n    currentLevelWords = {beginWord}\n\n    while currentLevelWords:\n      for word in currentLevelWords:\n        wordSet.discard(word)\n      nextLevelWords = set()\n      reachEndWord = False\n      for parent in currentLevelWords:\n        for child in self._getChildren(parent, wordSet):\n          if child in wordSet:\n            nextLevelWords.add(child)\n            graph[parent].append(child)\n          if child == endWord:\n            reachEndWord = True\n      if reachEndWord:\n        return True\n      currentLevelWords = nextLevelWords\n\n    return False\n\n  def _getChildren(self, parent: str, wordSet: Set[str]) -> List[str]:\n    children = []\n    s = list(parent)\n\n    for i, cache in enumerate(s):\n      for c in string.ascii_lowercase:\n        if c == cache:\n          continue\n        s[i] = c\n        child = ''.join(s)\n        if child in wordSet:\n          children.append(child)\n      s[i] = cache\n\n    return children\n\n  def _dfs(self, graph: Dict[str, List[str]], word: str, endWord: str, path: List[str], ans: List[List[str]]) -> None:\n    if word == endWord:\n      ans.append(path.copy())\n      return\n\n    for child in graph.get(word, []):\n      path.append(child)\n      self._dfs(graph, child, endWord, path, ans)\n      path.pop()",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {\n    Set<String> wordSet = new HashSet<>(wordList);\n    if (!wordSet.contains(endWord))\n      return new ArrayList<>();\n\n    // {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n    Map<String, List<String>> graph = new HashMap<>();\n\n    // Build graph from beginWord -> endWord\n    if (!bfs(beginWord, endWord, wordSet, graph))\n      return new ArrayList<>();\n\n    List<List<String>> ans = new ArrayList<>();\n    List<String> path = new ArrayList<>(Arrays.asList(beginWord));\n\n    dfs(graph, beginWord, endWord, path, ans);\n    return ans;\n  }\n\n  private boolean bfs(final String beginWord, final String endWord, Set<String> wordSet,\n                      Map<String, List<String>> graph) {\n    Set<String> currentLevelWords = new HashSet<>();\n    currentLevelWords.add(beginWord);\n    boolean reachEndWord = false;\n\n    while (!currentLevelWords.isEmpty()) {\n      for (final String word : currentLevelWords)\n        wordSet.remove(word);\n      Set<String> nextLevelWords = new HashSet<>();\n      for (final String parent : currentLevelWords) {\n        graph.putIfAbsent(parent, new ArrayList<>());\n        for (final String child : getChildren(parent, wordSet)) {\n          if (wordSet.contains(child)) {\n            nextLevelWords.add(child);\n            graph.get(parent).add(child);\n          }\n          if (child.equals(endWord))\n            reachEndWord = true;\n        }\n      }\n      if (reachEndWord)\n        return true;\n      currentLevelWords = nextLevelWords;\n    }\n\n    return false;\n  }\n\n  private List<String> getChildren(final String parent, Set<String> wordSet) {\n    List<String> children = new ArrayList<>();\n    StringBuilder sb = new StringBuilder(parent);\n\n    for (int i = 0; i < sb.length(); ++i) {\n      final char cache = sb.charAt(i);\n      for (char c = 'a'; c <= 'z'; ++c) {\n        if (c == cache)\n          continue;\n        sb.setCharAt(i, c);\n        final String child = sb.toString();\n        if (wordSet.contains(child))\n          children.add(child);\n      }\n      sb.setCharAt(i, cache);\n    }\n\n    return children;\n  }\n\n  private void dfs(Map<String, List<String>> graph, final String word, final String endWord,\n                   List<String> path, List<List<String>> ans) {\n    if (word.equals(endWord)) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n    if (!graph.containsKey(word))\n      return;\n\n    for (final String child : graph.get(word)) {\n      path.add(child);\n      dfs(graph, child, endWord, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> findLadders(string beginWord, string endWord,\n                                     vector<string>& wordList) {\n    unordered_set<string> wordSet{begin(wordList), end(wordList)};\n    if (!wordSet.count(endWord))\n      return {};\n\n    // {\"hit\": [\"hot\"], \"hot\": [\"dot\", \"lot\"], ...}\n    unordered_map<string, vector<string>> graph;\n\n    // Build graph from beginWord -> endWord\n    if (!bfs(beginWord, endWord, wordSet, graph))\n      return {};\n\n    vector<vector<string>> ans;\n\n    dfs(graph, beginWord, endWord, {beginWord}, ans);\n    return ans;\n  }\n\n private:\n  bool bfs(const string& beginWord, const string& endWord,\n           unordered_set<string>& wordSet,\n           unordered_map<string, vector<string>>& graph) {\n    unordered_set<string> currentLevelWords{beginWord};\n\n    while (!currentLevelWords.empty()) {\n      for (const string& word : currentLevelWords)\n        wordSet.erase(word);\n      unordered_set<string> nextLevelWords;\n      bool reachEndWord = false;\n      for (const string& parent : currentLevelWords) {\n        vector<string> children;\n        getChildren(parent, wordSet, children);\n        for (const string& child : children) {\n          if (wordSet.count(child)) {\n            nextLevelWords.insert(child);\n            graph[parent].push_back(child);\n          }\n          if (child == endWord)\n            reachEndWord = true;\n        }\n      }\n      if (reachEndWord)\n        return true;\n      currentLevelWords = move(nextLevelWords);\n    }\n\n    return true;\n  }\n\n  void getChildren(const string& parent, const unordered_set<string>& wordSet,\n                   vector<string>& children) {\n    string s(parent);\n\n    for (int i = 0; i < s.length(); ++i) {\n      const char cache = s[i];\n      for (char c = 'a'; c <= 'z'; ++c) {\n        if (c == cache)\n          continue;\n        s[i] = c;  // Now is `child`\n        if (wordSet.count(s))\n          children.push_back(s);\n      }\n      s[i] = cache;\n    }\n  }\n\n  void dfs(const unordered_map<string, vector<string>>& graph,\n           const string& word, const string& endWord, vector<string>&& path,\n           vector<vector<string>>& ans) {\n    if (word == endWord) {\n      ans.push_back(path);\n      return;\n    }\n    if (!graph.count(word))\n      return;\n\n    for (const string& child : graph.at(word)) {\n      path.push_back(child);\n      dfs(graph, child, endWord, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/126.html",
    "category": "Algorithms",
    "acceptance_rate": 27.155799849378752,
    "topics": [
      "Hash Table",
      "String",
      "Backtracking",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 6244,
    "dislikes": 805,
    "similar_questions": "[{\"title\": \"Word Ladder\", \"titleSlug\": \"word-ladder\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Groups of Strings\", \"titleSlug\": \"groups-of-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"408.2K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 408177, \"totalSubmissionRaw\": 1503100, \"acRate\": \"27.2%\"}",
    "title_pt": "Escada de Palavras II",
    "description_pt": "<p>Uma <strong>sequência de transformação</strong> da palavra <code>beginWord</code> para a palavra <code>endWord</code> usando um dicionário <code>wordList</code> é uma sequência de palavras <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> tal que:</p>\n\n<ul>\n\t<li>Cada par adjacente de palavras difere por uma única letra.</li>\n\t<li>Cada <code>s<sub>i</sub></code> para <code>1 &lt;= i &lt;= k</code> está em <code>wordList</code>. Observe que <code>beginWord</code> não precisa estar em <code>wordList</code>.</li>\n\t<li><code>s<sub>k</sub> == endWord</code></li>\n</ul>\n\n<p>Dadas duas palavras, <code>beginWord</code> e <code>endWord</code>, e um dicionário <code>wordList</code>, retorne <em>todas as <strong>sequências de transformação mais curtas</strong> de</em> <code>beginWord</code> <em>para</em> <code>endWord</code><em>, ou uma lista vazia se não existir tal sequência. Cada sequência deve ser retornada como uma lista das palavras </em><code>[beginWord, s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub>]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]\n<strong>Saída:</strong> [[&quot;hit&quot;,&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;cog&quot;],[&quot;hit&quot;,&quot;hot&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]]\n<strong>Explicação:</strong>&nbsp;Há 2 sequências de transformação mais curtas:\n&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; &quot;cog&quot;\n&quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;lot&quot; -&gt; &quot;log&quot; -&gt; &quot;cog&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> A palavra final &quot;cog&quot; não está em wordList, portanto não existe nenhuma sequência de transformação válida.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= beginWord.length &lt;= 5</code></li>\n\t<li><code>endWord.length == beginWord.length</code></li>\n\t<li><code>1 &lt;= wordList.length &lt;= 500</code></li>\n\t<li><code>wordList[i].length == beginWord.length</code></li>\n\t<li><code>beginWord</code>, <code>endWord</code>, e <code>wordList[i]</code> consistem de letras minúsculas do alfabeto inglês.</li>\n\t<li><code>beginWord != endWord</code></li>\n\t<li>Todas as palavras em <code>wordList</code> são <strong>únicas</strong>.</li>\n\t<li>A <strong>soma</strong> de todas as sequências de transformação mais curtas não excede <code>10<sup>5</sup></code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "127",
    "paidOnly": false,
    "title": "Word Ladder",
    "titleSlug": "word-ladder",
    "url": "https://leetcode.com/problems/word-ladder",
    "description_url": "https://leetcode.com/problems/word-ladder/description/",
    "description": "<p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p>\n\n<ul>\n\t<li>Every adjacent pair of words differs by a single letter.</li>\n\t<li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>\n\t<li><code>s<sub>k</sub> == endWord</code></li>\n</ul>\n\n<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> One shortest transformation sequence is &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; cog&quot;, which is 5 words long.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The endWord &quot;cog&quot; is not in wordList, therefore there is no valid transformation sequence.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= beginWord.length &lt;= 10</code></li>\n\t<li><code>endWord.length == beginWord.length</code></li>\n\t<li><code>1 &lt;= wordList.length &lt;= 5000</code></li>\n\t<li><code>wordList[i].length == beginWord.length</code></li>\n\t<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>\n\t<li><code>beginWord != endWord</code></li>\n\t<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-ladder/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n    wordSet = set(wordList)\n    if endWord not in wordSet:\n      return 0\n\n    ans = 0\n    q = deque([beginWord])\n\n    while q:\n      ans += 1\n      for _ in range(len(q)):\n        wordList = list(q.popleft())\n        for i, cache in enumerate(wordList):\n          for c in string.ascii_lowercase:\n            wordList[i] = c\n            word = ''.join(wordList)\n            if word == endWord:\n              return ans + 1\n            if word in wordSet:\n              q.append(word)\n              wordSet.remove(word)\n          wordList[i] = cache\n\n    return 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int ladderLength(String beginWord, String endWord, List<String> wordList) {\n    Set<String> wordSet = new HashSet<>(wordList);\n    if (!wordSet.contains(endWord))\n      return 0;\n\n    int ans = 0;\n    Queue<String> q = new ArrayDeque<>(Arrays.asList(beginWord));\n\n    while (!q.isEmpty()) {\n      ++ans;\n      for (int sz = q.size(); sz > 0; --sz) {\n        StringBuilder sb = new StringBuilder(q.poll());\n        for (int i = 0; i < sb.length(); ++i) {\n          final char cache = sb.charAt(i);\n          for (char c = 'a'; c <= 'z'; ++c) {\n            sb.setCharAt(i, c);\n            final String word = sb.toString();\n            if (word.equals(endWord))\n              return ans + 1;\n            if (wordSet.contains(word)) {\n              q.offer(word);\n              wordSet.remove(word);\n            }\n          }\n          sb.setCharAt(i, cache);\n        }\n      }\n    }\n\n    return 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int ladderLength(string beginWord, string endWord, vector<string>& wordList) {\n    unordered_set<string> wordSet(begin(wordList), end(wordList));\n    if (!wordSet.count(endWord))\n      return 0;\n\n    int ans = 0;\n    queue<string> q{{beginWord}};\n\n    while (!q.empty()) {\n      ++ans;\n      for (int sz = q.size(); sz > 0; --sz) {\n        string word = q.front();\n        q.pop();\n        for (int i = 0; i < word.length(); ++i) {\n          const char cache = word[i];\n          for (char c = 'a'; c <= 'z'; ++c) {\n            word[i] = c;\n            if (word == endWord)\n              return ans + 1;\n            if (wordSet.count(word)) {\n              q.push(word);\n              wordSet.erase(word);\n            }\n          }\n          word[i] = cache;\n        }\n      }\n    }\n\n    return 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/127.html",
    "category": "Algorithms",
    "acceptance_rate": 42.48887716996447,
    "topics": [
      "Hash Table",
      "String",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 12708,
    "dislikes": 1926,
    "similar_questions": "[{\"title\": \"Word Ladder II\", \"titleSlug\": \"word-ladder-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Genetic Mutation\", \"titleSlug\": \"minimum-genetic-mutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Words Within Two Edits of Dictionary\", \"titleSlug\": \"words-within-two-edits-of-dictionary\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"3.1M\", \"totalAcceptedRaw\": 1337466, \"totalSubmissionRaw\": 3147804, \"acRate\": \"42.5%\"}",
    "title_pt": "Escada de Palavras",
    "description_pt": "<p>Uma <strong>sequência de transformação</strong> de uma palavra <code>beginWord</code> para uma palavra <code>endWord</code> usando um dicionário <code>wordList</code> é uma sequência de palavras <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> tal que:</p>\n\n<ul>\n\t<li>Todo par adjacente de palavras difere por uma única letra.</li>\n\t<li>Todo <code>s<sub>i</sub></code> para <code>1 &lt;= i &lt;= k</code> está em <code>wordList</code>. Observe que <code>beginWord</code> não precisa estar em <code>wordList</code>.</li>\n\t<li><code>s<sub>k</sub> == endWord</code></li>\n</ul>\n\n<p>Dadas duas palavras, <code>beginWord</code> e <code>endWord</code>, e um dicionário <code>wordList</code>, retorne <em>o <strong>número de palavras</strong> na <strong>sequência de transformação mais curta</strong> de</em> <code>beginWord</code> <em>para</em> <code>endWord</code><em>, ou </em><code>0</code><em> se não existir tal sequência.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Uma sequência de transformação mais curta é &quot;hit&quot; -&gt; &quot;hot&quot; -&gt; &quot;dot&quot; -&gt; &quot;dog&quot; -&gt; cog&quot;, que tem 5 palavras.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> beginWord = &quot;hit&quot;, endWord = &quot;cog&quot;, wordList = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> A palavra final &quot;cog&quot; não está em wordList, portanto não existe uma sequência de transformação válida.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= beginWord.length &lt;= 10</code></li>\n\t<li><code>endWord.length == beginWord.length</code></li>\n\t<li><code>1 &lt;= wordList.length &lt;= 5000</code></li>\n\t<li><code>wordList[i].length == beginWord.length</code></li>\n\t<li><code>beginWord</code>, <code>endWord</code> e <code>wordList[i]</code> consistem de letras minúsculas do alfabeto inglês.</li>\n\t<li><code>beginWord != endWord</code></li>\n\t<li>Todas as palavras em <code>wordList</code> são <strong>únicas</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "128",
    "paidOnly": false,
    "title": "Longest Consecutive Sequence",
    "titleSlug": "longest-consecutive-sequence",
    "url": "https://leetcode.com/problems/longest-consecutive-sequence",
    "description_url": "https://leetcode.com/problems/longest-consecutive-sequence/description/",
    "description": "<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>\n\n<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [100,4,200,1,3,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]\n<strong>Output:</strong> 9\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,0,1,2]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-consecutive-sequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestConsecutive(self, nums: List[int]) -> int:\n    ans = 0\n    seen = set(nums)\n\n    for num in nums:\n      if num - 1 in seen:\n        continue\n      length = 0\n      while num in seen:\n        num += 1\n        length += 1\n      ans = max(ans, length)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestConsecutive(int[] nums) {\n    int ans = 0;\n    Set<Integer> seen = Arrays.stream(nums).boxed().collect(Collectors.toSet());\n\n    for (int num : nums) {\n      // Num is the start of a sequence\n      if (seen.contains(num - 1))\n        continue;\n      int length = 1;\n      while (seen.contains(++num))\n        ++length;\n      ans = Math.max(ans, length);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestConsecutive(vector<int>& nums) {\n    int ans = 0;\n    unordered_set<int> seen{begin(nums), end(nums)};\n\n    for (int num : nums) {\n      // Num is the start of a sequence\n      if (seen.count(num - 1))\n        continue;\n      int length = 1;\n      while (seen.count(++num))\n        ++length;\n      ans = max(ans, length);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/128.html",
    "category": "Algorithms",
    "acceptance_rate": 47.06540991416558,
    "topics": [
      "Array",
      "Hash Table",
      "Union Find"
    ],
    "hints": [],
    "likes": 21318,
    "dislikes": 1141,
    "similar_questions": "[{\"title\": \"Binary Tree Longest Consecutive Sequence\", \"titleSlug\": \"binary-tree-longest-consecutive-sequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Three Consecutive Integers That Sum to a Given Number\", \"titleSlug\": \"find-three-consecutive-integers-that-sum-to-a-given-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Consecutive Floors Without Special Floors\", \"titleSlug\": \"maximum-consecutive-floors-without-special-floors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Length of the Longest Alphabetical Continuous Substring\", \"titleSlug\": \"length-of-the-longest-alphabetical-continuous-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Number of Elements in Subset\", \"titleSlug\": \"find-the-maximum-number-of-elements-in-subset\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"5.3M\", \"totalAcceptedRaw\": 2510287, \"totalSubmissionRaw\": 5333604, \"acRate\": \"47.1%\"}",
    "title_pt": "Sequência Consecutiva Mais Longa",
    "description_pt": "<p>Dado um <em>array</em> desordenado de inteiros <code>nums</code>, retorne <em>o comprimento da sequência mais longa de elementos consecutivos.</em></p>\n\n<p>Você deve escrever um algoritmo que execute em tempo&nbsp;<code>O(n)</code>&nbsp;.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [100,4,200,1,3,2]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> A sequência mais longa de elementos consecutivos é <code>[1, 2, 3, 4]</code>. Portanto, seu comprimento é 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,3,7,2,5,8,4,6,0,1]\n<strong>Saída:</strong> 9\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,0,1,2]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "129",
    "paidOnly": false,
    "title": "Sum Root to Leaf Numbers",
    "titleSlug": "sum-root-to-leaf-numbers",
    "url": "https://leetcode.com/problems/sum-root-to-leaf-numbers",
    "description_url": "https://leetcode.com/problems/sum-root-to-leaf-numbers/description/",
    "description": "<p>You are given the <code>root</code> of a binary tree containing digits from <code>0</code> to <code>9</code> only.</p>\n\n<p>Each root-to-leaf path in the tree represents a number.</p>\n\n<ul>\n\t<li>For example, the root-to-leaf path <code>1 -&gt; 2 -&gt; 3</code> represents the number <code>123</code>.</li>\n</ul>\n\n<p>Return <em>the total sum of all root-to-leaf numbers</em>. Test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>\n\n<p>A <strong>leaf</strong> node is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg\" style=\"width: 212px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3]\n<strong>Output:</strong> 25\n<strong>Explanation:</strong>\nThe root-to-leaf path <code>1-&gt;2</code> represents the number <code>12</code>.\nThe root-to-leaf path <code>1-&gt;3</code> represents the number <code>13</code>.\nTherefore, sum = 12 + 13 = <code>25</code>.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [4,9,0,5,1]\n<strong>Output:</strong> 1026\n<strong>Explanation:</strong>\nThe root-to-leaf path <code>4-&gt;9-&gt;5</code> represents the number 495.\nThe root-to-leaf path <code>4-&gt;9-&gt;1</code> represents the number 491.\nThe root-to-leaf path <code>4-&gt;0</code> represents the number 40.\nTherefore, sum = 495 + 491 + 40 = <code>1026</code>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>The depth of the tree will not exceed <code>10</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sum-root-to-leaf-numbers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def sumNumbers(self, root: Optional[TreeNode]) -> int:\n    ans = 0\n\n    def dfs(root: Optional[TreeNode], path: int) -> None:\n      nonlocal ans\n      if not root:\n        return\n      if not root.left and not root.right:\n        ans += path * 10 + root.val\n        return\n\n      dfs(root.left, path * 10 + root.val)\n      dfs(root.right, path * 10 + root.val)\n\n    dfs(root, 0)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int sumNumbers(TreeNode root) {\n    dfs(root, 0);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  private void dfs(TreeNode root, int path) {\n    if (root == null)\n      return;\n    if (root.left == null && root.right == null) {\n      ans += path * 10 + root.val;\n      return;\n    }\n\n    dfs(root.left, path * 10 + root.val);\n    dfs(root.right, path * 10 + root.val);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int sumNumbers(TreeNode* root) {\n    int ans = 0;\n    dfs(root, 0, ans);\n    return ans;\n  }\n\n private:\n  void dfs(TreeNode* root, int path, int& ans) {\n    if (root == nullptr)\n      return;\n    if (root->left == nullptr && root->right == nullptr) {\n      ans += path * 10 + root->val;\n      return;\n    }\n\n    dfs(root->left, path * 10 + root->val, ans);\n    dfs(root->right, path * 10 + root->val, ans);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/129.html",
    "category": "Algorithms",
    "acceptance_rate": 68.3608203925727,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8385,
    "dislikes": 146,
    "similar_questions": "[{\"title\": \"Path Sum\", \"titleSlug\": \"path-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Maximum Path Sum\", \"titleSlug\": \"binary-tree-maximum-path-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Smallest String Starting From Leaf\", \"titleSlug\": \"smallest-string-starting-from-leaf\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1098507, \"totalSubmissionRaw\": 1606925, \"acRate\": \"68.4%\"}",
    "title_pt": "Somar Números da Raiz até as Folhas",
    "description_pt": "<p>Você recebe a <code>root</code> de uma árvore binária contendo apenas dígitos de <code>0</code> a <code>9</code>.</p>\n\n<p>Cada caminho da raiz até uma folha na árvore representa um número.</p>\n\n<ul>\n\t<li>Por exemplo, o caminho da raiz até a folha <code>1 -&gt; 2 -&gt; 3</code> representa o número <code>123</code>.</li>\n</ul>\n\n<p>Retorne <em>a soma total de todos os números da raiz até as folhas</em>. Os casos de teste são gerados de modo que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>Um nó <strong>folha</strong> é um nó sem filhos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg\" style=\"width: 212px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3]\n<strong>Saída:</strong> 25\n<strong>Explicação:</strong>\nO caminho da raiz até a folha <code>1-&gt;2</code> representa o número <code>12</code>.\nO caminho da raiz até a folha <code>1-&gt;3</code> representa o número <code>13</code>.\nPortanto, soma = 12 + 13 = <code>25</code>.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,9,0,5,1]\n<strong>Saída:</strong> 1026\n<strong>Explicação:</strong>\nO caminho da raiz até a folha <code>4-&gt;9-&gt;5</code> representa o número 495.\nO caminho da raiz até a folha <code>4-&gt;9-&gt;1</code> representa o número 491.\nO caminho da raiz até a folha <code>4-&gt;0</code> representa o número 40.\nPortanto, soma = 495 + 491 + 40 = <code>1026</code>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 1000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>A profundidade da árvore não excederá <code>10</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "130",
    "paidOnly": false,
    "title": "Surrounded Regions",
    "titleSlug": "surrounded-regions",
    "url": "https://leetcode.com/problems/surrounded-regions",
    "description_url": "https://leetcode.com/problems/surrounded-regions/description/",
    "description": "<p>You are given an <code>m x n</code> matrix <code>board</code> containing <strong>letters</strong> <code>&#39;X&#39;</code> and <code>&#39;O&#39;</code>, <strong>capture regions</strong> that are <strong>surrounded</strong>:</p>\n\n<ul>\n\t<li><strong>Connect</strong>: A cell is connected to adjacent cells horizontally or vertically.</li>\n\t<li><strong>Region</strong>: To form a region <strong>connect every</strong> <code>&#39;O&#39;</code> cell.</li>\n\t<li><strong>Surround</strong>: The region is surrounded with <code>&#39;X&#39;</code> cells if you can <strong>connect the region </strong>with <code>&#39;X&#39;</code> cells and none of the region cells are on the edge of the <code>board</code>.</li>\n</ul>\n\n<p>To capture a <strong>surrounded region</strong>, replace all <code>&#39;O&#39;</code>s with <code>&#39;X&#39;</code>s <strong>in-place</strong> within the original board. You do not need to return anything.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">board = [[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;O&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;O&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;X&quot;,&quot;X&quot;]]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;X&quot;,&quot;X&quot;]]</span></p>\n\n<p><strong>Explanation:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg\" style=\"width: 367px; height: 158px;\" />\n<p>In the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">board = [[&quot;X&quot;]]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[[&quot;X&quot;]]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>board[i][j]</code> is <code>&#39;X&#39;</code> or <code>&#39;O&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/surrounded-regions/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def solve(self, board: List[List[str]]) -> None:\n    if not board:\n      return\n\n    m = len(board)\n    n = len(board[0])\n    dirs = [0, 1, 0, -1, 0]\n    q = deque()\n\n    for i in range(m):\n      for j in range(n):\n        if i * j == 0 or i == m - 1 or j == n - 1:\n          if board[i][j] == 'O':\n            q.append((i, j))\n            board[i][j] = '*'\n\n    # Mark grids that stretch from four sides with '*'\n    while q:\n      i, j = q.popleft()\n      for k in range(4):\n        x = i + dirs[k]\n        y = j + dirs[k + 1]\n        if x < 0 or x == m or y < 0 or y == n:\n          continue\n        if board[x][y] != 'O':\n          continue\n        q.append((x, y))\n        board[x][y] = '*'\n\n    for row in board:\n      for i, c in enumerate(row):\n        row[i] = 'O' if c == '*' else 'X'",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void solve(char[][] board) {\n    if (board.length == 0)\n      return;\n\n    final int m = board.length;\n    final int n = board[0].length;\n    final int[] dirs = {0, 1, 0, -1, 0};\n    Queue<int[]> q = new ArrayDeque<>();\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (i * j == 0 || i == m - 1 || j == n - 1)\n          if (board[i][j] == 'O') {\n            q.offer(new int[] {i, j});\n            board[i][j] = '*';\n          }\n\n    // Mark grids that stretch from four sides with '*'\n    while (!q.isEmpty()) {\n      final int i = q.peek()[0];\n      final int j = q.poll()[1];\n      for (int k = 0; k < 4; ++k) {\n        final int x = i + dirs[k];\n        final int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (board[x][y] != 'O')\n          continue;\n        q.offer(new int[] {x, y});\n        board[x][y] = '*';\n      }\n    }\n\n    for (char[] row : board)\n      for (int i = 0; i < row.length; ++i)\n        if (row[i] == '*')\n          row[i] = 'O';\n        else if (row[i] == 'O')\n          row[i] = 'X';\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void solve(vector<vector<char>>& board) {\n    if (board.empty())\n      return;\n\n    const int m = board.size();\n    const int n = board[0].size();\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    queue<pair<int, int>> q;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (i * j == 0 || i == m - 1 || j == n - 1)\n          if (board[i][j] == 'O') {\n            q.emplace(i, j);\n            board[i][j] = '*';\n          }\n\n    // Mark grids that stretch from four sides with '*'\n    while (!q.empty()) {\n      const auto [i, j] = q.front();\n      q.pop();\n      for (int k = 0; k < 4; ++k) {\n        const int x = i + dirs[k];\n        const int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (board[x][y] != 'O')\n          continue;\n        q.emplace(x, y);\n        board[x][y] = '*';\n      }\n    }\n\n    for (vector<char>& row : board)\n      for (char& c : row)\n        if (c == '*')\n          c = 'O';\n        else if (c == 'O')\n          c = 'X';\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/130.html",
    "category": "Algorithms",
    "acceptance_rate": 42.58953870988612,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Matrix"
    ],
    "hints": [],
    "likes": 9193,
    "dislikes": 2071,
    "similar_questions": "[{\"title\": \"Number of Islands\", \"titleSlug\": \"number-of-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Walls and Gates\", \"titleSlug\": \"walls-and-gates\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"941.3K\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 941335, \"totalSubmissionRaw\": 2210263, \"acRate\": \"42.6%\"}",
    "title_pt": "Regiões Cercadas",
    "description_pt": "<p>Você recebe uma matriz <code>m x n</code> <code>board</code> contendo <strong>letras</strong> <code>&#39;X&#39;</code> e <code>&#39;O&#39;</code>, <strong>capture as regiões</strong> que estão <strong>cercadas</strong>:</p>\n\n<ul>\n\t<li><strong>Conectar</strong>: Uma célula está conectada a células adjacentes horizontalmente ou verticalmente.</li>\n\t<li><strong>Região</strong>: Para formar uma região, <strong>conecte cada</strong> célula <code>&#39;O&#39;</code>.</li>\n\t<li><strong>Cercar</strong>: A região é cercada por células <code>&#39;X&#39;</code> se você puder <strong>conectar a região </strong>com células <code>&#39;X&#39;</code> e nenhuma das células da região estiver na borda da <code>board</code>.</li>\n</ul>\n\n<p>Para capturar uma <strong>região cercada</strong>, substitua todos os <code>&#39;O&#39;</code>s por <code>&#39;X&#39;</code>s <strong>in-place</strong> dentro da board original. Você não precisa retornar nada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">board = [[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;O&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;O&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;X&quot;,&quot;X&quot;]]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;],[&quot;X&quot;,&quot;O&quot;,&quot;X&quot;,&quot;X&quot;]]</span></p>\n\n<p><strong>Explicação:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg\" style=\"width: 367px; height: 158px;\" />\n<p>No diagrama acima, a região inferior não é capturada porque está na borda da board e não pode ser cercada.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">board = [[&quot;X&quot;]]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[[&quot;X&quot;]]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>board[i][j]</code> é <code>&#39;X&#39;</code> ou <code>&#39;O&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "131",
    "paidOnly": false,
    "title": "Palindrome Partitioning",
    "titleSlug": "palindrome-partitioning",
    "url": "https://leetcode.com/problems/palindrome-partitioning",
    "description_url": "https://leetcode.com/problems/palindrome-partitioning/description/",
    "description": "<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword=\"substring-nonempty\">substring</span> of the partition is a <span data-keyword=\"palindrome-string\"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"aab\"\n<strong>Output:</strong> [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"a\"\n<strong>Output:</strong> [[\"a\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 16</code></li>\n\t<li><code>s</code> contains only lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/palindrome-partitioning/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def partition(self, s: str) -> List[List[str]]:\n    ans = []\n\n    def isPalindrome(s: str) -> bool:\n      return s == s[::-1]\n\n    def dfs(s: str, j: int, path: List[str], ans: List[List[str]]) -> None:\n      if j == len(s):\n        ans.append(path)\n        return\n\n      for i in range(j, len(s)):\n        if isPalindrome(s[j: i + 1]):\n          dfs(s, i + 1, path + [s[j: i + 1]], ans)\n\n    dfs(s, 0, [], ans)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> partition(String s) {\n    List<List<String>> ans = new ArrayList<>();\n    dfs(s, 0, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(final String s, int start, List<String> path, List<List<String>> ans) {\n    if (start == s.length()) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n\n    for (int i = start; i < s.length(); ++i)\n      if (isPalindrome(s, start, i)) {\n        path.add(s.substring(start, i + 1));\n        dfs(s, i + 1, path, ans);\n        path.remove(path.size() - 1);\n      }\n  }\n\n  private boolean isPalindrome(final String s, int l, int r) {\n    while (l < r)\n      if (s.charAt(l++) != s.charAt(r--))\n        return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> partition(string s) {\n    vector<vector<string>> ans;\n    dfs(s, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const string& s, int start, vector<string>&& path,\n           vector<vector<string>>& ans) {\n    if (start == s.length()) {\n      ans.push_back(path);\n      return;\n    }\n\n    for (int i = start; i < s.length(); ++i)\n      if (isPalindrome(s, start, i)) {\n        path.push_back(s.substr(start, i - start + 1));\n        dfs(s, i + 1, move(path), ans);\n        path.pop_back();\n      }\n  }\n\n  bool isPalindrome(const string& s, int l, int r) {\n    while (l < r)\n      if (s[l++] != s[r--])\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/131.html",
    "category": "Algorithms",
    "acceptance_rate": 71.84519340713959,
    "topics": [
      "String",
      "Dynamic Programming",
      "Backtracking"
    ],
    "hints": [],
    "likes": 13492,
    "dislikes": 541,
    "similar_questions": "[{\"title\": \"Palindrome Partitioning II\", \"titleSlug\": \"palindrome-partitioning-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Palindrome Partitioning IV\", \"titleSlug\": \"palindrome-partitioning-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Non-overlapping Palindrome Substrings\", \"titleSlug\": \"maximum-number-of-non-overlapping-palindrome-substrings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 1101456, \"totalSubmissionRaw\": 1533101, \"acRate\": \"71.8%\"}",
    "title_pt": "Particionamento em Palíndromos",
    "description_pt": "<p>Dada uma string <code>s</code>, particione <code>s</code> de modo que toda <span data-keyword=\"substring-nonempty\">substring</span> da partição seja um <span data-keyword=\"palindrome-string\"><strong>palíndromo</strong></span>. Retorne <em>todas as partições possíveis em palíndromos de </em><code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"aab\"\n<strong>Saída:</strong> [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"a\"\n<strong>Saída:</strong> [[\"a\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 16</code></li>\n\t<li><code>s</code> contém apenas letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "132",
    "paidOnly": false,
    "title": "Palindrome Partitioning II",
    "titleSlug": "palindrome-partitioning-ii",
    "url": "https://leetcode.com/problems/palindrome-partitioning-ii",
    "description_url": "https://leetcode.com/problems/palindrome-partitioning-ii/description/",
    "description": "<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword=\"substring-nonempty\">substring</span> of the partition is a <span data-keyword=\"palindrome-string\">palindrome</span>.</p>\n\n<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aab&quot;\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The palindrome partitioning [&quot;aa&quot;,&quot;b&quot;] could be produced using 1 cut.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a&quot;\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;ab&quot;\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2000</code></li>\n\t<li><code>s</code> consists of lowercase English letters only.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/palindrome-partitioning-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minCut(self, s: str) -> int:\n    n = len(s)\n    cut = [0] * n\n    dp = [[False] * n for _ in range(n)]\n\n    for i in range(n):\n      mini = i\n      for j in range(i + 1):\n        if s[j] == s[i] and (j + 1 > i - 1 or dp[j + 1][i - 1]):\n          dp[j][i] = True\n          mini = 0 if j == 0 else min(mini, cut[j - 1] + 1)\n      cut[i] = mini\n\n    return cut[n - 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minCut(String s) {\n    final int n = s.length();\n    // isPalindrome[i][j] := true if s[i..j] is a palindrome\n    boolean[][] isPalindrome = new boolean[n][n];\n    for (boolean[] row : isPalindrome)\n      Arrays.fill(row, true);\n    // dp[i] := min cuts needed for a palindrome partitioning of s[0..i]\n    int[] dp = new int[n];\n    Arrays.fill(dp, n);\n\n    for (int l = 2; l <= n; ++l)\n      for (int i = 0, j = l - 1; j < n; ++i, ++j)\n        isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1];\n\n    for (int i = 0; i < n; ++i) {\n      if (isPalindrome[0][i]) {\n        dp[i] = 0;\n        continue;\n      }\n\n      // Try all possible partitions\n      for (int j = 0; j < i; ++j)\n        if (isPalindrome[j + 1][i])\n          dp[i] = Math.min(dp[i], dp[j] + 1);\n    }\n\n    return dp[n - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minCut(string s) {\n    const int n = s.length();\n    // isPalindrome[i][j] := true if s[i..j] is a palindrome\n    vector<vector<bool>> isPalindrome(n, vector<bool>(n, true));\n    // dp[i] := min cuts needed for a palindrome partitioning of s[0..i]\n    vector<int> dp(n, n);\n\n    for (int l = 2; l <= n; ++l)\n      for (int i = 0, j = l - 1; j < n; ++i, ++j)\n        isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i + 1][j - 1];\n\n    for (int i = 0; i < n; ++i) {\n      if (isPalindrome[0][i]) {\n        dp[i] = 0;\n        continue;\n      }\n\n      // Try all possible partitions\n      for (int j = 0; j < i; ++j)\n        if (isPalindrome[j + 1][i])\n          dp[i] = min(dp[i], dp[j] + 1);\n    }\n\n    return dp.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/132.html",
    "category": "Algorithms",
    "acceptance_rate": 35.1120649095213,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 5647,
    "dislikes": 144,
    "similar_questions": "[{\"title\": \"Palindrome Partitioning\", \"titleSlug\": \"palindrome-partitioning\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Partitioning IV\", \"titleSlug\": \"palindrome-partitioning-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Non-overlapping Palindrome Substrings\", \"titleSlug\": \"maximum-number-of-non-overlapping-palindrome-substrings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Great Partitions\", \"titleSlug\": \"number-of-great-partitions\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"335.1K\", \"totalSubmission\": \"954.3K\", \"totalAcceptedRaw\": 335076, \"totalSubmissionRaw\": 954308, \"acRate\": \"35.1%\"}",
    "title_pt": "Particionamento de Palíndromos II",
    "description_pt": "<p>Dada uma string <code>s</code>, divida <code>s</code> de modo que toda <span data-keyword=\"substring-nonempty\">substring</span> da partição seja um <span data-keyword=\"palindrome-string\">palíndromo</span>.</p>\n\n<p>Retorne <em>o número <strong>mínimo</strong> de cortes necessários para uma partição em palíndromos de</em> <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aab&quot;\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> A partição em palíndromos [&quot;aa&quot;,&quot;b&quot;] poderia ser produzida usando 1 corte.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a&quot;\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;ab&quot;\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2000</code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "133",
    "paidOnly": false,
    "title": "Clone Graph",
    "titleSlug": "clone-graph",
    "url": "https://leetcode.com/problems/clone-graph",
    "description_url": "https://leetcode.com/problems/clone-graph/description/",
    "description": "<p>Given a reference of a node in a <strong><a href=\"https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph\" target=\"_blank\">connected</a></strong> undirected graph.</p>\n\n<p>Return a <a href=\"https://en.wikipedia.org/wiki/Object_copying#Deep_copy\" target=\"_blank\"><strong>deep copy</strong></a> (clone) of the graph.</p>\n\n<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>\n\n<pre>\nclass Node {\n    public int val;\n    public List&lt;Node&gt; neighbors;\n}\n</pre>\n\n<p>&nbsp;</p>\n\n<p><strong>Test case format:</strong></p>\n\n<p>For simplicity, each node&#39;s value is the same as the node&#39;s index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>\n\n<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>\n\n<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png\" style=\"width: 454px; height: 500px;\" />\n<pre>\n<strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]\n<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]\n<strong>Explanation:</strong> There are 4 nodes in the graph.\n1st node (val = 1)&#39;s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)&#39;s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)&#39;s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)&#39;s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/07/graph.png\" style=\"width: 163px; height: 148px;\" />\n<pre>\n<strong>Input:</strong> adjList = [[]]\n<strong>Output:</strong> [[]]\n<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> adjList = []\n<strong>Output:</strong> []\n<strong>Explanation:</strong> This an empty graph, it does not have any nodes.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>Node.val</code> is unique for each node.</li>\n\t<li>There are no repeated edges and no self-loops in the graph.</li>\n\t<li>The Graph is connected and all nodes can be visited starting from the given node.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/clone-graph/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def cloneGraph(self, node: 'Node') -> 'Node':\n    if not node:\n      return None\n\n    q = deque([node])\n    map = {node: Node(node.val)}\n\n    while q:\n      u = q.popleft()\n      for v in u.neighbors:\n        if v not in map:\n          map[v] = Node(v.val)\n          q.append(v)\n        map[u].neighbors.append(map[v])\n\n    return map[node]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node cloneGraph(Node node) {\n    if (node == null)\n      return null;\n\n    Queue<Node> q = new ArrayDeque<>(Arrays.asList(node));\n    Map<Node, Node> map = new HashMap<>();\n    map.put(node, new Node(node.val));\n\n    while (!q.isEmpty()) {\n      Node u = q.poll();\n      for (Node v : u.neighbors) {\n        if (!map.containsKey(v)) {\n          map.put(v, new Node(v.val));\n          q.offer(v);\n        }\n        map.get(u).neighbors.add(map.get(v));\n      }\n    }\n\n    return map.get(node);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* cloneGraph(Node* node) {\n    if (node == nullptr)\n      return nullptr;\n\n    queue<Node*> q{{node}};\n    unordered_map<Node*, Node*> map{{node, new Node(node->val)}};\n\n    while (!q.empty()) {\n      Node* u = q.front();\n      q.pop();\n      for (Node* v : u->neighbors) {\n        if (!map.count(v)) {\n          map[v] = new Node(v->val);\n          q.push(v);\n        }\n        map[u]->neighbors.push_back(map[v]);\n      }\n    }\n\n    return map[node];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/133.html",
    "category": "Algorithms",
    "acceptance_rate": 61.996213401533076,
    "topics": [
      "Hash Table",
      "Depth-First Search",
      "Breadth-First Search",
      "Graph"
    ],
    "hints": [],
    "likes": 10007,
    "dislikes": 4041,
    "similar_questions": "[{\"title\": \"Copy List with Random Pointer\", \"titleSlug\": \"copy-list-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone Binary Tree With Random Pointer\", \"titleSlug\": \"clone-binary-tree-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone N-ary Tree\", \"titleSlug\": \"clone-n-ary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1573727, \"totalSubmissionRaw\": 2538423, \"acRate\": \"62.0%\"}",
    "title_pt": "Clonar Grafo",
    "description_pt": "<p>Dada uma referência de um nó em um grafo <strong><a href=\"https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph\" target=\"_blank\">conexo</a></strong> não direcionado.</p>\n\n<p>Retorne uma <a href=\"https://en.wikipedia.org/wiki/Object_copying#Deep_copy\" target=\"_blank\"><strong>cópia profunda</strong></a> (clone) do grafo.</p>\n\n<p>Cada nó no grafo contém um valor (<code>int</code>) e uma lista (<code>List[Node]</code>) de seus vizinhos.</p>\n\n<pre>\nclass Node {\n    public int val;\n    public List&lt;Node&gt; neighbors;\n}\n</pre>\n\n<p>&nbsp;</p>\n\n<p><strong>Formato do caso de teste:</strong></p>\n\n<p>Por simplicidade, o valor de cada nó é igual ao índice do nó (indexado em 1). Por exemplo, o primeiro nó tem <code>val == 1</code>, o segundo nó tem <code>val == 2</code>, e assim por diante. O grafo é representado no caso de teste usando uma lista de adjacência.</p>\n\n<p><b>Uma lista de adjacência</b> é uma coleção de <b>listas</b> não ordenadas usada para representar um grafo finito. Cada lista descreve o conjunto de vizinhos de um nó no grafo.</p>\n\n<p>O nó fornecido será sempre o primeiro nó com <code>val = 1</code>. Você deve retornar a <strong>cópia do nó fornecido</strong> como uma referência para o grafo clonado.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png\" style=\"width: 454px; height: 500px;\" />\n<pre>\n<strong>Entrada:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]\n<strong>Saída:</strong> [[2,4],[1,3],[2,4],[1,3]]\n<strong>Explicação:</strong> Há 4 nós no grafo.\nOs vizinhos do 1º nó (val = 1) são o 2º nó (val = 2) e o 4º nó (val = 4).\nOs vizinhos do 2º nó (val = 2) são o 1º nó (val = 1) e o 3º nó (val = 3).\nOs vizinhos do 3º nó (val = 3) são o 2º nó (val = 2) e o 4º nó (val = 4).\nOs vizinhos do 4º nó (val = 4) são o 1º nó (val = 1) e o 3º nó (val = 3).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/01/07/graph.png\" style=\"width: 163px; height: 148px;\" />\n<pre>\n<strong>Entrada:</strong> adjList = [[]]\n<strong>Saída:</strong> [[]]\n<strong>Explicação:</strong> Observe que a entrada contém uma lista vazia. O grafo consiste em apenas um nó com val = 1 e ele não possui vizinhos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> adjList = []\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> Este é um grafo vazio; ele não possui nenhum nó.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós no grafo está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>Node.val</code> é único para cada nó.</li>\n\t<li>Não há arestas repetidas nem laços próprios no grafo.</li>\n\t<li>O grafo é conexo e todos os nós podem ser visitados a partir do nó fornecido.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "134",
    "paidOnly": false,
    "title": "Gas Station",
    "titleSlug": "gas-station",
    "url": "https://leetcode.com/problems/gas-station",
    "description_url": "https://leetcode.com/problems/gas-station/description/",
    "description": "<p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>\n\n<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>\n\n<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station&#39;s index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>\nYou can&#39;t start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet&#39;s start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can&#39;t travel around the circuit once no matter where you start.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == gas.length == cost.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= gas[i], cost[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/gas-station/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n    ans = 0\n    net = 0\n    summ = 0\n\n    for i in range(len(gas)):\n      net += gas[i] - cost[i]\n      summ += gas[i] - cost[i]\n      if summ < 0:\n        summ = 0\n        ans = i + 1\n\n    return -1 if net < 0 else ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int canCompleteCircuit(int[] gas, int[] cost) {\n    final int gasses = Arrays.stream(gas).sum();\n    final int costs = Arrays.stream(cost).sum();\n    if (gasses - costs < 0)\n      return -1;\n\n    int ans = 0;\n    int sum = 0;\n\n    // Try to start from each index\n    for (int i = 0; i < gas.length; ++i) {\n      sum += gas[i] - cost[i];\n      if (sum < 0) {\n        sum = 0;\n        ans = i + 1; // Start from next index\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {\n    const int gasses = accumulate(begin(gas), end(gas), 0);\n    const int costs = accumulate(begin(cost), end(cost), 0);\n    if (gasses - costs < 0)\n      return -1;\n\n    int ans = 0;\n    int sum = 0;\n\n    // Try to start from each index\n    for (int i = 0; i < gas.size(); ++i) {\n      sum += gas[i] - cost[i];\n      if (sum < 0) {\n        sum = 0;\n        ans = i + 1;  // Start from next index\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/134.html",
    "category": "Algorithms",
    "acceptance_rate": 46.243272317508286,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 12677,
    "dislikes": 1290,
    "similar_questions": "[{\"title\": \"Maximize the Topmost Element After K Moves\", \"titleSlug\": \"maximize-the-topmost-element-after-k-moves\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1085843, \"totalSubmissionRaw\": 2348108, \"acRate\": \"46.2%\"}",
    "title_pt": "Estação de Gasolina",
    "description_pt": "<p>Há <code>n</code> estações de gasolina ao longo de uma rota circular, onde a quantidade de gasolina na estação <code>i<sup>th</sup></code> é <code>gas[i]</code>.</p>\n\n<p>Você tem um carro com um tanque de gasolina ilimitado e custa <code>cost[i]</code> de gasolina para viajar da estação <code>i<sup>th</sup></code> até a próxima estação <code>(i + 1)<sup>th</sup></code>. Você inicia a jornada com um tanque vazio em uma das estações de gasolina.</p>\n\n<p>Dadas duas arrays de inteiros <code>gas</code> e <code>cost</code>, retorne <em>o índice da estação de gasolina inicial se você puder percorrer o circuito uma vez no sentido horário; caso contrário, retorne</em> <code>-1</code>. Se existir uma solução, é <strong>garantido</strong> que ela seja <strong>única</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>\nComece na estação 3 (índice 3) e abasteça com 4 unidades de gasolina. Seu tanque = 0 + 4 = 4\nViaje para a estação 4. Seu tanque = 4 - 1 + 5 = 8\nViaje para a estação 0. Seu tanque = 8 - 2 + 1 = 7\nViaje para a estação 1. Seu tanque = 7 - 3 + 2 = 6\nViaje para a estação 2. Seu tanque = 6 - 4 + 3 = 5\nViaje para a estação 3. O custo é 5. Sua gasolina é exatamente suficiente para voltar à estação 3.\nPortanto, retorne 3 como o índice inicial.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> gas = [2,3,4], cost = [3,4,3]\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong>\nVocê não pode começar na estação 0 ou 1, pois não há gasolina suficiente para viajar para a próxima estação.\nVamos começar na estação 2 e abastecer com 4 unidades de gasolina. Seu tanque = 0 + 4 = 4\nViaje para a estação 0. Seu tanque = 4 - 3 + 2 = 3\nViaje para a estação 1. Seu tanque = 3 - 3 + 3 = 3\nVocê não pode voltar para a estação 2, pois isso requer 4 unidades de gasolina, mas você só tem 3.\nPortanto, você não pode percorrer o circuito uma vez, não importa onde comece.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == gas.length == cost.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= gas[i], cost[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "135",
    "paidOnly": false,
    "title": "Candy",
    "titleSlug": "candy",
    "url": "https://leetcode.com/problems/candy",
    "description_url": "https://leetcode.com/problems/candy/description/",
    "description": "<p>There are <code>n</code> children standing in a line. Each child is assigned a rating value given in the integer array <code>ratings</code>.</p>\n\n<p>You are giving candies to these children subjected to the following requirements:</p>\n\n<ul>\n\t<li>Each child must have at least one candy.</li>\n\t<li>Children with a higher rating get more candies than their neighbors.</li>\n</ul>\n\n<p>Return <em>the minimum number of candies you need to have to distribute the candies to the children</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> ratings = [1,0,2]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> ratings = [1,2,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == ratings.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= ratings[i] &lt;= 2 * 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/candy/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def candy(self, ratings: List[int]) -> int:\n    n = len(ratings)\n\n    ans = 0\n    l = [1] * n\n    r = [1] * n\n\n    for i in range(1, n):\n      if ratings[i] > ratings[i - 1]:\n        l[i] = l[i - 1] + 1\n\n    for i in range(n - 2, -1, -1):\n      if ratings[i] > ratings[i + 1]:\n        r[i] = r[i + 1] + 1\n\n    for a, b in zip(l, r):\n      ans += max(a, b)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int candy(int[] ratings) {\n    final int n = ratings.length;\n\n    int ans = 0;\n    int[] l = new int[n];\n    int[] r = new int[n];\n    Arrays.fill(l, 1);\n    Arrays.fill(r, 1);\n\n    for (int i = 1; i < n; ++i)\n      if (ratings[i] > ratings[i - 1])\n        l[i] = l[i - 1] + 1;\n\n    for (int i = n - 2; i >= 0; --i)\n      if (ratings[i] > ratings[i + 1])\n        r[i] = r[i + 1] + 1;\n\n    for (int i = 0; i < n; ++i)\n      ans += Math.max(l[i], r[i]);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int candy(vector<int>& ratings) {\n    const int n = ratings.size();\n    int ans = 0;\n    vector<int> l(n, 1);\n    vector<int> r(n, 1);\n\n    for (int i = 1; i < n; ++i)\n      if (ratings[i] > ratings[i - 1])\n        l[i] = l[i - 1] + 1;\n\n    for (int i = n - 2; i >= 0; --i)\n      if (ratings[i] > ratings[i + 1])\n        r[i] = r[i + 1] + 1;\n\n    for (int i = 0; i < n; ++i)\n      ans += max(l[i], r[i]);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/135.html",
    "category": "Algorithms",
    "acceptance_rate": 44.68818582260315,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 8421,
    "dislikes": 747,
    "similar_questions": "[{\"title\": \"Minimize Maximum Value in a Grid\", \"titleSlug\": \"minimize-maximum-value-in-a-grid\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Satisfy Conditions\", \"titleSlug\": \"minimum-number-of-operations-to-satisfy-conditions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check if Grid Satisfies Conditions\", \"titleSlug\": \"check-if-grid-satisfies-conditions\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"744.8K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 744840, \"totalSubmissionRaw\": 1666767, \"acRate\": \"44.7%\"}",
    "title_pt": "Balas",
    "description_pt": "<p>Há <code>n</code> crianças em pé em fila. Cada criança recebe um valor de classificação dado no array de inteiros <code>ratings</code>.</p>\n\n<p>Você está distribuindo balas para essas crianças, sujeito aos seguintes requisitos:</p>\n\n<ul>\n\t<li>Cada criança deve ter pelo menos uma bala.</li>\n\t<li>Crianças com uma classificação mais alta recebem mais balas do que seus vizinhos.</li>\n</ul>\n\n<p>Retorne <em>o número mínimo de balas que você precisa ter para distribuir as balas às crianças</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ratings = [1,0,2]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Você pode alocar para a primeira, segunda e terceira criança 2, 1, 2 balas, respectivamente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ratings = [1,2,2]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Você pode alocar para a primeira, segunda e terceira criança 1, 2, 1 balas, respectivamente.\nA terceira criança recebe 1 bala porque isso satisfaz as duas condições acima.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == ratings.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= ratings[i] &lt;= 2 * 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "136",
    "paidOnly": false,
    "title": "Single Number",
    "titleSlug": "single-number",
    "url": "https://leetcode.com/problems/single-number",
    "description_url": "https://leetcode.com/problems/single-number/description/",
    "description": "<p>Given a <strong>non-empty</strong>&nbsp;array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>\n\n<p>You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [2,2,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">1</span></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [4,1,2,1,2]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">4</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">1</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-3 * 10<sup>4</sup> &lt;= nums[i] &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li>Each element in the array appears twice except for one element which appears only once.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/single-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def singleNumber(self, nums: List[int]) -> int:\n    return functools.reduce(lambda x, y: x ^ y, nums, 0)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int singleNumber(int[] nums) {\n    int ans = 0;\n\n    for (final int num : nums)\n      ans ^= num;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int singleNumber(vector<int>& nums) {\n    int ans = 0;\n\n    for (const int num : nums)\n      ans ^= num;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/136.html",
    "category": "Algorithms",
    "acceptance_rate": 75.75928517708908,
    "topics": [
      "Array",
      "Bit Manipulation"
    ],
    "hints": [
      "Think about the XOR (^) operator's property."
    ],
    "likes": 17501,
    "dislikes": 808,
    "similar_questions": "[{\"title\": \"Single Number II\", \"titleSlug\": \"single-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Single Number III\", \"titleSlug\": \"single-number-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Missing Number\", \"titleSlug\": \"missing-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Duplicate Number\", \"titleSlug\": \"find-the-duplicate-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Difference\", \"titleSlug\": \"find-the-difference\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the XOR of Numbers Which Appear Twice\", \"titleSlug\": \"find-the-xor-of-numbers-which-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.6M\", \"totalSubmission\": \"4.8M\", \"totalAcceptedRaw\": 3643533, \"totalSubmissionRaw\": 4809356, \"acRate\": \"75.8%\"}",
    "title_pt": "Número Único",
    "description_pt": "<p>Dado um array <strong>não vazio</strong>&nbsp;de inteiros <code>nums</code>, todo elemento aparece <em>duas vezes</em> exceto um. Encontre esse único elemento.</p>\n\n<p>Você deve&nbsp;implementar uma solução com complexidade de tempo linear e usar&nbsp;apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [2,2,1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">1</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [4,1,2,1,2]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">4</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">1</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-3 * 10<sup>4</sup> &lt;= nums[i] &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li>Cada elemento no array aparece duas vezes exceto por um elemento, que aparece apenas uma vez.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Pense sobre a propriedade do operador XOR (^) ."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "137",
    "paidOnly": false,
    "title": "Single Number II",
    "titleSlug": "single-number-ii",
    "url": "https://leetcode.com/problems/single-number-ii",
    "description_url": "https://leetcode.com/problems/single-number-ii/description/",
    "description": "<p>Given an integer array <code>nums</code> where&nbsp;every element appears <strong>three times</strong> except for one, which appears <strong>exactly once</strong>. <em>Find the single element and return it</em>.</p>\n\n<p>You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [2,2,3,2]\n<strong>Output:</strong> 3\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [0,1,0,1,0,1,99]\n<strong>Output:</strong> 99\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Each element in <code>nums</code> appears exactly <strong>three times</strong> except for one element which appears <strong>once</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/single-number-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def singleNumber(self, nums: List[int]) -> int:\n    ones = 0\n    twos = 0\n\n    for num in nums:\n      ones ^= num & ~twos\n      twos ^= num & ~ones\n\n    return ones",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int singleNumber(int[] nums) {\n    int ans = 0;\n\n    for (int i = 0; i < 32; ++i) {\n      int sum = 0;\n      for (final int num : nums)\n        sum += num >> i & 1;\n      sum %= 3;\n      ans |= sum << i;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int singleNumber(vector<int>& nums) {\n    int ans = 0;\n\n    for (int i = 0; i < 32; ++i) {\n      int sum = 0;\n      for (const int num : nums)\n        sum += num >> i & 1;\n      sum %= 3;\n      ans |= sum << i;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/137.html",
    "category": "Algorithms",
    "acceptance_rate": 65.0436972722849,
    "topics": [
      "Array",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 8293,
    "dislikes": 719,
    "similar_questions": "[{\"title\": \"Single Number\", \"titleSlug\": \"single-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Single Number III\", \"titleSlug\": \"single-number-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the XOR of Numbers Which Appear Twice\", \"titleSlug\": \"find-the-xor-of-numbers-which-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"729.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 729813, \"totalSubmissionRaw\": 1122036, \"acRate\": \"65.0%\"}",
    "title_pt": "Número Único II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> em que&nbsp;cada elemento aparece <strong>três vezes</strong>, exceto um, que aparece <strong>exatamente uma vez</strong>. <em>Encontre o elemento único e retorne-o</em>.</p>\n\n<p>Você deve&nbsp;implementar uma solução com complexidade de tempo linear e usar&nbsp;apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [2,2,3,2]\n<strong>Saída:</strong> 3\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [0,1,0,1,0,1,99]\n<strong>Saída:</strong> 99\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Cada elemento em <code>nums</code> aparece exatamente <strong>três vezes</strong>, exceto por um elemento que aparece <strong>uma vez</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "138",
    "paidOnly": false,
    "title": "Copy List with Random Pointer",
    "titleSlug": "copy-list-with-random-pointer",
    "url": "https://leetcode.com/problems/copy-list-with-random-pointer",
    "description_url": "https://leetcode.com/problems/copy-list-with-random-pointer/description/",
    "description": "<p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>\n\n<p>Construct a <a href=\"https://en.wikipedia.org/wiki/Object_copying#Deep_copy\" target=\"_blank\"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>\n\n<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --&gt; Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --&gt; y</code>.</p>\n\n<p>Return <em>the head of the copied linked list</em>.</p>\n\n<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>\n\n<ul>\n\t<li><code>val</code>: an integer representing <code>Node.val</code></li>\n\t<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>\n</ul>\n\n<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e1.png\" style=\"width: 700px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\n<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e2.png\" style=\"width: 700px; height: 114px;\" />\n<pre>\n<strong>Input:</strong> head = [[1,1],[2,1]]\n<strong>Output:</strong> [[1,1],[2,1]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e3.png\" style=\"width: 700px; height: 122px;\" /></strong></p>\n\n<pre>\n<strong>Input:</strong> head = [[3,null],[3,0],[3,null]]\n<strong>Output:</strong> [[3,null],[3,0],[3,null]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 1000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/copy-list-with-random-pointer/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def copyRandomList(self, head: 'Node') -> 'Node':\n    if not head:\n      return None\n    if head in self.map:\n      return self.map[head]\n\n    newNode = Node(head.val)\n    self.map[head] = newNode\n    newNode.next = self.copyRandomList(head.next)\n    newNode.random = self.copyRandomList(head.random)\n    return newNode\n\n  map = {}",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node copyRandomList(Node head) {\n    if (head == null)\n      return null;\n    if (map.containsKey(head))\n      return map.get(head);\n\n    Node newNode = new Node(head.val);\n    map.put(head, newNode);\n    newNode.next = copyRandomList(head.next);\n    newNode.random = copyRandomList(head.random);\n    return newNode;\n  }\n\n  private Map<Node, Node> map = new HashMap<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* copyRandomList(Node* head) {\n    if (head == nullptr)\n      return nullptr;\n    if (map.count(head))\n      return map[head];\n\n    Node* newNode = new Node(head->val);\n    map[head] = newNode;\n    newNode->next = copyRandomList(head->next);\n    newNode->random = copyRandomList(head->random);\n    return newNode;\n  }\n\n private:\n  unordered_map<Node*, Node*> map;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/138.html",
    "category": "Algorithms",
    "acceptance_rate": 60.19918089670693,
    "topics": [
      "Hash Table",
      "Linked List"
    ],
    "hints": [
      "Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, ensure you are not making multiple copies of the same node.",
      "You may want to use extra space to keep old_node ---> new_node mapping to prevent creating multiple copies of the same node.",
      "We can avoid using extra space for old_node ---> new_node mapping by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For example:\r\nOld List: A --> B --> C --> D\r\nInterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D'",
      "The interweaving is done using next</b> pointers and we can make use of interweaved structure to get the correct reference nodes for random</b> pointers."
    ],
    "likes": 14693,
    "dislikes": 1590,
    "similar_questions": "[{\"title\": \"Clone Graph\", \"titleSlug\": \"clone-graph\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone Binary Tree With Random Pointer\", \"titleSlug\": \"clone-binary-tree-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone N-ary Tree\", \"titleSlug\": \"clone-n-ary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1593471, \"totalSubmissionRaw\": 2647013, \"acRate\": \"60.2%\"}",
    "title_pt": "Copiar Lista com Ponteiro Aleatório",
    "description_pt": "<p>Uma lista encadeada de comprimento <code>n</code> é dada de forma que cada nó contém um ponteiro aleatório adicional, que pode apontar para qualquer nó na lista, ou <code>null</code>.</p>\n\n<p>Construa uma <a href=\"https://en.wikipedia.org/wiki/Object_copying#Deep_copy\" target=\"_blank\"><strong>cópia profunda</strong></a> da lista. A cópia profunda deve consistir de exatamente <code>n</code> nós <strong>totalmente novos</strong>, onde cada novo nó tem seu valor definido como o valor do nó original correspondente. Tanto o ponteiro <code>next</code> quanto o ponteiro <code>random</code> dos novos nós devem apontar para novos nós na lista copiada, de modo que os ponteiros na lista original e na lista copiada representem o mesmo estado da lista. <strong>Nenhum dos ponteiros na nova lista deve apontar para nós na lista original</strong>.</p>\n\n<p>Por exemplo, se houver dois nós <code>X</code> e <code>Y</code> na lista original, em que <code>X.random --&gt; Y</code>, então, para os dois nós correspondentes <code>x</code> e <code>y</code> na lista copiada, <code>x.random --&gt; y</code>.</p>\n\n<p>Retorne <em>a cabeça da lista encadeada copiada</em>.</p>\n\n<p>A lista encadeada é representada na entrada/saída como uma lista de <code>n</code> nós. Cada nó é representado como um par de <code>[val, random_index]</code> em que:</p>\n\n<ul>\n\t<li><code>val</code>: um inteiro representando <code>Node.val</code></li>\n\t<li><code>random_index</code>: o índice do nó (variando de <code>0</code> a <code>n-1</code>) para o qual o ponteiro <code>random</code> aponta, ou <code>null</code> se ele não apontar para nenhum nó.</li>\n</ul>\n\n<p>Seu código receberá <strong>apenas</strong> a <code>head</code> da lista encadeada original.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e1.png\" style=\"width: 700px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\n<strong>Saída:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e2.png\" style=\"width: 700px; height: 114px;\" />\n<pre>\n<strong>Entrada:</strong> head = [[1,1],[2,1]]\n<strong>Saída:</strong> [[1,1],[2,1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<p><strong><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/12/18/e3.png\" style=\"width: 700px; height: 122px;\" /></strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [[3,null],[3,0],[3,null]]\n<strong>Saída:</strong> [[3,null],[3,0],[3,null]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 1000</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>Node.random</code> é <code>null</code> ou aponta para algum nó na lista encadeada.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Apenas percorra a lista encadeada e crie cópias dos nós conforme avança. Como um nó pode ser referenciado por vários nós devido aos ponteiros random, certifique-se de não fazer várias cópias do mesmo nó.",
      "Dica 2: Você pode querer usar espaço extra para manter o mapeamento old_node ---> new_node e evitar criar várias cópias do mesmo nó.",
      "Dica 3: Podemos evitar o uso de espaço extra para o mapeamento old_node ---> new_node ajustando a lista encadeada original. Simplesmente intercale os nós da lista antiga e da lista copiada. Por exemplo:\nLista Antiga: A --> B --> C --> D\nLista Intercalada: A --> A' --> B --> B' --> C --> C' --> D --> D'",
      "Dica 4: A intercalação é feita usando ponteiros next</b> e podemos fazer uso da estrutura intercalada para obter os nós de referência corretos para os ponteiros random</b>."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "139",
    "paidOnly": false,
    "title": "Word Break",
    "titleSlug": "word-break",
    "url": "https://leetcode.com/problems/word-break",
    "description_url": "https://leetcode.com/problems/word-break/description/",
    "description": "<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>\n\n<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;leetcode&quot;, wordDict = [&quot;leet&quot;,&quot;code&quot;]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Return true because &quot;leetcode&quot; can be segmented as &quot;leet code&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;applepenapple&quot;, wordDict = [&quot;apple&quot;,&quot;pen&quot;]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Return true because &quot;applepenapple&quot; can be segmented as &quot;apple pen apple&quot;.\nNote that you are allowed to reuse a dictionary word.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;catsandog&quot;, wordDict = [&quot;cats&quot;,&quot;dog&quot;,&quot;sand&quot;,&quot;and&quot;,&quot;cat&quot;]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= wordDict.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= wordDict[i].length &lt;= 20</code></li>\n\t<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>\n\t<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-break/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Breadth-First Search\n\n**Intuition**\n\nLet's imagine the indices of `s` as a graph. Each index can be thought of as a node, which represents building `s` up to the index.\n\nAdding a word to an existing string is like an edge between nodes. For a node `start`, we can move to node `end` if the substring of `s` between `start, end` exists in `wordDict`.\n\nFor example, let's say we have `s = \"leetcode\"` and `wordDict = [\"leet\", \"code\"]`. We are currently at node `4`, which implies that we have built `\"leet\"` (the first 4 characters of `s`). We can move to node `8`, because the substring of `s` with indices `[4, 8)` is `\"code\"`, which is in `wordDict`.\n\nWe start at node `0`, which represents the empty string. We want to reach node `s.length`, which implies that we have built the entire string. We can run a BFS to accomplish this traversal. If you're not familiar with BFS, check out the relevant [Explore Card](https://leetcode.com/explore/learn/card/graph/620/breadth-first-search-in-graph/).\n\nAt each node `start`, we iterate over all the nodes `end` that come after `start`. For each `end`, we check if the substring between `start, end` is in `wordDict`. If it is, we can add `end` to the queue.\n\nWe will first convert `wordDict` into a set so that we can perform the checks in constant time. We will also use a data structure `seen` to prevent us from visiting a node more than once.\n\n**Algorithm**\n\n1. Convert `wordDict` into a set `words`.\n2. Initialize a `queue` with `0` and a set `seen`.\n3. While the `queue` is not empty:\n    - Remove the first element, `start`.\n    - If `start == s.length`, return `true`.\n    - Iterate `end` from `start + 1` up to and including `s.length`. For each `end`, if `end` has not been visited yet,\n        - Check the substring starting at `start` and ending before `end`. If it is in `words`, add `end` to the queue and mark it in `seen`.\n4. Return `false` if the BFS finishes without reaching the final node.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/evkSf6sx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"evkSf6sx\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`, $$m$$ as the length of `wordDict`, and $$k$$ as the average length of the words in `wordDict`,\n\n* Time complexity: $$O(n^3 + m \\cdot k)$$\n\n    There are $$O(n)$$ nodes. Because of `seen`, we never visit a node more than once. At each node, we iterate over the nodes in front of the current node, of which there are $$O(n)$$. For each node `end`, we create a substring, which also costs $$O(n)$$.\n\n    Therefore, handling a node costs $$O(n^2)$$, so the BFS could cost up to $$O(n^3)$$. Finally, we also spent $$O(m \\cdot k)$$ to create the set `words`.\n\n* Space complexity: $$O(n + m \\cdot k)$$\n\n    We use $$O(n)$$ space for `queue` and `seen`. We use $$O(m \\cdot k)$$ space for the set `words`.\n    \n<br/>\n\n---\n\n### Approach 2: Top-Down Dynamic Programming \n\n**Intuition**\n\n> If you're not familiar with dynamic programming, we recommend checking out the [Dynamic Programming explore card](https://leetcode.com/explore/featured/card/dynamic-programming/). This problem is on the difficult side, so we will assume that readers are already familiar with the principles of DP.\n\nLet's have a function `dp` that returns a boolean indicating if it is possible to build `s` up to and including the index `i`.\n\nFor example, given `s = \"leetcode\"` and `wordDict = [\"leet\", \"code\"]`, `dp(3)` would return `true`. `s` up to index `3` is `\"leet\"`, and we can build `\"leet\"` using the words in `wordDict`. The answer to the problem would be `dp(s.length - 1)`, which represents if we can build `s`.\n\nThe base case of this function is when `i < 0`. This would represent an empty string, and we can always build an empty string by doing nothing. Therefore, `dp(i) = true` for `i < 0`.\n\nGiven an index `i`, we need a recurrence relation to determine if `dp(i)` is `true` or `false`. For `dp(i)` to be `true`, there are two requirements:\n\n1. First, there needs to be a `word` from `wordDict` that **ends** at index `i`. Given a `word`, the substring of `s` from indices `i - word.length + 1` up to and including `i` should match `word`. We can check every `word` for this.\n2. If we manage to find a `word` that **ends** at index `i`, we would need to add it on top of another string (since we are building `s` by joining words together one by one). We need to make sure that the string we are adding onto is also buildable. If we find a `word` that passes the first check, it means `word` would start at index `i - word.length + 1`. The index before that is `i - word.length`. To check if the string ending at that index is buildable, we can refer to `dp(i - word.length)`.\n\nThis gives us our recurrence relation:\n\n$$\\large{\\text{dp(i)} = \\text{any}(\\text{s}[\\text{i - word.length + 1, i}] == \\text{word \\&\\& dp(i - \\text{word.length})})}$$\n\nThat is, there exists any `word` that satisfies both of the listed conditions.\n\nWe can implement a recursive function `dp(i)` that implements the base cases and recurrence. We need to use memoization to avoid repeated computation.\n\n!?!../Documents/139.json:960,540!?!\n\n**Algorithm**\n\n1. Declare a data structure `memo` that stores the values of `dp` for each index.\n2. Create a function `dp(i)`:\n    - If `i < 0`, return `true`.\n    - If we already calculated `i`, return the value stored in `memo`.\n    - Iterate over `wordDict`. For each `word`:\n        - Check the substring of `s` ending at `i` with the same length as `word`. If the substring matches, and `dp(i - word.length)` is `true`, return `true`.\n    - If no `word` satisfying the criteria was found, return `false`.\n3. Return `dp(s.length - 1)`.\n\n**Implementation**\n\n> In Python, the <a href=\"https://docs.python.org/3/library/functools.html\" target=\"_blank\" rel=\"noopener noreferrer\">functools</a> module provides super handy tools that automatically memoize a function for us. We're going to use the `@cache` decorator in the Python implementation.\n>\n> In Java and C++, we will use an array `memo` to save values. `memo[i] = -1` if we haven't calculated yet, `memo[i] = 0` if `dp(i) = false`, and `memo[i] = 1` if `dp(i) = true`.\n\n<iframe src=\"https://leetcode.com/playground/4pvUY8Eg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4pvUY8Eg\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`, $$m$$ as the length of `wordDict`, and $$k$$ as the average length of the words in `wordDict`,\n\n* Time complexity: $$O(n \\cdot m \\cdot k)$$\n\n    There are $$n$$ states of `dp(i)`. Because of memoization, we only calculate each state once. To calculate a state, we iterate over $$m$$ words, and for each word perform some substring operations which costs $$O(k)$$. Therefore, calculating a state costs $$O(m \\cdot k)$$, and we need to calculate $$O(n)$$ states. \n\n* Space complexity: $$O(n)$$\n\n    The data structure we use for memoization and the recursion call stack can use up to $$O(n)$$ space.\n    \n<br/>\n\n---\n\n### Approach 3: Bottom-Up Dynamic Programming\n\n**Intuition**\n\nThe same algorithm can be implemented iteratively. Instead of using a function `dp(i)`, we will use an array `dp` where `dp[i]` represents the same thing that `dp(i)` did. We can use the same recurrence relation:\n\n$$\\large{\\text{dp[i]} = \\text{any}(\\text{s}[\\text{i - word.length + 1, i}] == \\text{word \\&\\& dp[i - \\text{word.length}]})}$$\n\nIn top-down, we started at the top (`s.length - 1`) and work our way down to the base cases. In bottom-up, we start at the bottom `(i = 0)` and work our way up to the top.\n\nBefore we check `dp[i - word.length]`, we should check if `i == word.length - 1`. This would mean that the current `word` we are placing to end at index `i` is the first word. `i - word.length` would be negative, so we need to separately check this case.\n\n**Algorithm**\n\n1. Initialize an array `dp` with the same length as `s` and all values initially set to `false`.\n2. Iterate `i` over the indices of `s`. At each `i`:\n    - Iterate over each `word` in `wordDict`:\n        - Check if `i == word.length - 1` or `dp[i - word.length] = true`.\n        - If so, and the substring of `s` ending at `i` with the same length as `word` matches, set `dp[i] = true` and `break`.\n3. Return `dp[s.length - 1]`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/EWiwhkJC/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"EWiwhkJC\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`, $$m$$ as the length of `wordDict`, and $$k$$ as the average length of the words in `wordDict`,\n\n* Time complexity: $$O(n \\cdot m \\cdot k)$$\n\n    The logic behind the time complexity is identical to the previous approach. It costs us $$O(m \\cdot k)$$ to calculate each state, and we calculate $$O(n)$$ states in total. \n\n* Space complexity: $$O(n)$$\n\n    We use an array `dp` of length $$n$$.\n    \n<br/>\n\n---\n\n### Approach 4: Trie Optimization \n\n**Intuition**\n\nIn the previous approach, we iterated over each state `i` and then calculated `dp[i]`. To calculate a given `dp[i]`, we did the following:\n\n- Iterate over every `word` in `wordDict`\n- Check if each `word` ended at the current index\n\nThis cost us $$O(m \\cdot k)$$. In the problem constraints, we can see that the maximum value of $$m \\cdot k$$ is `20,000`, so this is expensive. We can optimize the time it takes to calculate a given `dp[i]` by using a trie.\n\nA trie is a data structure that can be used to efficiently search for strings. If you are not familiar with tries, we highly recommend you read the official solution to [this problem](https://leetcode.com/problems/implement-trie-prefix-tree/solution) before proceeding with this approach.\n\nTo summarize, a trie is a tree where each node is labeled. Here, we label each node with a character. The path from the root to any node represents the string that is built by the nodes on the path. The root represents the empty string.\n\n<img src=\"../Figures/139/4.png\" width=\"960\"> <br>\n\nWe can start by building a trie from the words in `wordDict`. Each trie node will have an additional attribute `isWord` which indicates if the current node represents a word from `wordDict`. Then, we will calculate the same `dp` array as in the previous approach. We will calculate each state as follows:\n\n- First, check if `i == 0` (placing first word) or `dp[i - 1]` (we could build the string up to this point). If neither are true, move on to the next state `i + 1`.\n- Otherwise, we see if `dp[i]` can be `true`. Initialize a node `curr` at the `root` of the trie.\n- Start iterating with a variable `j` from index `i`. For each character `s[j]`, check if we can traverse the trie.\n- If we can't traverse the trie, it means no words exist starting at index `i` and ending at index `j` or beyond. We can break from the loop and move on to the next state `i + 1`.\n- If we can traverse the trie, we move to the child node. We check the child's `isWord` attribute. If it is `true`, it means there is a word in `wordDict` starting at index `i` and ending at index `j`. We set `dp[j] = true`.\n- We continue traversing the trie until we reach a dead end or `j` reaches the end of the string.\n\nThis allows us to handle each state in $$O(n)$$ instead of $$O(m \\cdot k)$$, which is a big improvement since $$n \\leq 300$$.\n\n**Algorithm**\n\n1. Build a trie from `wordDict`. Each node should also have an `isWord` attribute. Store the root of the trie in `root`.\n2. Initialize an array `dp` with the same length as `s` and all values initially set to `false`.\n3. Iterate `i` over the indices of `s`. At each `i`:\n    - Check if `i == 0` or `dp[i - 1] = true`. If not, continue to the next `i`.\n    - Set `curr = root`. Iterate `j` over the indices of `s`, starting from `i`. At each `j`,\n        - Get the character at index `j` as `c = s[j]`.\n        - If `c` is not in the children of `curr`, we can `break` from the loop.\n        - Otherwise, move `curr` to the child labeled `c`.\n        - If `curr.isWord`, set `dp[j] = true`.\n4. Return `dp[s.length - 1]`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/FhHxmwHE/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"FhHxmwHE\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`, $$m$$ as the length of `wordDict`, and $$k$$ as the average length of the words in `wordDict`,\n\n* Time complexity: $$O(n^2 + m \\cdot k)$$\n\n    Building the trie involves iterating over all characters of all words. This costs $$O(m \\cdot k)$$.\n\n    Once we build the trie, we calculate `dp`. For each `i`, we iterate over all the indices after `i`. We have a basic nested for loop which costs $$O(n^2)$$ to handle all `dp[i]`.\n\n* Space complexity: $$O(n + m \\cdot k)$$\n\n    The `dp` array takes $$O(n)$$ space. The trie can have up to $$m \\cdot k$$ nodes in it.\n    \n<br/>\n\n---\n\n### Approach 5: A Different DP\n\n**Intuition**\n\n> In this approach, we will take a look at another way to implement the DP algorithm. Note that this approach is the one covered in the video.\n\nHere, we let `dp[i]` hold the answer to the question: \"is it possible to form `s` up to a length of `i`? To find the answer for each index, instead of iterating over the words in `wordDict` and checking if a `word` ends at the current index `i`, we will instead iterate over **all substrings that end before index `i`**. If we find one of these substrings is in `wordDict` **and** we can form the string prior to the substring, then `dp[i] = true`.\n\nThe reason we are checking for **before** index `i` is because we have slightly changed our `dp` definition here. In the previous problem, `i` represented the index of the last character. Here, `i` represents the length, so we are offset by one.\n\nBefore starting the DP, we first convert `wordsDict` to a set so that we can perform the checks in $O(1)$. The rest of the algorithm follows similarly to the previous approaches.\n\n**Algorithm**\n\n1. Convert `wordsDict` to a set `words`.\n2. Initialize an array `dp` of length `n + 1` with all values set to `false`.\n3. Iterate `i` from `1` until and including `n`. Here, `i` represents the length of the string starting from the beginning.\n    - Iterate `j` from `0` until `i`. Here, `j` represents the first index of the substring we are checking.\n    - If `dp[j]` is true AND the substring `s[j:i]` is in `words`, set `dp[i] = true` and break. Note that `s[j:i]` represents the substring starting at `j` and ending at `i - 1`.\n4. Return `dp[n]`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/eiTDAMA4/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"eiTDAMA4\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the length of `s`, $$m$$ as the length of `wordDict`, and $$k$$ as the average length of the words in `wordDict`,\n\n* Time complexity: $$O(n^3 + m \\cdot k)$$\n\n    First, we spend $$O(m \\cdot k)$$ to convert `wordDict` into a set. Then we have a nested loop over `n`, which iterates $$O(n^2)$$ times. For each iteration, we have a substring operation which could cost up to $$O(n)$$. Thus this nested loop costs $$O(n^3)$$.\n\n* Space complexity: $$O(n + m \\cdot k)$$\n\n    The `dp` array takes $$O(n)$$ space. The set `words` takes up $$O(m \\cdot k)$$ space.\n    \n<br/>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n    wordSet = set(wordDict)\n\n    @functools.lru_cache(None)\n    def wordBreak(s: str) -> bool:\n      if s in wordSet:\n        return True\n      return any(s[:i] in wordSet and wordBreak(s[i:]) for i in range(len(s)))\n\n    return wordBreak(s)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean wordBreak(String s, List<String> wordDict) {\n    return wordBreak(s, new HashSet<>(wordDict), new HashMap<>());\n  }\n\n  private boolean wordBreak(final String s, Set<String> wordSet, Map<String, Boolean> memo) {\n    if (memo.containsKey(s))\n      return memo.get(s);\n    if (wordSet.contains(s)) {\n      memo.put(s, true);\n      return true;\n    }\n\n    // 1 <= prefix.length() < s.length()\n    for (int i = 1; i < s.length(); ++i) {\n      final String prefix = s.substring(0, i);\n      final String suffix = s.substring(i);\n      if (wordSet.contains(prefix) && wordBreak(suffix, wordSet, memo)) {\n        memo.put(s, true);\n        return true;\n      }\n    }\n\n    memo.put(s, false);\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool wordBreak(string s, vector<string>& wordDict) {\n    return wordBreak(s, {begin(wordDict), end(wordDict)}, {});\n  }\n\n private:\n  bool wordBreak(const string& s, const unordered_set<string>&& wordSet,\n                 unordered_map<string, bool>&& memo) {\n    if (wordSet.count(s))\n      return true;\n    if (memo.count(s))\n      return memo[s];\n\n    // 1 <= prefix.length() < s.length()\n    for (int i = 1; i < s.length(); ++i) {\n      const string& prefix = s.substr(0, i);\n      const string& suffix = s.substr(i);\n      if (wordSet.count(prefix) && wordBreak(suffix, move(wordSet), move(memo)))\n        return memo[s] = true;\n    }\n\n    return memo[s] = false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/139.html",
    "category": "Algorithms",
    "acceptance_rate": 48.1456946137698,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Dynamic Programming",
      "Trie",
      "Memoization"
    ],
    "hints": [],
    "likes": 17917,
    "dislikes": 855,
    "similar_questions": "[{\"title\": \"Word Break II\", \"titleSlug\": \"word-break-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Extra Characters in a String\", \"titleSlug\": \"extra-characters-in-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2039309, \"totalSubmissionRaw\": 4235720, \"acRate\": \"48.1%\"}",
    "title_pt": "Quebra de Palavra",
    "description_pt": "<p>Dada uma string <code>s</code> e um dicionário de strings <code>wordDict</code>, retorne <code>true</code> se <code>s</code> puder ser segmentada em uma sequência separada por espaços de uma ou mais palavras do dicionário.</p>\n\n<p><strong>Nota</strong> que a mesma palavra no dicionário pode ser reutilizada múltiplas vezes na segmentação.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;leetcode&quot;, wordDict = [&quot;leet&quot;,&quot;code&quot;]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Retorne true porque &quot;leetcode&quot; pode ser segmentada como &quot;leet code&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;applepenapple&quot;, wordDict = [&quot;apple&quot;,&quot;pen&quot;]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Retorne true porque &quot;applepenapple&quot; pode ser segmentada como &quot;apple pen apple&quot;.\nObserve que você tem permissão para reutilizar uma palavra do dicionário.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;catsandog&quot;, wordDict = [&quot;cats&quot;,&quot;dog&quot;,&quot;sand&quot;,&quot;and&quot;,&quot;cat&quot;]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= wordDict.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= wordDict[i].length &lt;= 20</code></li>\n\t<li><code>s</code> e <code>wordDict[i]</code> consistem apenas de letras minúsculas do inglês.</li>\n\t<li>Todas as strings de <code>wordDict</code> são <strong>únicas</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "140",
    "paidOnly": false,
    "title": "Word Break II",
    "titleSlug": "word-break-ii",
    "url": "https://leetcode.com/problems/word-break-ii",
    "description_url": "https://leetcode.com/problems/word-break-ii/description/",
    "description": "<p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, add spaces in <code>s</code> to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in <strong>any order</strong>.</p>\n\n<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;catsanddog&quot;, wordDict = [&quot;cat&quot;,&quot;cats&quot;,&quot;and&quot;,&quot;sand&quot;,&quot;dog&quot;]\n<strong>Output:</strong> [&quot;cats and dog&quot;,&quot;cat sand dog&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;pineapplepenapple&quot;, wordDict = [&quot;apple&quot;,&quot;pen&quot;,&quot;applepen&quot;,&quot;pine&quot;,&quot;pineapple&quot;]\n<strong>Output:</strong> [&quot;pine apple pen apple&quot;,&quot;pineapple pen apple&quot;,&quot;pine applepen apple&quot;]\n<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;catsandog&quot;, wordDict = [&quot;cats&quot;,&quot;dog&quot;,&quot;sand&quot;,&quot;and&quot;,&quot;cat&quot;]\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>1 &lt;= wordDict.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= wordDict[i].length &lt;= 10</code></li>\n\t<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>\n\t<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>\n\t<li>Input is generated in a way that the length of the answer doesn&#39;t exceed&nbsp;10<sup>5</sup>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-break-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe have a string `s` and a dictionary of strings `wordDict`. The task is to add spaces in `s` to construct valid sentences where each word is present in `wordDict` and return all possible valid sentences. The same word from the dictionary can be reused multiple times.\n\nThis problem is an extension of [Problem 139. Word Break I](https://leetcode.com/problems/word-break/description/), where the goal was to determine if a word could be segmented into other words from a given dictionary. In this problem, however, we need to find all possible ways to split the word into valid statements. To understand this problem, it is beneficial to be familiar with [Problem 139. Word Break I](https://leetcode.com/problems/word-break/description/) as well as [Problem 208. Implement Trie Prefix Tree](https://leetcode.com/problems/implement-trie-prefix-tree/), as those questions provide the foundational concepts and intuition necessary for solving this problem.\n\nHere, we will focus on the applications of recursion, dynamic programming, and tries, rather than on understanding their underlying mechanisms.\n\nTo gain an understanding of their underlying mechanisms, we suggest you check out these explore cards: \n1. [Backtracking Explore Card](https://leetcode.com/explore/learn/card/recursion-ii/472/backtracking/).\n2. [Dynamic Programming Explore Card](https://leetcode.com/explore/learn/card/dynamic-programming/).\n3. [Trie Explore Card](https://leetcode.com/explore/learn/card/trie/).\n\n---\n\n### Approach 1: Backtracking\n\n#### Intuition\n\nInitially, we might think of a brute-force approach where we systematically explore all possible ways to break the string into words from the dictionary. This leads us to the backtracking strategy, where we recursively try to form words from the string and add them to a current sentence if they are in the dictionary. If the current prefix doesn't lead to a valid solution, we backtrack by removing the last added word and trying the next possible word. This ensures we explore all possible segmentations of the string.\n\nAt each step, we consider all possible end indices for substrings starting from the current index. For each substring, we check if it exists in the dictionary. If the substring is a valid word, we append it to the current sentence and recursively call the function with the updated index, which is the end index of the substring plus one.\n\nIf we reach the end of the string, it means we have found a valid segmentation, and we can add the current sentence to the results. However, if we encounter a substring that is not a valid word, we backtrack by returning from that recursive call and trying the next possible end index.\n\nThe backtracking approach will be inefficient due to the large number of recursive calls, especially for longer strings. To increase efficiency, we will convert the word dictionary into a set for constant-time lookups. However, the overall time complexity remains high because we explore all possible partitions.\n\nThe process is visualized below:\n\n![backtrack](../Figures/140/backtrack.png)\n\n#### Algorithm\n\n**`wordBreak` Function:**\n- Convert the `wordDict` array into an unordered set `wordSet` for efficient lookups.\n- Initialize an empty array `results` to store valid sentences.\n- Initialize an empty string `currentSentence` to keep track of the sentence being constructed.\n- Call the `backtrack` function with the input string `s`, `wordSet`, `currentSentence`, `results`, and a starting index set to 0, the beginning of the input string.\n- Return `results`.\n\n**`backtrack` Function:**\n- Base Case: If the `startIndex` is equal to the length of the string, add the `currentSentence` to `results` and return as it means that `currentSentence` represents a valid sentence.\n- Iterate over possible `endIndex` values from `startIndex + 1` to the end of the string.\n    - Extract the substring `word` from `startIndex` to `endIndex - 1`.\n    - If `word` is found in `wordSet`:\n        - Store the current `currentSentence` in `originalSentence`.\n        - Append `word` to `currentSentence` (with a space if needed).\n        - Recursively call `backtrack` with the updated `currentSentence` and `endIndex`.\n        - Reset `currentSentence` to its original value (`originalSentence`) to backtrack and try the next `endIndex`.\n- Return from the `backtrack` function.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/izdRa3p9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"izdRa3p9\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.  \n\n- Time complexity: $O(n \\cdot 2^n)$\n\n    The algorithm explores all possible ways to break the string into words. In the worst case, where each character can be treated as a word, the recursion tree has $2^n$ leaf nodes, resulting in an exponential time complexity. For each leaf node, $O(n)$ work is performed, so the overall complexity is $O(n \\cdot 2^n)$.\n\n- Space complexity: $O(2^n)$\n\n    The recursion stack can grow up to a depth of $n$, where each recursive call consumes additional space for storing the current state. \n    \n    Since each position in the string can be a split point or not, and for $n$ positions, there are $2^n$ possible combinations of splits. Thus, in the worst case, each combination generates a different sentence that needs to be stored, leading to exponential space complexity.\n\n---\n\n### Approach 2: Dynamic Programming - Memoization\n\n#### Intuition\n\nWe can improve the efficiency of the backtracking method by using Memoization, which stores the results of subproblems to avoid recalculating them.\n\nWe use a depth-first search (DFS) function that recursively breaks the string into words. However, before performing a recursive call, we check if the results for the current substring have already been computed and stored in a memoization map (typically a dictionary or hash table).\n\nIf the results of the current substring are found in the memoization map, we can directly return them without further computation. If not, we proceed with the recursive call, computing the results and storing them in the memoization map before returning them.\n\nBy memoizing the results, we can reduce the number of computations by ensuring that each substring is processed only once in average cases. \n\n#### Algorithm\n \n**`wordBreak` Function:**\n- Convert the `wordDict` array into an unordered set `wordSet` for efficient lookups.\n- Initialize an empty unordered map `memoization` to store the results of subproblems.\n- Call the `dfs` function with the input string `s`, `wordSet`, and `memoization`.\n\n**`dfs` Function:**\n- Check if the answer for the current `remainingStr`(the remaining part of the string to be processed) are already in `memoization`. If so, return them.\n- Base Case: If `remainingStr` is empty, it means that all characters have been processed. An empty string represents a valid sentence so return an array containing the empty string.\n- Initialize an empty array `results`.\n- Iterate from 1 to the length of `remainingStr`:\n    - Extract the substring `currentWord` from 0 to `i` to check if it is a valid word.\n    - If `currentWord` is found in `wordSet`:\n        - Recursively call `dfs` with `remainingStr.substr(i)`, `wordSet`, and `memoization`.\n        - Append `currentWord` and the recursive results to `results`(with a space if needed) to form valid sentences.\n- Store the `results` for `remainingStr` in `memoization`.\n- Return `results`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Ri3aMwXd/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Ri3aMwXd\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.  \n\n* Time complexity: $O(n \\cdot 2^n)$\n\n    While memoization avoids redundant computations, it does not change the overall number of subproblems that need to be solved. In the worst case, there are still unique $2^n$ possible substrings that need to be explored, leading to an exponential time complexity. For each subproblem, $O(n)$ work is performed, so the overall complexity is $O(n \\cdot 2^n)$.\n\n* Space complexity: $O(n \\cdot 2^n)$\n\n    The recursion stack can grow up to a depth of $n$, where each recursive call consumes additional space for storing the current state. \n\n    The memoization map needs to store the results for all possible substrings, which can be up to $2^n$ substrings of size $n$ in the worst case, resulting in an exponential space complexity.\n\n---\n\n### Approach 3: Dynamic Programming - Tabulation\n\n#### Intuition\n\nWhile memoization improves the backtracking approach, we might consider an alternative approach using dynamic programming principles. This leads us to the tabulation method, which builds a table (or map) of valid sentences for each starting index in the string. \n\nThe tabulation approach is often more efficient than backtracking and memoization in terms of time and space complexity because it avoids the overhead of recursive calls and stack usage. It also eliminates the need for a separate memoization map, as the table itself serves as the storage for the subproblem solutions.\n\nThe tabulation approach works in a bottom-up manner, iterating from the end of the string towards the beginning. At each step, we construct all possible sentences that can be formed starting from the current index by checking if substrings form valid words in the dictionary.\n\nIf a valid word is found, we combine it with the valid sentences formed from the remaining substring. This process continues until we reach the beginning of the string, building up the table of valid sentences for each starting index.\n\nThe key idea behind tabulation is that we ensure all subproblems are solved before they are needed, enabling the construction of complete solutions in an organized manner. By iterating from the end to the beginning of the string, we guarantee that the necessary subproblems have already been solved when we need them.\n\n#### Algorithm\n \n- Initialize an empty unordered map `dp` to store the results of subproblems.\n- Iterate from the end of the string to the beginning (`startIdx` from `s.size()` to 0):\n    - Initialize an empty array `validSentences` to store all valid sentences starting from that index. \n    - Iterate from `startIdx` to the end of the string (`endIdx`):\n        - Extract the substring `currentWord` from `startIdx` to `endIdx`.\n        - If `currentWord` is a valid word in `wordDict`:\n            - If `endIdx` is the last index, add `currentWord` to `validSentences`.\n            - Else, append `currentWord` to each sentence formed by the remaining substring (`sentencesFromNextIndex`) from `dp[endIdx + 1]`.\n    - Store `validSentences` in `dp[startIdx]`.\n- Return `dp[0]` (valid sentences formed from the entire string).\n\nThe algorithm is visualized below:\n\n!?!../Documents/140/tabulation.json:976,631!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/gWJckozB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gWJckozB\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.  \n\n* Time complexity: $O(n \\cdot 2^n)$\n\n    Similar to memoization, the tabulation approach still needs to explore all possible substrings, which can be up to $2^n$ in the worst case, leading to an exponential time complexity. $O(n)$ work is performed to explore each substring, so the overall complexity is $O(n \\cdot 2^n)$.\n\n* Space complexity: $O(n \\cdot 2^n)$\n\n    The dynamic programming table or map needs to store the valid sentences for all possible starting indices, which can be up to $2^n$ strings of size $n$ in the worst case, resulting in an exponential space complexity.\n\n---\n\n### Approach 4: Trie Optimization\n\n#### Intuition\n\nWhile the previous approaches focus on optimizing the search and computation process, we can also consider leveraging efficient data structures to enhance the word lookup process. This leads us to the trie-based approach, which uses a trie data structure to store the word dictionary, allowing efficient word lookup and prefix matching.\n\n> The trie, also known as a prefix tree, is a tree-based data structure where each node represents a character in a word, and the path from the root to a leaf node represents a complete word. This structure is particularly useful for problems involving word segmentation because it allows for efficient prefix matching.\n\nHere, we first build a trie from the dictionary words. Each word is represented as a path in the trie, where each node corresponds to a character in the word.\n\nBy using the trie, we can quickly determine whether a substring can form a valid word without having to perform linear searches or set lookups. This reduces the search space and improves the efficiency of the algorithm.\n\nIn this approach, instead of recursively exploring the remaining substring and using memoization, we iterate from the end of the input string to the beginning (in reverse order). For each starting index (`startIdx`), we attempt to find valid sentences that can be formed from that index by iterating through the string and checking if the current substring forms a valid word using the trie data structure.\nWhen a valid word is encountered in the trie, we append it to the list of valid sentences for the current starting index. If the current valid word is not the last word in the sentence, we combine it with the valid sentences formed from the next index (`endIdx + 1`), which are retrieved from the `dp` dictionary.\n\nThe valid sentences for each starting index are stored in the `dp` dictionary, ensuring that previously computed results are reused. By using tabulation and storing the valid sentences for each starting index, we avoid redundant computations and achieve significant time and space efficiency improvements compared to the standard backtracking method with memoization.\n\nThe trie-based approach offers advantages in terms of efficient word lookup and prefix matching, making it particularly suitable for problems involving word segmentation or string manipulation. However, it comes with the additional overhead of constructing and maintaining the trie data structure, which can be more memory-intensive for large dictionaries.\n\n#### Algorithm\n \n**Initialize TrieNode Structure**\n- Each TrieNode has two properties:\n - `isEnd`: A boolean value indicating if the node marks the end of a word.\n - `children`: An array of size 26 (for lowercase English letters) to store pointers to child nodes.\n- The constructor initializes `isEnd` to `false` and all elements in `children` to `null`.\n\n**Trie Class**\n- The Trie class has a `root` pointer of type `TrieNode`.\n- The constructor initializes the `root` with a new `TrieNode` object.\n- The `insert` function:\n - Takes a string `word` as input.\n - Starts from the `root` node.\n - For each character `c` in the `word`:\n   - Calculate the index corresponding to the character.\n   - If the child node at the calculated index doesn't exist, create a new `TrieNode` and assign it to that index.\n   - Move to the child node.\n - After processing all characters, mark the current node's `isEnd` as `true`.\n\n**wordBreak Function**\n- Create a `Trie` object.\n- Insert all words from `wordDict` into the trie using the `insert` function.\n- Initialize a map `dp` to store the results of subproblems.\n- Iterate from the end of the string `s` to the beginning (in reverse order).\n - For each starting index `startIdx`:\n   - Initialize a vector `validSentences` to store valid sentences starting from `startIdx`.\n   - Initialize a `current_node` pointer to the `root` of the trie.\n   - Iterate from `startIdx` to the end of the string.\n     - For each character `c` in the string:\n       - Calculate the index corresponding to `c`.\n       - Check if the child node at the calculated index exists in the trie.\n        - If the child node doesn't exist, break out of the inner loop. This means that the current substring cannot form a valid word, so there is no need to continue checking the remaining characters.\n       - Move to the child node.\n     - Check if the current node's `isEnd` is `true`, indicating a valid word.\n     - If a valid word is found:\n       - Extract the current word from the string using `substr`.\n       - If it's the last word in the sentence (`endIdx` is the last index):\n         - Add the current word to `validSentences`.\n       - If it's not the last word:\n         - Retrieve the valid sentences formed by the remaining substring from `dp[endIdx + 1]`.\n         - Combine the current word with each sentence and add it to `validSentences`.\n   - Store the `validSentences` for the current `startIdx` in `dp`.\n- Return the valid sentences stored in `dp[0]`, which represents the valid sentences formed from the entire string.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/YBoyT88T/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"YBoyT88T\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string. \n\n* Time complexity: $O(n \\cdot 2^n)$\n\n    Even though the trie-based approach uses an efficient data structure for word lookup, it still needs to explore all possible ways to break the string into words. In the worst case, there are $2^n$ unique possible partitions, leading to an exponential time complexity. $O(n)$ work is performed for each partition, so the overall complexity is $O(n \\cdot 2^n)$.\n\n* Space complexity: $O(n \\cdot 2^n)$\n\n    The trie data structure itself can have a maximum of $2^n$ nodes in the worst case, where each character in the string represents a separate word. Additionally, the tabulation map used in this approach can also store up to $2^n$ strings of size $n$, resulting in an overall exponential space complexity.\n\n---\n\n**Further Thoughts On Complexity Analysis:**\n\nThe complexity of this problem cannot be reduced from $n \\cdot 2^n$; the worst-case scenario will still be $(n \\cdot 2^n)$. However, using dynamic programming (DP) will make it a bit more efficient than backtracking overall because of the below test case.\n\nConsider the input `\"aaaaaa\"`, with `wordDict = [\"a\", \"aa\", \"aaa\", \"aaaa\", \"aaaaa\", \"aaaaa\"]`. \nEvery possible partition is a valid sentence, and there are $2^{n-1}$ such partitions. The algorithms cannot perform better than this since they must generate all valid sentences. The cost of iterating over cached results will be exponential, as every possible partition will be cached, resulting in the same runtime as regular backtracking. Likewise, the space complexity will also be $O(n \\cdot 2^n)$ for the same reason—every partition is stored in memory.\n\nAnother way to explain why the worst-case complexity is $O(n \\cdot 2^n)$ for all the algorithms is that, given an array of length $n$, there are $n+1$ ways/intervals to partition it into two parts. Each interval has two choices: to split or not to split. In the worst case, we will have to check all possibilities, which results in a time complexity of $O(n \\cdot 2^{n+1})$, which simplifies to $O(n \\cdot 2^n)$. This analysis is extremely similar to palindrome partitioning.\n\nOverall, this question is interesting because of the nature of this complexity. In an interview setting, if an interviewer asks this question, the most expected solutions would be Backtracking and Trie, as they become natural choices for the conditions and outputs we need.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n    wordSet = set(wordDict)\n\n    @functools.lru_cache(None)\n    def wordBreak(s: str) -> List[str]:\n      ans = []\n\n      # 1 <= len(prefix) < len(s)\n      for i in range(1, len(s)):\n        prefix = s[0:i]\n        suffix = s[i:]\n        if prefix in wordSet:\n          for word in wordBreak(suffix):\n            ans.append(prefix + ' ' + word)\n\n      # Contains whole string, so don't add any space\n      if s in wordSet:\n        ans.append(s)\n\n      return ans\n\n    return wordBreak(s)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> wordBreak(String s, List<String> wordDict) {\n    Set<String> wordSet = new HashSet<>(wordDict);\n    Map<String, List<String>> memo = new HashMap<>();\n    return wordBreak(s, wordSet, memo);\n  }\n\n  private List<String> wordBreak(final String s, Set<String> wordSet,\n                                 Map<String, List<String>> memo) {\n    if (memo.containsKey(s))\n      return memo.get(s);\n\n    List<String> ans = new ArrayList<>();\n\n    // 1 <= prefix.length() < s.length()\n    for (int i = 1; i < s.length(); ++i) {\n      final String prefix = s.substring(0, i);\n      final String suffix = s.substring(i);\n      if (wordSet.contains(prefix))\n        for (final String word : wordBreak(suffix, wordSet, memo))\n          ans.add(prefix + \" \" + word);\n    }\n\n    // Contains whole string, so don't add any space\n    if (wordSet.contains(s))\n      ans.add(s);\n\n    memo.put(s, ans);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> wordBreak(string s, vector<string>& wordDict) {\n    unordered_set<string> wordSet{begin(wordDict), end(wordDict)};\n    unordered_map<string, vector<string>> memo;\n    return wordBreak(s, wordSet, memo);\n  }\n\n private:\n  vector<string> wordBreak(const string& s,\n                           const unordered_set<string>& wordSet,\n                           unordered_map<string, vector<string>>& memo) {\n    if (memo.count(s))\n      return memo[s];\n\n    vector<string> ans;\n\n    // 1 <= prefix.length() < s.length()\n    for (int i = 1; i < s.length(); ++i) {\n      const string& prefix = s.substr(0, i);\n      const string& suffix = s.substr(i);\n      if (wordSet.count(prefix))\n        for (const string& word : wordBreak(suffix, wordSet, memo))\n          ans.push_back(prefix + \" \" + word);\n    }\n\n    // Contains whole string, so don't add any space\n    if (wordSet.count(s))\n      ans.push_back(s);\n\n    return memo[s] = ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/140.html",
    "category": "Algorithms",
    "acceptance_rate": 53.42040486028166,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Dynamic Programming",
      "Backtracking",
      "Trie",
      "Memoization"
    ],
    "hints": [],
    "likes": 7376,
    "dislikes": 541,
    "similar_questions": "[{\"title\": \"Word Break\", \"titleSlug\": \"word-break\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Concatenated Words\", \"titleSlug\": \"concatenated-words\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"742K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 741993, \"totalSubmissionRaw\": 1388971, \"acRate\": \"53.4%\"}",
    "title_pt": "Quebra de Palavras II",
    "description_pt": "<p>Dada uma string <code>s</code> e um dicionário de strings <code>wordDict</code>, adicione espaços em <code>s</code> para construir uma sentença em que cada palavra seja uma palavra válida do dicionário. Retorne todas essas sentenças possíveis em <strong>qualquer ordem</strong>.</p>\n\n<p><strong>Nota</strong> que a mesma palavra no dicionário pode ser reutilizada várias vezes na segmentação.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;catsanddog&quot;, wordDict = [&quot;cat&quot;,&quot;cats&quot;,&quot;and&quot;,&quot;sand&quot;,&quot;dog&quot;]\n<strong>Saída:</strong> [&quot;cats and dog&quot;,&quot;cat sand dog&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;pineapplepenapple&quot;, wordDict = [&quot;apple&quot;,&quot;pen&quot;,&quot;applepen&quot;,&quot;pine&quot;,&quot;pineapple&quot;]\n<strong>Saída:</strong> [&quot;pine apple pen apple&quot;,&quot;pineapple pen apple&quot;,&quot;pine applepen apple&quot;]\n<strong>Explicação:</strong> Observe que você tem permissão para reutilizar uma palavra do dicionário.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;catsandog&quot;, wordDict = [&quot;cats&quot;,&quot;dog&quot;,&quot;sand&quot;,&quot;and&quot;,&quot;cat&quot;]\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 20</code></li>\n\t<li><code>1 &lt;= wordDict.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= wordDict[i].length &lt;= 10</code></li>\n\t<li><code>s</code> e <code>wordDict[i]</code> consistem apenas de letras minúsculas do alfabeto inglês.</li>\n\t<li>Todas as strings de <code>wordDict</code> são <strong>únicas</strong>.</li>\n\t<li>A entrada é gerada de forma que o comprimento da resposta não excede&nbsp;10<sup>5</sup>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "141",
    "paidOnly": false,
    "title": "Linked List Cycle",
    "titleSlug": "linked-list-cycle",
    "url": "https://leetcode.com/problems/linked-list-cycle",
    "description_url": "https://leetcode.com/problems/linked-list-cycle/description/",
    "description": "<p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>\n\n<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the&nbsp;<code>next</code>&nbsp;pointer. Internally, <code>pos</code>&nbsp;is used to denote the index of the node that&nbsp;tail&#39;s&nbsp;<code>next</code>&nbsp;pointer is connected to.&nbsp;<strong>Note that&nbsp;<code>pos</code>&nbsp;is not passed as a parameter</strong>.</p>\n\n<p>Return&nbsp;<code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png\" style=\"width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;\" />\n<pre>\n<strong>Input:</strong> head = [3,2,0,-4], pos = 1\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png\" style=\"width: 141px; height: 74px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2], pos = 0\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png\" style=\"width: 45px; height: 45px;\" />\n<pre>\n<strong>Input:</strong> head = [1], pos = -1\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no cycle in the linked list.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>\n",
    "solution_url": "https://leetcode.com/problems/linked-list-cycle/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def hasCycle(self, head: ListNode) -> bool:\n    slow = head\n    fast = head\n\n    while fast and fast.next:\n      slow = slow.next\n      fast = fast.next.next\n      if slow == fast:\n        return True\n\n    return False",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  public boolean hasCycle(ListNode head) {\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (fast != null && fast.next != null) {\n      slow = slow.next;\n      fast = fast.next.next;\n      if (slow == fast)\n        return true;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool hasCycle(ListNode* head) {\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (fast && fast->next) {\n      slow = slow->next;\n      fast = fast->next->next;\n      if (slow == fast)\n        return true;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/141.html",
    "category": "Algorithms",
    "acceptance_rate": 52.37443034338778,
    "topics": [
      "Hash Table",
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 16423,
    "dislikes": 1498,
    "similar_questions": "[{\"title\": \"Linked List Cycle II\", \"titleSlug\": \"linked-list-cycle-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Happy Number\", \"titleSlug\": \"happy-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.9M\", \"totalSubmission\": \"7.4M\", \"totalAcceptedRaw\": 3887459, \"totalSubmissionRaw\": 7422440, \"acRate\": \"52.4%\"}",
    "title_pt": "Ciclo em Lista Encadeada",
    "description_pt": "<p>Dado <code>head</code>, a cabeça de uma lista encadeada, determine se a lista encadeada possui um ciclo.</p>\n\n<p>Há um ciclo em uma lista encadeada se existir algum nó na lista que possa ser alcançado novamente seguindo continuamente o ponteiro <code>next</code>. Internamente, <code>pos</code> é usado para denotar o índice do nó ao qual o ponteiro <code>next</code> de <code>tail</code> está conectado. <strong>Observe que <code>pos</code> não é passado como parâmetro</strong>.</p>\n\n<p>Retorne <code>true</code><em> se houver um ciclo na lista encadeada</em>. Caso contrário, retorne <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png\" style=\"width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;\" />\n<pre>\n<strong>Entrada:</strong> head = [3,2,0,-4], pos = 1\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Há um ciclo na lista encadeada, onde a cauda se conecta ao 1º nó (indexado em 0).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png\" style=\"width: 141px; height: 74px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2], pos = 0\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Há um ciclo na lista encadeada, onde a cauda se conecta ao 0º nó.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png\" style=\"width: 45px; height: 45px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1], pos = -1\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Não há ciclo na lista encadeada.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pos</code> é <code>-1</code> ou um <strong>índice válido</strong> na lista encadeada.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue resolvê-lo usando memória <code>O(1)</code> (ou seja, constante)?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "142",
    "paidOnly": false,
    "title": "Linked List Cycle II",
    "titleSlug": "linked-list-cycle-ii",
    "url": "https://leetcode.com/problems/linked-list-cycle-ii",
    "description_url": "https://leetcode.com/problems/linked-list-cycle-ii/description/",
    "description": "<p>Given the <code>head</code> of a linked list, return <em>the node where the cycle begins. If there is no cycle, return </em><code>null</code>.</p>\n\n<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail&#39;s <code>next</code> pointer is connected to (<strong>0-indexed</strong>). It is <code>-1</code> if there is no cycle. <strong>Note that</strong> <code>pos</code> <strong>is not passed as a parameter</strong>.</p>\n\n<p><strong>Do not modify</strong> the linked list.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png\" style=\"height: 145px; width: 450px;\" />\n<pre>\n<strong>Input:</strong> head = [3,2,0,-4], pos = 1\n<strong>Output:</strong> tail connects to node index 1\n<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the second node.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png\" style=\"height: 105px; width: 201px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2], pos = 0\n<strong>Output:</strong> tail connects to node index 0\n<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the first node.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png\" style=\"height: 65px; width: 65px;\" />\n<pre>\n<strong>Input:</strong> head = [1], pos = -1\n<strong>Output:</strong> no cycle\n<strong>Explanation:</strong> There is no cycle in the linked list.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>\n",
    "solution_url": "https://leetcode.com/problems/linked-list-cycle-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def detectCycle(self, head: ListNode) -> ListNode:\n    slow = head\n    fast = head\n\n    while fast and fast.next:\n      slow = slow.next\n      fast = fast.next.next\n      if slow == fast:\n        slow = head\n        while slow != fast:\n          slow = slow.next\n          fast = fast.next\n        return slow\n\n    return None",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  public ListNode detectCycle(ListNode head) {\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (fast != null && fast.next != null) {\n      slow = slow.next;\n      fast = fast.next.next;\n      if (slow == fast) {\n        slow = head;\n        while (slow != fast) {\n          slow = slow.next;\n          fast = fast.next;\n        }\n        return slow;\n      }\n    }\n\n    return null;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* detectCycle(ListNode* head) {\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (fast && fast->next) {\n      slow = slow->next;\n      fast = fast->next->next;\n      if (slow == fast) {\n        slow = head;\n        while (slow != fast) {\n          slow = slow->next;\n          fast = fast->next;\n        }\n        return slow;\n      }\n    }\n\n    return nullptr;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/142.html",
    "category": "Algorithms",
    "acceptance_rate": 54.57561748457111,
    "topics": [
      "Hash Table",
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 14272,
    "dislikes": 1021,
    "similar_questions": "[{\"title\": \"Linked List Cycle\", \"titleSlug\": \"linked-list-cycle\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Duplicate Number\", \"titleSlug\": \"find-the-duplicate-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"3M\", \"totalAcceptedRaw\": 1616252, \"totalSubmissionRaw\": 2961490, \"acRate\": \"54.6%\"}",
    "title_pt": "Ciclo em Lista Encadeada II",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada, retorne <em>o nó onde o ciclo começa. Se não houver ciclo, retorne </em><code>null</code>.</p>\n\n<p>Há um ciclo em uma lista encadeada se existir algum nó na lista que possa ser alcançado novamente seguindo continuamente o ponteiro <code>next</code>. Internamente, <code>pos</code> é usado para denotar o índice do nó ao qual o ponteiro <code>next</code> da cauda está conectado (<strong>indexado em 0</strong>). Ele é <code>-1</code> se não houver ciclo. <strong>Observe que</strong> <code>pos</code> <strong>não é passado como parâmetro</strong>.</p>\n\n<p><strong>Não modifique</strong> a lista encadeada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png\" style=\"height: 145px; width: 450px;\" />\n<pre>\n<strong>Entrada:</strong> head = [3,2,0,-4], pos = 1\n<strong>Saída:</strong> a cauda se conecta ao nó de índice 1\n<strong>Explicação:</strong> Há um ciclo na lista encadeada, em que a cauda se conecta ao segundo nó.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png\" style=\"height: 105px; width: 201px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2], pos = 0\n<strong>Saída:</strong> a cauda se conecta ao nó de índice 0\n<strong>Explicação:</strong> Há um ciclo na lista encadeada, em que a cauda se conecta ao primeiro nó.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png\" style=\"height: 65px; width: 65px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1], pos = -1\n<strong>Saída:</strong> sem ciclo\n<strong>Explicação:</strong> Não há ciclo na lista encadeada.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pos</code> é <code>-1</code> ou um <strong>índice válido</strong> na lista encadeada.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue resolvê-lo usando memória <code>O(1)</code> (isto é, constante)?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "143",
    "paidOnly": false,
    "title": "Reorder List",
    "titleSlug": "reorder-list",
    "url": "https://leetcode.com/problems/reorder-list",
    "description_url": "https://leetcode.com/problems/reorder-list/description/",
    "description": "<p>You are given the head of a singly linked-list. The list can be represented as:</p>\n\n<pre>\nL<sub>0</sub> &rarr; L<sub>1</sub> &rarr; &hellip; &rarr; L<sub>n - 1</sub> &rarr; L<sub>n</sub>\n</pre>\n\n<p><em>Reorder the list to be on the following form:</em></p>\n\n<pre>\nL<sub>0</sub> &rarr; L<sub>n</sub> &rarr; L<sub>1</sub> &rarr; L<sub>n - 1</sub> &rarr; L<sub>2</sub> &rarr; L<sub>n - 2</sub> &rarr; &hellip;\n</pre>\n\n<p>You may not modify the values in the list&#39;s nodes. Only nodes themselves may be changed.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg\" style=\"width: 422px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4]\n<strong>Output:</strong> [1,4,2,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [1,5,2,4,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reorder-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reorderList(self, head: ListNode) -> None:\n    def findMid(head: ListNode):\n      prev = None\n      slow = head\n      fast = head\n\n      while fast and fast.next:\n        prev = slow\n        slow = slow.next\n        fast = fast.next.next\n      prev.next = None\n\n      return slow\n\n    def reverse(head: ListNode) -> ListNode:\n      prev = None\n      curr = head\n\n      while curr:\n        next = curr.next\n        curr.next = prev\n        prev = curr\n        curr = next\n\n      return prev\n\n    def merge(l1: ListNode, l2: ListNode) -> None:\n      while l2:\n        next = l1.next\n        l1.next = l2\n        l1 = l2\n        l2 = next\n\n    if not head or not head.next:\n      return\n\n    mid = findMid(head)\n    reversed = reverse(mid)\n    merge(head, reversed)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void reorderList(ListNode head) {\n    if (head == null || head.next == null)\n      return;\n\n    ListNode mid = findMid(head);\n    ListNode reversed = reverse(mid);\n    merge(head, reversed);\n  }\n\n  private ListNode findMid(ListNode head) {\n    ListNode prev = null;\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (fast != null && fast.next != null) {\n      prev = slow;\n      slow = slow.next;\n      fast = fast.next.next;\n    }\n    prev.next = null;\n\n    return slow;\n  }\n\n  private ListNode reverse(ListNode head) {\n    ListNode prev = null;\n    ListNode curr = head;\n\n    while (curr != null) {\n      ListNode next = curr.next;\n      curr.next = prev;\n      prev = curr;\n      curr = next;\n    }\n\n    return prev;\n  }\n\n  private void merge(ListNode l1, ListNode l2) {\n    while (l2 != null) {\n      ListNode next = l1.next;\n      l1.next = l2;\n      l1 = l2;\n      l2 = next;\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void reorderList(ListNode* head) {\n    if (!head || !head->next)\n      return;\n\n    ListNode* mid = findMid(head);\n    ListNode* reversed = reverse(mid);\n    merge(head, reversed);\n  }\n\n private:\n  ListNode* findMid(ListNode* head) {\n    ListNode* prev = nullptr;\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (fast && fast->next) {\n      prev = slow;\n      slow = slow->next;\n      fast = fast->next->next;\n    }\n    prev->next = nullptr;\n\n    return slow;\n  }\n\n  ListNode* reverse(ListNode* head) {\n    ListNode* prev = nullptr;\n    ListNode* curr = head;\n\n    while (curr) {\n      ListNode* next = curr->next;\n      curr->next = prev;\n      prev = curr;\n      curr = next;\n    }\n\n    return prev;\n  }\n\n  void merge(ListNode* l1, ListNode* l2) {\n    while (l2) {\n      ListNode* next = l1->next;\n      l1->next = l2;\n      l1 = l2;\n      l2 = next;\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/143.html",
    "category": "Algorithms",
    "acceptance_rate": 62.20657797971707,
    "topics": [
      "Linked List",
      "Two Pointers",
      "Stack",
      "Recursion"
    ],
    "hints": [],
    "likes": 11728,
    "dislikes": 453,
    "similar_questions": "[{\"title\": \"Delete the Middle Node of a Linked List\", \"titleSlug\": \"delete-the-middle-node-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Take K of Each Character From Left and Right\", \"titleSlug\": \"take-k-of-each-character-from-left-and-right\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1233268, \"totalSubmissionRaw\": 1982539, \"acRate\": \"62.2%\"}",
    "title_pt": "Reordenar Lista",
    "description_pt": "<p>Você recebe o <code>head</code> de uma lista encadeada simplesmente encadeada. A lista pode ser representada como:</p>\n\n<pre>\nL<sub>0</sub> &rarr; L<sub>1</sub> &rarr; &hellip; &rarr; L<sub>n - 1</sub> &rarr; L<sub>n</sub>\n</pre>\n\n<p><em>Reordene a lista para que ela fique na seguinte forma:</em></p>\n\n<pre>\nL<sub>0</sub> &rarr; L<sub>n</sub> &rarr; L<sub>1</sub> &rarr; L<sub>n - 1</sub> &rarr; L<sub>2</sub> &rarr; L<sub>n - 2</sub> &rarr; &hellip;\n</pre>\n\n<p>Você não pode modificar os valores nos nós da lista. Apenas os próprios nós podem ser alterados.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg\" style=\"width: 422px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4]\n<strong>Saída:</strong> [1,4,2,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5]\n<strong>Saída:</strong> [1,5,2,4,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[1, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "144",
    "paidOnly": false,
    "title": "Binary Tree Preorder Traversal",
    "titleSlug": "binary-tree-preorder-traversal",
    "url": "https://leetcode.com/problems/binary-tree-preorder-traversal",
    "description_url": "https://leetcode.com/problems/binary-tree-preorder-traversal/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,2,3]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,2,4,5,6,7,3,8,9]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-preorder-traversal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n    ans = []\n\n    def preorder(root: Optional[TreeNode]) -> None:\n      if not root:\n        return\n\n      ans.append(root.val)\n      preorder(root.left)\n      preorder(root.right)\n\n    preorder(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> preorderTraversal(TreeNode root) {\n    List<Integer> ans = new ArrayList<>();\n    preorder(root, ans);\n    return ans;\n  }\n\n  private void preorder(TreeNode root, List<Integer> ans) {\n    if (root == null)\n      return;\n\n    ans.add(root.val);\n    preorder(root.left, ans);\n    preorder(root.right, ans);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> preorderTraversal(TreeNode* root) {\n    vector<int> ans;\n    preorder(root, ans);\n    return ans;\n  }\n\n private:\n  void preorder(TreeNode* root, vector<int>& ans) {\n    if (root == nullptr)\n      return;\n\n    ans.push_back(root->val);\n    preorder(root->left, ans);\n    preorder(root->right, ans);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/144.html",
    "category": "Algorithms",
    "acceptance_rate": 72.90807894066384,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8400,
    "dislikes": 222,
    "similar_questions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Verify Preorder Sequence in Binary Search Tree\", \"titleSlug\": \"verify-preorder-sequence-in-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Preorder Traversal\", \"titleSlug\": \"n-ary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Sum in a Binary Tree\", \"titleSlug\": \"kth-largest-sum-in-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"2.8M\", \"totalAcceptedRaw\": 2008873, \"totalSubmissionRaw\": 2755360, \"acRate\": \"72.9%\"}",
    "title_pt": "Travessia em Pré-Ordem de Árvore Binária",
    "description_pt": "<p>Dado a <code>root</code> de uma árvore binária, retorne <em>a travessia em pré-ordem dos valores dos seus nós</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,2,3]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,2,4,5,6,7,3,8,9]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> A solução recursiva é trivial, você conseguiria fazê-la iterativamente?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "145",
    "paidOnly": false,
    "title": "Binary Tree Postorder Traversal",
    "titleSlug": "binary-tree-postorder-traversal",
    "url": "https://leetcode.com/problems/binary-tree-postorder-traversal",
    "description_url": "https://leetcode.com/problems/binary-tree-postorder-traversal/description/",
    "description": "<p>Given the <code>root</code> of a&nbsp;binary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[3,2,1]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[4,6,7,5,2,9,8,3,1]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?",
    "solution_url": "https://leetcode.com/problems/binary-tree-postorder-traversal/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nTo traverse a tree, we use two main strategies:\n\n- Breadth-First Search (BFS): This strategy involves scanning the tree level by level from the top down, visiting nodes at higher levels before those at lower levels.\n\n- Depth-First Search (DFS): This approach explores as far down a branch as possible before backtracking. It starts at the root, proceeds to a leaf, and then returns to explore other branches. DFS can be further categorized into:\n  - Preorder: Visit the root first, then the left subtree, followed by the right subtree.\n  - Inorder: Visit the left subtree first, then the root, and then the right subtree.\n  - Postorder: Visit the left subtree first, then the right subtree, and finally the root.\n\n![Tree Traversal Example](../Figures/145/traverse2.png)\n*Figure 1. Nodes are numbered in the order they are visited; refer to the sequence `1-2-3-4-5` to compare different traversal strategies.*\n\nFor a binary tree with the root `[1, null, 2, 3]`, the tree structure is as follows:\n\n```\n1\n \\\n  2\n /\n3\n```\n\nIn Postorder traversal, nodes are visited in the sequence: `3` (left subtree), `2` (right subtree), and finally `1` (root). Thus, the output for this input should be `[3, 2, 1]`.\n\n---\n\n### Approach 1: Recursive Postorder Traversal\n\n#### Intuition\n\n![recursion](../Figures/145/recursion.png)\n*Figure 2. Recursive DFS traversals.*\n\nIn this approach, we treat each node as the root of its subtree. We start by recursively traversing the left subtree. If the left child is not null, we continue exploring until the left subtree is fully traversed. Then, we move to the right subtree and repeat the process. After both subtrees are explored, we process the current node by adding its value to the result list.\n\nThe base case occurs when the current node is null, indicating no further subtree to explore. At this point, we simply return and backtrack.\n\n#### Algorithm\n\n1. Define a helper function `postorderTraversalHelper`:\n   - If `currentNode` is `null`, return to stop further recursion.\n   - Recursively call `postorderTraversalHelper` with `currentNode->left` to process the left subtree.\n   - Recursively call `postorderTraversalHelper` with `currentNode->right` to process the right subtree.\n   - Append `currentNode->val` to the `result` array to collect values in postorder.\n2. In the `postorderTraversal` function:\n   - Initialize an empty `result` array to store the postorder ordering of the nodes in`root`.\n   - Call `postorderTraversalHelper` with the root node and `result` to start the traversal.\n   - Return the `result` array containing the postorder traversal.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/X7v7GcVB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"X7v7GcVB\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes.\n\n- Time complexity: $O(n)$\n\n    Each node is visited once during the traversal, so the time complexity is linear with respect to the number of nodes `n`.\n\n- Space complexity: $O(n)$\n\n    The space complexity is $O(n)$ due to the recursion stack. In the worst case (e.g., a completely unbalanced tree), the recursion stack could hold all `n` nodes.\n\n---\n\n### Approach 2: Manipulating Preorder Traversal (Iterative Hack)\n\n#### Intuition\n\nLet's take a creative leap in this approach by exploiting the relationship between preorder and postorder traversals. In a standard preorder traversal, we visit the root node before we visit the left and right subtrees. However, postorder traversal requires us to visit the left and right subtrees before the root node.\n\nWe can adapt the preorder traversal by visiting nodes in the order of root, right subtree, and then left subtree. Reversing the resulting list from this modified preorder traversal gives us the correct postorder sequence.\n\nWe use a stack to traverse the tree iteratively, starting with the root node. We push the current node onto the stack and add its value to the result list. Instead of moving to the left child, we move to the right child. If there's no right child, we pop a node from the stack and move to its left child. This approach processes the right subtree before the left subtree, aligning with the modified preorder traversal.\n\nAfter traversing the entire tree, we reverse the result list to get the postorder sequence: left subtree, right subtree, root.\n\n#### Algorithm\n \n1. Initialize an empty `result` list to store the traversal result, a `traversalStack` for nodes, and set `currentNode` to `root`.\n2. While `currentNode` is not `null` or `traversalStack` is not empty:\n   - If `currentNode` is not `null`, add `currentNode->val` to the `result` list before processing its children.\n   - Push `currentNode` onto the `traversalStack` to revisit it later.\n   - Move `currentNode` to `currentNode->right` to continue traversal in the right subtree.\n   - If `currentNode` is `null`, pop the top node from `traversalStack` and set it to `currentNode`.\n   - Move `currentNode` to `currentNode->left` to process the left subtree.\n3. Reverse the `result` list to correct the order from preorder to postorder.\n4. Return the `result` list with postorder traversal values.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5wrszGxT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5wrszGxT\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes. \n\n* Time complexity: $O(n)$\n\n    Each node is processed a constant number of times (essentially twice), so the time complexity remains linear with respect to `n`.\n\n* Space complexity: $O(n)$\n\n    The space complexity is $O(2n) = O(n)$ due to the stack used for traversing the tree nodes. This stack could hold up to `n` nodes in the worst case. \n\n---\n\n### Approach 3: Two Stack Postorder Traversal (Iterative)\n\n#### Intuition\n\nInstead of relying on hacks and tricks, this time we will build on the idea that we need to control the order in which nodes are processed to achieve postorder traversal.  \n\nTo achieve postorder traversal without recursion, we use two stacks to control the node processing order systematically.\n\nFirst, we push the root node onto the first stack. This stack simulates the recursive traversal of the tree. To process nodes in postorder (left-right-root), we need a second stack to reverse the order. As we pop nodes from the first stack, we push them onto the second stack. This reversal ensures that nodes are processed in the correct order.\n\nAfter all nodes are transferred to the second stack, popping from it gives us the nodes in postorder sequence. This method efficiently achieves the desired traversal order by leveraging the two stacks to manage the processing sequence without needing a final reversal step.\n\nIn summary, the two-stack approach uses the first stack for tree traversal and the second stack to reverse the order, resulting in a postorder traversal. Despite initially seeming like a manipulation of preorder traversal, the final order of nodes from the second stack aligns with postorder traversal.\n\n#### Algorithm\n \n1. Initialize an empty `result` list, and create `mainStack` and `pathStack` for nodes.\n2. Check if `root` is `null`; if so, return `result` immediately, indicating there are no nodes to process.\n3. Push `root` onto `mainStack` to start the traversal.\n4. While `mainStack` is not empty:\n   - Peek at the top of `mainStack` to examine the current node.\n   - If the top of `pathStack` is the same as the top of `mainStack`, add `root->val` to the `result` list.\n   - Pop the top node from both `mainStack` and `pathStack` after processing.\n   - Otherwise, push the current node onto `pathStack`.\n   - Push `root->right` and `root->left` onto `mainStack` if they exist to process their children.\n5. Return the `result` list containing postorder traversal values.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/GkvWqGqp/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"GkvWqGqp\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes. \n\n* Time complexity: $O(n)$\n\n    Each node is processed a constant number of times (once when pushed to the first stack and once when popped to the second stack), so the time complexity is linear with respect to `n`.\n\n* Space complexity: $O(n)$\n\n    The space complexity is $O(n)$ due to the use of two stacks. Each stack can hold up to `n` nodes in the worst case.\n\n---\n\n### Approach 4: Single Stack Postorder Traversal (Iterative)\n\n#### Intuition\n\nAfter exploring the two-stack approach, we might seek to optimize further by reducing space complexity. While two stacks effectively manage traversal order, they double our space usage. Instead, we can use a single stack combined with a `previousNode` pointer to track the traversal.\n\nWe start by pushing nodes onto the stack while traversing left, similar to inorder traversal. In postorder traversal, we must process each node after its right subtree. To manage this, the `previousNode` pointer helps remember the last processed node.\n\nWhen a node is reached on the stack, we first check if it has an unvisited right child. If so, we move to that right child since we can't process the current node until after its right subtree. If the node has no right child or its right child has already been processed (indicated by `previousNode`), we process the node by popping it from the stack and adding its value to the result list, then update `previousNode` to this node.\n\n#### Algorithm\n \n1. Initialize an empty `result` list, set `previousNode` to `null`, and initialize `traversalStack`.\n2. Check if `root` is `null`; if so, return `result` immediately, indicating there are no nodes to process.\n3. While `root` is not `null` or `traversalStack` is not empty:\n   - If `root` is not `null`, push `root` onto `traversalStack`.\n   - Move `root` to `root->left` to process the left subtree.\n   - If `root` is `null`, peek at the top of `traversalStack`.\n   - If `root->right` is `null` or `root->right` equals `previousNode`, add `root->val` to `result`.\n   - Pop `root` from `traversalStack`, set `previousNode` to `root`, and set `root` to `null`.\n   - If `root->right` is not `null`, move `root` to `root->right` to continue the traversal.\n4. Return the `result` list containing postorder traversal values.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/PMTa9tEv/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"PMTa9tEv\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes.\n\n* Time complexity: $O(n)$\n\n    Each node is processed a constant number of times. The stack operations and pointer manipulations also contribute to a linear time complexity with respect to `n`.\n\n* Space complexity: $O(n)$\n\n    Although this approach uses only a single stack, in the worst case, the stack can still hold up to `n` nodes, so the space complexity remains $O(n)$. However, this approach optimizes the space usage compared to using two stacks.\n\n---\n\n### Approach 5: Morris Traversal (No stack)\n\n#### Intuition\n\nAll the approaches so far have been using some auxiliary space. To optimize for space complexity, we can use a traversal algorithm called Morris traversal. In Morris traversal, the tree structure is temporarily modified to create temporary links that simulate the effect of a stack or recursion. As a result, there is no overhead from additional data structures and the space complexity is constant. This traversal is tricky to understand at first, but the high level idea is to link each predecessor back to the current node, which allows us to trace back to the top of the tree. We encourage you to simulate the traversal on a piece of paper to get a stronger understanding.\n\nIn setting up Morris traversal, we introduce a `dummyNode` with a value that is not part of the original tree and link it to the root. Our traversal begins with this dummyNode, treating it as the new root of the tree.\n\nFor each node, we look for its in-order predecessor, the rightmost node in its left subtree. We do this so that the in-order predecessor can be used to create a temporary link back to the current node, simulating the recursive call stack.\n- If the current node has a left child, we find the rightmost node in the left subtree. This rightmost node is the in-order predecessor.\n- We then create a temporary link from this predecessor to the current node by setting its right pointer to the current node.\n\nIf the predecessor’s right pointer is `null`, set it to point to the current node and move to the left child. This simulates the recursive call by allowing us to return to the current node after processing the left subtree.\n\nWhen a node’s predecessor’s right pointer points back to the current node, it indicates the left subtree is processed. Process the current node and reverse the temporary link to restore the tree’s structure.\n\nFinally, move to the right child and continue the traversal.\n\nMorris traversal operates in $O(n)$ time because finding the predecessor is not done for every node but only for nodes with a valid left child.\n\n> Note: Morris traversal may be a surprise topic in interviews. It’s useful to know but not always the main focus; prioritize understanding basic traversal methods first.\n\n#### Algorithm\n \n1. Initialize an empty `result` list and create a dummy node with the value `-1`. Set `dummyNode->left` to `root` and update `root` to `dummyNode`.\n2. Check if `root` is `null`; if so, return `result` immediately, indicating there are no nodes to process.\n3. While `root` is not `null`:\n   - If `root->left` is not `null`, find the rightmost node (predecessor) in the `root->left` subtree.\n   - If the right child of the predecessor is `null`, set the right child to `root` and move `root` to `root->left`.\n   - If the right child of the predecessor is `root`, perform reverse traversal of the `root->left` subtree and add values to `result`.\n   - Reverse the subtree back to its original state by restoring pointers.\n   - Remove the temporary link from the predecessor to `root` and move `root` to `root->right`.\n   - If `root->left` is `null`, move `root` to `root->right`.\n4. Return the `result` list containing postorder traversal values.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/XKjo3KQc/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"XKjo3KQc\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes.\n\n* Time complexity: $O(n)$\n\n    Each node is visited a constant number of times, and the traversal through the tree is linear in terms of `n`.\n\n* Space complexity: $O(1)$\n\n    The Morris Traversal technique uses no extra space beyond the pointers used for traversal. The temporary modifications to the tree structure are reversed before the traversal ends, so the space complexity is constant.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n    ans = []\n\n    def postorder(root: Optional[TreeNode]) -> None:\n      if not root:\n        return\n\n      postorder(root.left)\n      postorder(root.right)\n      ans.append(root.val)\n\n    postorder(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> postorderTraversal(TreeNode root) {\n    List<Integer> ans = new ArrayList<>();\n    postorder(root, ans);\n    return ans;\n  }\n\n  private void postorder(TreeNode root, List<Integer> ans) {\n    if (root == null)\n      return;\n\n    postorder(root.left, ans);\n    postorder(root.right, ans);\n    ans.add(root.val);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> postorderTraversal(TreeNode* root) {\n    vector<int> ans;\n    postorder(root, ans);\n    return ans;\n  }\n\n private:\n  void postorder(TreeNode* root, vector<int>& ans) {\n    if (root == nullptr)\n      return;\n\n    postorder(root->left, ans);\n    postorder(root->right, ans);\n    ans.push_back(root->val);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/145.html",
    "category": "Algorithms",
    "acceptance_rate": 75.44344923660911,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 7395,
    "dislikes": 215,
    "similar_questions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Postorder Traversal\", \"titleSlug\": \"n-ary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Fuel Cost to Report to the Capital\", \"titleSlug\": \"minimum-fuel-cost-to-report-to-the-capital\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1613826, \"totalSubmissionRaw\": 2139124, \"acRate\": \"75.4%\"}",
    "title_pt": "Percurso em Pós-Ordem de Árvore Binária",
    "description_pt": "<p>Dada a raiz <code>root</code> de uma&nbsp;árvore binária, retorne <em>o percurso em pós-ordem dos valores de seus nós</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,null,2,3]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[3,2,1]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png\" style=\"width: 200px; height: 264px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,2,3,4,5,null,8,null,null,6,7,9]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[4,6,7,5,2,9,8,3,1]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/08/29/tree_2.png\" style=\"width: 350px; height: 286px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> A solução recursiva é trivial; você conseguiria fazê-la iterativamente?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "146",
    "paidOnly": false,
    "title": "LRU Cache",
    "titleSlug": "lru-cache",
    "url": "https://leetcode.com/problems/lru-cache",
    "description_url": "https://leetcode.com/problems/lru-cache/description/",
    "description": "<p>Design a data structure that follows the constraints of a <strong><a href=\"https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\" target=\"_blank\">Least Recently Used (LRU) cache</a></strong>.</p>\n\n<p>Implement the <code>LRUCache</code> class:</p>\n\n<ul>\n\t<li><code>LRUCache(int capacity)</code> Initialize the LRU cache with <strong>positive</strong> size <code>capacity</code>.</li>\n\t<li><code>int get(int key)</code> Return the value of the <code>key</code> if the key exists, otherwise return <code>-1</code>.</li>\n\t<li><code>void put(int key, int value)</code> Update the value of the <code>key</code> if the <code>key</code> exists. Otherwise, add the <code>key-value</code> pair to the cache. If the number of keys exceeds the <code>capacity</code> from this operation, <strong>evict</strong> the least recently used key.</li>\n</ul>\n\n<p>The functions <code>get</code> and <code>put</code> must each run in <code>O(1)</code> average time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;LRUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\n<strong>Output</strong>\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\n<strong>Explanation</strong>\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1);    // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2);    // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1);    // return -1 (not found)\nlRUCache.get(3);    // return 3\nlRUCache.get(4);    // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= capacity &lt;= 3000</code></li>\n\t<li><code>0 &lt;= key &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li>\n\t<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/lru-cache/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Node:\n  def __init__(self, key: int, value: int):\n    self.key = key\n    self.value = value\n    self.prev = None\n    self.next = None\n\n\nclass LRUCache:\n  def __init__(self, capacity: int):\n    self.capacity = capacity\n    self.keyToNode = {}\n    self.head = Node(-1, -1)\n    self.tail = Node(-1, -1)\n    self.join(self.head, self.tail)\n\n  def get(self, key: int) -> int:\n    if key not in self.keyToNode:\n      return -1\n\n    node = self.keyToNode[key]\n    self.remove(node)\n    self.moveToHead(node)\n    return node.value\n\n  def put(self, key: int, value: int) -> None:\n    if key in self.keyToNode:\n      node = self.keyToNode[key]\n      node.value = value\n      self.remove(node)\n      self.moveToHead(node)\n      return\n\n    if len(self.keyToNode) == self.capacity:\n      lastNode = self.tail.prev\n      del self.keyToNode[lastNode.key]\n      self.remove(lastNode)\n\n    self.moveToHead(Node(key, value))\n    self.keyToNode[key] = self.head.next\n\n  def join(self, node1: Node, node2: Node):\n    node1.next = node2\n    node2.prev = node1\n\n  def moveToHead(self, node: Node):\n    self.join(node, self.head.next)\n    self.join(self.head, node)\n\n  def remove(self, node: Node):\n    self.join(node.prev, node.next)",
    "solution_code_java": "\t\t\t\n\nclass Node {\n  public int key;\n  public int value;\n\n  public Node(int key, int value) {\n    this.key = key;\n    this.value = value;\n  }\n}\n\nclass LRUCache {\n  public LRUCache(int capacity) {\n    this.capacity = capacity;\n  }\n\n  public int get(int key) {\n    if (!keyToNode.containsKey(key))\n      return -1;\n\n    Node node = keyToNode.get(key);\n    cache.remove(node);\n    cache.add(node);\n    return node.value;\n  }\n\n  public void put(int key, int value) {\n    if (keyToNode.containsKey(key)) {\n      keyToNode.get(key).value = value;\n      get(key);\n      return;\n    }\n\n    if (cache.size() == capacity) {\n      Node lastNode = cache.iterator().next();\n      cache.remove(lastNode);\n      keyToNode.remove(lastNode.key);\n    }\n\n    Node node = new Node(key, value);\n    cache.add(node);\n    keyToNode.put(key, node);\n  }\n\n  private int capacity;\n  private Set<Node> cache = new LinkedHashSet<>();\n  private Map<Integer, Node> keyToNode = new HashMap<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Node {\n  int key;\n  int value;\n  Node(int key, int value) : key(key), value(value) {}\n};\n\nclass LRUCache {\n public:\n  LRUCache(int capacity) : capacity(capacity) {}\n\n  int get(int key) {\n    if (!keyToIterator.count(key))\n      return -1;\n\n    const auto& it = keyToIterator[key];\n    // Move it to the front\n    cache.splice(begin(cache), cache, it);\n    return it->value;\n  }\n\n  void put(int key, int value) {\n    // No capacity issue, just update the value\n    if (keyToIterator.count(key)) {\n      const auto& it = keyToIterator[key];\n      // Move it to the front\n      cache.splice(begin(cache), cache, it);\n      it->value = value;\n      return;\n    }\n\n    // Check the capacity\n    if (cache.size() == capacity) {\n      const Node& lastNode = cache.back();\n      // that's why we store `key` in `Node`\n      keyToIterator.erase(lastNode.key);\n      cache.pop_back();\n    }\n\n    cache.emplace_front(key, value);\n    keyToIterator[key] = begin(cache);\n  }\n\n private:\n  const int capacity;\n  list<Node> cache;\n  unordered_map<int, list<Node>::iterator> keyToIterator;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/146.html",
    "category": "Algorithms",
    "acceptance_rate": 44.965481880276144,
    "topics": [
      "Hash Table",
      "Linked List",
      "Design",
      "Doubly-Linked List"
    ],
    "hints": [],
    "likes": 21785,
    "dislikes": 1127,
    "similar_questions": "[{\"title\": \"LFU Cache\", \"titleSlug\": \"lfu-cache\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Design In-Memory File System\", \"titleSlug\": \"design-in-memory-file-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Design Compressed String Iterator\", \"titleSlug\": \"design-compressed-string-iterator\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Design Most Recently Used Queue\", \"titleSlug\": \"design-most-recently-used-queue\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"4.6M\", \"totalAcceptedRaw\": 2087179, \"totalSubmissionRaw\": 4641745, \"acRate\": \"45.0%\"}",
    "title_pt": "Cache LRU",
    "description_pt": "<p>Projete uma estrutura de dados que siga as restrições de um <strong><a href=\"https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\" target=\"_blank\">cache Least Recently Used (LRU)</a></strong>.</p>\n\n<p>Implemente a classe <code>LRUCache</code>:</p>\n\n<ul>\n\t<li><code>LRUCache(int capacity)</code> Inicializa o cache LRU com tamanho <strong>positivo</strong> <code>capacity</code>.</li>\n\t<li><code>int get(int key)</code> Retorna o valor da <code>key</code> se a key existir; caso contrário, retorna <code>-1</code>.</li>\n\t<li><code>void put(int key, int value)</code> Atualiza o valor da <code>key</code> se a <code>key</code> existir. Caso contrário, adiciona o par <code>key-value</code> ao cache. Se o número de chaves exceder a <code>capacity</code> a partir desta operação, <strong>remova</strong> a key menos recentemente usada.</li>\n</ul>\n\n<p>As funções <code>get</code> e <code>put</code> devem cada uma executar em complexidade de tempo médio de <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;LRUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\n<strong>Output</strong>\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\n<strong>Explicação</strong>\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1);    // retorna 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2);    // retorna -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1);    // retorna -1 (not found)\nlRUCache.get(3);    // retorna 3\nlRUCache.get(4);    // retorna 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= capacity &lt;= 3000</code></li>\n\t<li><code>0 &lt;= key &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li>\n\t<li>No máximo <code>2 * 10<sup>5</sup></code> chamadas serão feitas a <code>get</code> e <code>put</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "147",
    "paidOnly": false,
    "title": "Insertion Sort List",
    "titleSlug": "insertion-sort-list",
    "url": "https://leetcode.com/problems/insertion-sort-list",
    "description_url": "https://leetcode.com/problems/insertion-sort-list/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list, sort the list using <strong>insertion sort</strong>, and return <em>the sorted list&#39;s head</em>.</p>\n\n<p>The steps of the <strong>insertion sort</strong> algorithm:</p>\n\n<ol>\n\t<li>Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.</li>\n\t<li>At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.</li>\n\t<li>It repeats until no input elements remain.</li>\n</ol>\n\n<p>The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif\" style=\"height:180px; width:300px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg\" style=\"width: 422px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [4,2,1,3]\n<strong>Output:</strong> [1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [-1,5,3,4,0]\n<strong>Output:</strong> [-1,0,3,4,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 5000]</code>.</li>\n\t<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/insertion-sort-list/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Overview\n\n\n[Insertion sort](https://en.wikipedia.org/wiki/Insertion_sort) is an intuitive sorting algorithm, although it is much less efficient than the more advanced algorithms such as quicksort or merge sort.\n\nOften that we perform the sorting algorithm on an [Array](https://leetcode.com/explore/learn/card/fun-with-arrays) structure,\nthis problem though asks us to perform the insertion sort on a **linked list** data structure, which makes the implementation a bit challenging.\n\nIn this article, we will present some tricks to manipulate the linked list, which would help us to simplify the logics of implementation.\n\n\n---\n\n### Approach 1: Insertion Sort\n\n#### Intuition\n\nLet us first review the idea of insertion sort algorithm, which can be broke down into the following steps:\n\n- First of all, we create an empty list which would be used to hold the results of sorting.\n\n- We then iterate through each element in the _input_ list. For each element, we need to find a proper position in the resulting list to insert the element, so that the order of the resulting list is maintained.\n\n- As one can see, once the iteration in the above step terminates, we will obtain the resulting list where the elements are _ordered_.\n\nNow, let us walk through a simple example, by applying the above intuition.\n\nGiven the input list `input=[4, 3, 5]`, we have initially an empty resulting list `result=[]`.\n\n- We then iterate over the input list. For the first element `4`, we need to find a proper position in the resulting list to place it.\nSince the resulting list is still empty, we then simply _append_ it to the resulting list, _i.e._ `result=[4]`.\n\n![step 1](../Figures/147/147_linked_list_step_1.png)\n\n- Now for the second element (_i.e._ `3`) in the input list, similarly we need to insert it properly into the resulting list.\nAs one can see, we need to insert it right before the element `4`.\nAs a result, the resulting list becomes `[3, 4]`.\n\n![step 2](../Figures/147/147_linked_list_step_2.png)\n\n- Finally, for the last element (_i.e._ `5`) in the input list, as it turns out, the proper position to place it is the _tail_ of the resulting list.\nWith this last iteration, we obtain a _sorted_ list as `result=[3, 4, 5]`.\n\n![step 3](../Figures/147/147_linked_list_step_3.png)\n\n\n#### Algorithm\n\nTo translate the above intuition into the implementation, we applied two **tricks**.\n\n>The first trick is that we will create a `dummy` (`pseudo_head`) node which serves as a pointer pointing to the resulting list.\n\nMore precisely, this node facilitates us to always get a _hold_ on the resulting list, especially when we need to insert a new element to the head of the resulting list.\nOne will see later in more details how it can greatly simplify the logic.\n\nIn a _singly-linked list_, each node has only one pointer that points to the next node.\nIf we would like to insert a new node (say `B`) before certain node (say `A`), we need to know the node (say `C`) that is currently before the node `A`, _i.e._ `C -> A`.\nWith the reference in the node `C`, we could now insert the new node, _i.e._ `C -> B -> A`.\n\nGiven the above insight, in order to insert a new element into a singly-linked list, we apply another trick.\n\n>The idea is that we use a _**pair of pointers**_ (namely `prev -> next`) which serve as place-holders to guard the position where in-between we would insert a new element (_i.e._ `prev -> new_node -> next`).\n\nWith the same example before, _i.e._ `input=[4, 3, 5]`, we illustrate what the above helper pointers look like at the moment of insertion, in the following graph:\n\n![pointers](../Figures/147/147_pointers.png)\n\n#### Implementation\n\nHere are some sample implementations based on the above ideas:\n\n<iframe src=\"https://leetcode.com/playground/gDxDYr3y/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"gDxDYr3y\"></iframe>\n\n\n\n#### Complexity Analysis\n\nLet $N$ be the number of elements in the input list.\n\n- Time Complexity: $\\mathcal{O}(N^2)$\n\n    - First of all, we run an iteration over the input list.\n\n    - At each iteration, we insert an element into the resulting list. In the worst case where the position to insert is the tail of the list, we have to walk through the entire resulting list.\n\n    - As a result, the total steps that we need to walk in the worst case would be $\\sum_{i=1}^{N} i = \\frac{N(N+1)}{2}$.\n\n    - To sum up, the overall time complexity of the algorithm is $\\mathcal{O}(N^2)$.\n\n\n- Space Complexity: $\\mathcal{O}(1)$\n\n    - We used some pointers within the algorithm. However, their memory consumption is constant regardless of the input.\n\n    - **Note**, we did not create new nodes to hold the values of input list, but simply _reorder_ the existing nodes.\n\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def insertionSortList(self, head: ListNode) -> ListNode:\n    dummy = ListNode(0)\n    curr = head\n\n    while curr:\n      prev = dummy\n      while prev.next and prev.next.val < curr.val:\n        prev = prev.next\n      next = curr.next\n      curr.next = prev.next\n      prev.next = curr\n      curr = next\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode insertionSortList(ListNode head) {\n    ListNode dummy = new ListNode(0);\n    ListNode prev = dummy; // The last (largest) of the sorted list\n\n    while (head != null) {       // Current inserting node\n      ListNode next = head.next; // Cache next inserting node\n      if (prev.val >= head.val)  // `prev` >= current inserting node\n        prev = dummy;            // Move `prev` to the front\n      while (prev.next != null && prev.next.val < head.val)\n        prev = prev.next;\n      head.next = prev.next;\n      prev.next = head;\n      head = next; // Update current inserting node\n    }\n\n    return dummy.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* insertionSortList(ListNode* head) {\n    ListNode dummy(0);\n    ListNode* prev = &dummy;  // The last (largest) of the sorted list\n\n    while (head) {                  // Current inserting node\n      ListNode* next = head->next;  // Cache next inserting node\n      if (prev->val >= head->val)   // `prev` >= current inserting node\n        prev = &dummy;              // Move `prev` to the front\n      while (prev->next && prev->next->val < head->val)\n        prev = prev->next;\n      head->next = prev->next;\n      prev->next = head;\n      head = next;  // Update current inserting node\n    }\n\n    return dummy.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/147.html",
    "category": "Algorithms",
    "acceptance_rate": 56.244827809930875,
    "topics": [
      "Linked List",
      "Sorting"
    ],
    "hints": [],
    "likes": 3251,
    "dislikes": 873,
    "similar_questions": "[{\"title\": \"Sort List\", \"titleSlug\": \"sort-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insert into a Sorted Circular Linked List\", \"titleSlug\": \"insert-into-a-sorted-circular-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"424.8K\", \"totalSubmission\": \"755.2K\", \"totalAcceptedRaw\": 424783, \"totalSubmissionRaw\": 755239, \"acRate\": \"56.2%\"}",
    "title_pt": "Ordenação por Inserção em Lista Encadeada",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada simplesmente encadeada, ordene a lista usando <strong>insertion sort</strong> e retorne <em>o <code>head</code> da lista ordenada</em>.</p>\n\n<p>Os passos do algoritmo <strong>insertion sort</strong>:</p>\n\n<ol>\n\t<li>Insertion sort itera, consumindo um elemento de entrada em cada repetição e expandindo uma lista de saída ordenada.</li>\n\t<li>Em cada iteração, insertion sort remove um elemento dos dados de entrada, encontra a posição em que ele pertence dentro da lista ordenada e o insere ali.</li>\n\t<li>Ele se repete até que não restem elementos de entrada.</li>\n</ol>\n\n<p>A seguir está um exemplo gráfico do algoritmo insertion sort. A lista parcialmente ordenada (preta) inicialmente contém apenas o primeiro elemento da lista. Um elemento (vermelho) é removido dos dados de entrada e inserido in-place na lista ordenada a cada iteração.</p>\n<img alt=\"\" src=\"https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif\" style=\"height:180px; width:300px\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg\" style=\"width: 422px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [4,2,1,3]\n<strong>Saída:</strong> [1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [-1,5,3,4,0]\n<strong>Saída:</strong> [-1,0,3,4,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[1, 5000]</code>.</li>\n\t<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "148",
    "paidOnly": false,
    "title": "Sort List",
    "titleSlug": "sort-list",
    "url": "https://leetcode.com/problems/sort-list",
    "description_url": "https://leetcode.com/problems/sort-list/description/",
    "description": "<p>Given the <code>head</code> of a linked list, return <em>the list after sorting it in <strong>ascending order</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg\" style=\"width: 450px; height: 194px;\" />\n<pre>\n<strong>Input:</strong> head = [4,2,1,3]\n<strong>Output:</strong> [1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg\" style=\"width: 550px; height: 184px;\" />\n<pre>\n<strong>Input:</strong> head = [-1,5,3,4,0]\n<strong>Output:</strong> [-1,0,3,4,5]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Can you sort the linked list in <code>O(n logn)</code> time and <code>O(1)</code> memory (i.e. constant space)?</p>\n",
    "solution_url": "https://leetcode.com/problems/sort-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def sortList(self, head: ListNode) -> ListNode:\n    def split(head: ListNode, k: int) -> ListNode:\n      while k > 1 and head:\n        head = head.next\n        k -= 1\n      rest = head.next if head else None\n      if head:\n        head.next = None\n      return rest\n\n    def merge(l1: ListNode, l2: ListNode) -> tuple:\n      dummy = ListNode(0)\n      tail = dummy\n\n      while l1 and l2:\n        if l1.val > l2.val:\n          l1, l2 = l2, l1\n        tail.next = l1\n        l1 = l1.next\n        tail = tail.next\n      tail.next = l1 if l1 else l2\n      while tail.next:\n        tail = tail.next\n\n      return dummy.next, tail\n\n    length = 0\n    curr = head\n    while curr:\n      length += 1\n      curr = curr.next\n\n    dummy = ListNode(0, head)\n\n    k = 1\n    while k < length:\n      curr = dummy.next\n      tail = dummy\n      while curr:\n        l = curr\n        r = split(l, k)\n        curr = split(r, k)\n        mergedHead, mergedTail = merge(l, r)\n        tail.next = mergedHead\n        tail = mergedTail\n      k *= 2\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode sortList(ListNode head) {\n    final int length = getLength(head);\n    ListNode dummy = new ListNode(0, head);\n\n    for (int k = 1; k < length; k *= 2) {\n      ListNode curr = dummy.next;\n      ListNode tail = dummy;\n      while (curr != null) {\n        ListNode l = curr;\n        ListNode r = split(l, k);\n        curr = split(r, k);\n        ListNode[] merged = merge(l, r);\n        tail.next = merged[0];\n        tail = merged[1];\n      }\n    }\n\n    return dummy.next;\n  }\n\n  private int getLength(ListNode head) {\n    int length = 0;\n    for (ListNode curr = head; curr != null; curr = curr.next)\n      ++length;\n    return length;\n  }\n\n  private ListNode split(ListNode head, int k) {\n    while (--k > 0 && head != null)\n      head = head.next;\n    ListNode rest = head == null ? null : head.next;\n    if (head != null)\n      head.next = null;\n    return rest;\n  }\n\n  private ListNode[] merge(ListNode l1, ListNode l2) {\n    ListNode dummy = new ListNode(0);\n    ListNode tail = dummy;\n\n    while (l1 != null && l2 != null) {\n      if (l1.val > l2.val) {\n        ListNode temp = l1;\n        l1 = l2;\n        l2 = temp;\n      }\n      tail.next = l1;\n      l1 = l1.next;\n      tail = tail.next;\n    }\n    tail.next = l1 == null ? l2 : l1;\n    while (tail.next != null)\n      tail = tail.next;\n\n    return new ListNode[] {dummy.next, tail};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* sortList(ListNode* head) {\n    const int length = getLength(head);\n    ListNode dummy(0, head);\n\n    for (int k = 1; k < length; k *= 2) {\n      ListNode* curr = dummy.next;\n      ListNode* tail = &dummy;\n      while (curr) {\n        ListNode* l = curr;\n        ListNode* r = split(l, k);\n        curr = split(r, k);\n        auto [mergedHead, mergedTail] = merge(l, r);\n        tail->next = mergedHead;\n        tail = mergedTail;\n      }\n    }\n\n    return dummy.next;\n  }\n\n private:\n  int getLength(ListNode* head) {\n    int length = 0;\n    for (ListNode* curr = head; curr; curr = curr->next)\n      ++length;\n    return length;\n  }\n\n  ListNode* split(ListNode* head, int k) {\n    while (--k && head)\n      head = head->next;\n    ListNode* rest = head ? head->next : nullptr;\n    if (head != nullptr)\n      head->next = nullptr;\n    return rest;\n  }\n\n  pair<ListNode*, ListNode*> merge(ListNode* l1, ListNode* l2) {\n    ListNode dummy(0);\n    ListNode* tail = &dummy;\n\n    while (l1 && l2) {\n      if (l1->val > l2->val)\n        swap(l1, l2);\n      tail->next = l1;\n      l1 = l1->next;\n      tail = tail->next;\n    }\n    tail->next = l1 ? l1 : l2;\n    while (tail->next)\n      tail = tail->next;\n\n    return {dummy.next, tail};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/148.html",
    "category": "Algorithms",
    "acceptance_rate": 61.478385116923505,
    "topics": [
      "Linked List",
      "Two Pointers",
      "Divide and Conquer",
      "Sorting",
      "Merge Sort"
    ],
    "hints": [],
    "likes": 12280,
    "dislikes": 387,
    "similar_questions": "[{\"title\": \"Merge Two Sorted Lists\", \"titleSlug\": \"merge-two-sorted-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sort Colors\", \"titleSlug\": \"sort-colors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insertion Sort List\", \"titleSlug\": \"insertion-sort-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Linked List Already Sorted Using Absolute Values\", \"titleSlug\": \"sort-linked-list-already-sorted-using-absolute-values\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1022298, \"totalSubmissionRaw\": 1662864, \"acRate\": \"61.5%\"}",
    "title_pt": "Ordenar Lista Encadeada",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada, retorne <em>a lista após ordená-la em <strong>ordem crescente</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg\" style=\"width: 450px; height: 194px;\" />\n<pre>\n<strong>Entrada:</strong> head = [4,2,1,3]\n<strong>Saída:</strong> [1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/14/sort_list_2.jpg\" style=\"width: 550px; height: 184px;\" />\n<pre>\n<strong>Entrada:</strong> head = [-1,5,3,4,0]\n<strong>Saída:</strong> [-1,0,3,4,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue ordenar a lista encadeada em tempo <code>O(n logn)</code> e memória <code>O(1)</code> (isto é, espaço constante)?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "149",
    "paidOnly": false,
    "title": "Max Points on a Line",
    "titleSlug": "max-points-on-a-line",
    "url": "https://leetcode.com/problems/max-points-on-a-line",
    "description_url": "https://leetcode.com/problems/max-points-on-a-line/description/",
    "description": "<p>Given an array of <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents a point on the <strong>X-Y</strong> plane, return <em>the maximum number of points that lie on the same straight line</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Input:</strong> points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 300</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>All the <code>points</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/max-points-on-a-line/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxPoints(self, points: List[List[int]]) -> int:\n    ans = 0\n\n    def gcd(a: int, b: int) -> int:\n      return a if b == 0 else gcd(b, a % b)\n\n    def getSlope(p: List[int], q: List[int]) -> Tuple[int, int]:\n      dx = p[0] - q[0]\n      dy = p[1] - q[1]\n      if dx == 0:\n        return (0, p[0])\n      if dy == 0:\n        return (p[1], 0)\n      d = gcd(dx, dy)\n      return (dx // d, dy // d)\n\n    for i, p in enumerate(points):\n      slopeCount = defaultdict(int)\n      samePoints = 1\n      maxPoints = 0\n      for j in range(i + 1, len(points)):\n        q = points[j]\n        if p == q:\n          samePoints += 1\n        else:\n          slope = getSlope(p, q)\n          slopeCount[slope] += 1\n          maxPoints = max(maxPoints, slopeCount[slope])\n      ans = max(ans, samePoints + maxPoints)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxPoints(int[][] points) {\n    int ans = 0;\n\n    for (int i = 0; i < points.length; ++i) {\n      Map<Pair<Integer, Integer>, Integer> slopeCount = new HashMap<>();\n      int[] p1 = points[i];\n      int samePoints = 1;\n      int maxPoints = 0; // Maximum number of points with the same slope\n      for (int j = i + 1; j < points.length; ++j) {\n        int[] p2 = points[j];\n        if (p1[0] == p2[0] && p1[1] == p2[1])\n          ++samePoints;\n        else {\n          Pair<Integer, Integer> slope = getSlope(p1, p2);\n          slopeCount.merge(slope, 1, Integer::sum);\n          maxPoints = Math.max(maxPoints, slopeCount.get(slope));\n        }\n      }\n      ans = Math.max(ans, samePoints + maxPoints);\n    }\n\n    return ans;\n  }\n\n  private Pair<Integer, Integer> getSlope(int[] p, int[] q) {\n    final int dx = p[0] - q[0];\n    final int dy = p[1] - q[1];\n    if (dx == 0)\n      return new Pair<>(0, p[0]);\n    if (dy == 0)\n      return new Pair<>(p[1], 0);\n    final int d = gcd(dx, dy);\n    return new Pair<>(dx / d, dy / y);\n  }\n\n  private int gcd(int a, int b) {\n    return b == 0 ? a : gcd(b, a % b);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxPoints(vector<vector<int>>& points) {\n    int ans = 0;\n\n    for (int i = 0; i < points.size(); ++i) {\n      unordered_map<pair<int, int>, int, pairHash> slopeCount;\n      const vector<int> p1{points[i]};\n      int samePoints = 1;\n      int maxPoints = 0;  // Maximum number of points with the same slope\n      for (int j = i + 1; j < points.size(); ++j) {\n        const vector<int> p2{points[j]};\n        if (p1 == p2)\n          ++samePoints;\n        else\n          maxPoints = max(maxPoints, ++slopeCount[getSlope(p1, p2)]);\n      }\n      ans = max(ans, samePoints + maxPoints);\n    }\n\n    return ans;\n  }\n\n private:\n  pair<int, int> getSlope(const vector<int>& p, const vector<int>& q) {\n    const int dx = p[0] - q[0];\n    const int dy = p[1] - q[1];\n    if (dx == 0)\n      return {0, p[0]};\n    if (dy == 0)\n      return {p[1], 0};\n    const int d = __gcd(dx, dy);\n    return {dx / d, dy / d};\n  }\n\n  struct pairHash {\n    size_t operator()(const pair<int, int>& p) const {\n      return p.first ^ p.second;\n    }\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/149.html",
    "category": "Algorithms",
    "acceptance_rate": 28.793874601993007,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Geometry"
    ],
    "hints": [],
    "likes": 4346,
    "dislikes": 544,
    "similar_questions": "[{\"title\": \"Line Reflection\", \"titleSlug\": \"line-reflection\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Lines to Cover Points\", \"titleSlug\": \"minimum-number-of-lines-to-cover-points\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Lines to Represent a Line Chart\", \"titleSlug\": \"minimum-lines-to-represent-a-line-chart\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Special Subsequences\", \"titleSlug\": \"count-special-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"460.3K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 460296, \"totalSubmissionRaw\": 1598590, \"acRate\": \"28.8%\"}",
    "title_pt": "Máximo de Pontos em uma Reta",
    "description_pt": "<p>Dado um array de <code>points</code> em que <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> representa um ponto no plano <strong>X-Y</strong>, retorne <em>o número máximo de pontos que ficam na mesma reta</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Entrada:</strong> points = [[1,1],[2,2],[3,3]]\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Entrada:</strong> points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 300</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os <code>points</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "150",
    "paidOnly": false,
    "title": "Evaluate Reverse Polish Notation",
    "titleSlug": "evaluate-reverse-polish-notation",
    "url": "https://leetcode.com/problems/evaluate-reverse-polish-notation",
    "description_url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/description/",
    "description": "<p>You are given an array of strings <code>tokens</code> that represents an arithmetic expression in a <a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\" target=\"_blank\">Reverse Polish Notation</a>.</p>\n\n<p>Evaluate the expression. Return <em>an integer that represents the value of the expression</em>.</p>\n\n<p><strong>Note</strong> that:</p>\n\n<ul>\n\t<li>The valid operators are <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;*&#39;</code>, and <code>&#39;/&#39;</code>.</li>\n\t<li>Each operand may be an integer or another expression.</li>\n\t<li>The division between two integers always <strong>truncates toward zero</strong>.</li>\n\t<li>There will not be any division by zero.</li>\n\t<li>The input represents a valid arithmetic expression in a reverse polish notation.</li>\n\t<li>The answer and all the intermediate calculations can be represented in a <strong>32-bit</strong> integer.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> tokens = [&quot;2&quot;,&quot;1&quot;,&quot;+&quot;,&quot;3&quot;,&quot;*&quot;]\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> ((2 + 1) * 3) = 9\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> tokens = [&quot;4&quot;,&quot;13&quot;,&quot;5&quot;,&quot;/&quot;,&quot;+&quot;]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> (4 + (13 / 5)) = 6\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> tokens = [&quot;10&quot;,&quot;6&quot;,&quot;9&quot;,&quot;3&quot;,&quot;+&quot;,&quot;-11&quot;,&quot;*&quot;,&quot;/&quot;,&quot;*&quot;,&quot;17&quot;,&quot;+&quot;,&quot;5&quot;,&quot;+&quot;]\n<strong>Output:</strong> 22\n<strong>Explanation:</strong> ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tokens.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>tokens[i]</code> is either an operator: <code>&quot;+&quot;</code>, <code>&quot;-&quot;</code>, <code>&quot;*&quot;</code>, or <code>&quot;/&quot;</code>, or an integer in the range <code>[-200, 200]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/evaluate-reverse-polish-notation/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def evalRPN(self, tokens: List[str]) -> int:\n    stack = []\n    operators = {\n        '+': lambda a, b: a + b,\n        '-': lambda a, b: a - b,\n        '*': lambda a, b: a * b,\n        '/': lambda a, b: int(a / b),\n    }\n\n    for token in tokens:\n      if token in operators:\n        b = stack.pop()\n        a = stack.pop()\n        stack.append(operators[token](a, b))\n      else:\n        stack.append(int(token))\n\n    return stack[0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int evalRPN(String[] tokens) {\n    Deque<Integer> stack = new ArrayDeque<>();\n\n    for (final String token : tokens)\n      switch (token) {\n        case \"+\":\n          stack.push(stack.pop() + stack.pop());\n          break;\n        case \"-\":\n          stack.push(-stack.pop() + stack.pop());\n          break;\n        case \"*\":\n          stack.push(stack.pop() * stack.pop());\n          break;\n        case \"/\":\n          final int b = stack.pop();\n          final int a = stack.pop();\n          stack.push(a / b);\n          break;\n        default:\n          stack.push(Integer.parseInt(token));\n      }\n\n    return stack.peek();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int evalRPN(vector<string>& tokens) {\n    stack<int> stack;\n    const unordered_map<string, function<int(int, int)>> op{\n        {\"+\", plus<int>()},\n        {\"-\", minus<int>()},\n        {\"*\", multiplies<int>()},\n        {\"/\", divides<int>()}};\n\n    for (const string& token : tokens)\n      if (op.count(token)) {\n        const int b = stack.top();\n        stack.pop();\n        const int a = stack.top();\n        stack.pop();\n        stack.push(op.at(token)(a, b));\n      } else {\n        stack.push(stoi(token));\n      }\n\n    return stack.top();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/150.html",
    "category": "Algorithms",
    "acceptance_rate": 54.658226687945934,
    "topics": [
      "Array",
      "Math",
      "Stack"
    ],
    "hints": [],
    "likes": 8100,
    "dislikes": 1140,
    "similar_questions": "[{\"title\": \"Basic Calculator\", \"titleSlug\": \"basic-calculator\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Expression Add Operators\", \"titleSlug\": \"expression-add-operators\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1371621, \"totalSubmissionRaw\": 2509459, \"acRate\": \"54.7%\"}",
    "title_pt": "Avaliar Notação Polonesa Reversa",
    "description_pt": "<p>Você recebe um array de strings <code>tokens</code> que representa uma expressão aritmética em <a href=\"http://en.wikipedia.org/wiki/Reverse_Polish_notation\" target=\"_blank\">notação polonesa reversa</a>.</p>\n\n<p>Avalie a expressão. Retorne <em>um inteiro que representa o valor da expressão</em>.</p>\n\n<p><strong>Observe</strong> que:</p>\n\n<ul>\n\t<li>Os operadores válidos são <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;*&#39;</code> e <code>&#39;/&#39;</code>.</li>\n\t<li>Cada operando pode ser um inteiro ou outra expressão.</li>\n\t<li>A divisão entre dois inteiros sempre <strong>trunca em direção a zero</strong>.</li>\n\t<li>Não haverá nenhuma divisão por zero.</li>\n\t<li>A entrada representa uma expressão aritmética válida em notação polonesa reversa.</li>\n\t<li>A resposta e todos os cálculos intermediários podem ser representados em um inteiro de <strong>32 bits</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> tokens = [&quot;2&quot;,&quot;1&quot;,&quot;+&quot;,&quot;3&quot;,&quot;*&quot;]\n<strong>Saída:</strong> 9\n<strong>Explicação:</strong> ((2 + 1) * 3) = 9\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> tokens = [&quot;4&quot;,&quot;13&quot;,&quot;5&quot;,&quot;/&quot;,&quot;+&quot;]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> (4 + (13 / 5)) = 6\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> tokens = [&quot;10&quot;,&quot;6&quot;,&quot;9&quot;,&quot;3&quot;,&quot;+&quot;,&quot;-11&quot;,&quot;*&quot;,&quot;/&quot;,&quot;*&quot;,&quot;17&quot;,&quot;+&quot;,&quot;5&quot;,&quot;+&quot;]\n<strong>Saída:</strong> 22\n<strong>Explicação:</strong> ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tokens.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>tokens[i]</code> é ou um operador: <code>&quot;+&quot;</code>, <code>&quot;-&quot;</code>, <code>&quot;*&quot;</code> ou <code>&quot;/&quot;</code>, ou um inteiro no intervalo <code>[-200, 200]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "151",
    "paidOnly": false,
    "title": "Reverse Words in a String",
    "titleSlug": "reverse-words-in-a-string",
    "url": "https://leetcode.com/problems/reverse-words-in-a-string",
    "description_url": "https://leetcode.com/problems/reverse-words-in-a-string/description/",
    "description": "<p>Given an input string <code>s</code>, reverse the order of the <strong>words</strong>.</p>\n\n<p>A <strong>word</strong> is defined as a sequence of non-space characters. The <strong>words</strong> in <code>s</code> will be separated by at least one space.</p>\n\n<p>Return <em>a string of the words in reverse order concatenated by a single space.</em></p>\n\n<p><b>Note</b> that <code>s</code> may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;the sky is blue&quot;\n<strong>Output:</strong> &quot;blue is sky the&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;  hello world  &quot;\n<strong>Output:</strong> &quot;world hello&quot;\n<strong>Explanation:</strong> Your reversed string should not contain leading or trailing spaces.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a good   example&quot;\n<strong>Output:</strong> &quot;example good a&quot;\n<strong>Explanation:</strong> You need to reduce multiple spaces between two words to a single space in the reversed string.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> contains English letters (upper-case and lower-case), digits, and spaces <code>&#39; &#39;</code>.</li>\n\t<li>There is <strong>at least one</strong> word in <code>s</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b data-stringify-type=\"bold\">Follow-up:&nbsp;</b>If the string data type is mutable in your language, can&nbsp;you solve it&nbsp;<b data-stringify-type=\"bold\">in-place</b>&nbsp;with&nbsp;<code data-stringify-type=\"code\">O(1)</code>&nbsp;extra space?</p>\n",
    "solution_url": "https://leetcode.com/problems/reverse-words-in-a-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseWords(self, s: str) -> str:\n    return ' '.join(reversed(s.split()))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String reverseWords(String s) {\n    StringBuilder sb = new StringBuilder(s).reverse(); // Reverse the whole string\n    reverseWords(sb, sb.length());                     // Reverse each word\n    return cleanSpaces(sb, sb.length());               // Clean up spaces\n  }\n\n  private void reverseWords(StringBuilder sb, int n) {\n    int i = 0;\n    int j = 0;\n\n    while (i < n) {\n      while (i < j || i < n && sb.charAt(i) == ' ') // Skip spaces\n        ++i;\n      while (j < i || j < n && sb.charAt(j) != ' ') // Skip non spaces\n        ++j;\n      reverse(sb, i, j - 1); // Reverse the word\n    }\n  }\n\n  // Trim leading, trailing, and middle spaces\n  private String cleanSpaces(StringBuilder sb, int n) {\n    int i = 0;\n    int j = 0;\n\n    while (j < n) {\n      while (j < n && sb.charAt(j) == ' ') // Skip spaces\n        ++j;\n      while (j < n && sb.charAt(j) != ' ') // Keep non spaces\n        sb.setCharAt(i++, sb.charAt(j++));\n      while (j < n && sb.charAt(j) == ' ') // Skip spaces\n        ++j;\n      if (j < n) // Keep only one space\n        sb.setCharAt(i++, ' ');\n    }\n\n    return sb.substring(0, i).toString();\n  }\n\n  private void reverse(StringBuilder sb, int l, int r) {\n    while (l < r) {\n      final char temp = sb.charAt(l);\n      sb.setCharAt(l++, sb.charAt(r));\n      sb.setCharAt(r--, temp);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string reverseWords(string s) {\n    reverse(begin(s), end(s));          // Reverse the whole string\n    reverseWords(s, s.length());        // Reverse each word\n    return cleanSpaces(s, s.length());  // Clean up spaces\n  }\n\n private:\n  void reverseWords(string& s, int n) {\n    int i = 0;\n    int j = 0;\n\n    while (i < n) {\n      while (i < j || i < n && s[i] == ' ')  // Skip spaces\n        ++i;\n      while (j < i || j < n && s[j] != ' ')  // Skip non spaces\n        ++j;\n      reverse(begin(s) + i, begin(s) + j);  // Reverse the word\n    }\n  }\n\n  // Trim leading, trailing, and middle spaces\n  string cleanSpaces(string& s, int n) {\n    int i = 0;\n    int j = 0;\n\n    while (j < n) {\n      while (j < n && s[j] == ' ')  // Skip spaces\n        ++j;\n      while (j < n && s[j] != ' ')  // Keep non spaces\n        s[i++] = s[j++];\n      while (j < n && s[j] == ' ')  // Skip spaces\n        ++j;\n      if (j < n)  // Keep only one space\n        s[i++] = ' ';\n    }\n\n    return s.substr(0, i);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/151.html",
    "category": "Algorithms",
    "acceptance_rate": 51.34901101493177,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 9394,
    "dislikes": 5356,
    "similar_questions": "[{\"title\": \"Reverse Words in a String II\", \"titleSlug\": \"reverse-words-in-a-string-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"4.5M\", \"totalAcceptedRaw\": 2316240, \"totalSubmissionRaw\": 4510782, \"acRate\": \"51.3%\"}",
    "title_pt": "Inverter Palavras em uma String",
    "description_pt": "<p>Dada uma string de entrada <code>s</code>, inverta a ordem das <strong>palavras</strong>.</p>\n\n<p>Uma <strong>palavra</strong> é definida como uma sequência de caracteres que não são espaços. As <strong>palavras</strong> em <code>s</code> serão separadas por pelo menos um espaço.</p>\n\n<p>Retorne <em>uma string das palavras em ordem inversa concatenadas por um único espaço.</em></p>\n\n<p><b>Nota</b> que <code>s</code> pode conter espaços no início ou no fim, ou múltiplos espaços entre duas palavras. A string retornada deve conter apenas um único espaço separando as palavras. Não inclua espaços extras.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;the sky is blue&quot;\n<strong>Saída:</strong> &quot;blue is sky the&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;  hello world  &quot;\n<strong>Saída:</strong> &quot;world hello&quot;\n<strong>Explicação:</strong> Sua string invertida não deve conter espaços no início ou no fim.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a good   example&quot;\n<strong>Saída:</strong> &quot;example good a&quot;\n<strong>Explicação:</strong> Você precisa reduzir múltiplos espaços entre duas palavras para um único espaço na string invertida.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> contém letras inglesas (maiúsculas e minúsculas), dígitos e espaços <code>&#39; &#39;</code>.</li>\n\t<li>Há <strong>pelo menos uma</strong> palavra em <code>s</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b data-stringify-type=\"bold\">Desafio extra:&nbsp;</b>Se o tipo de dado string for mutável na sua linguagem, você consegue resolvê-lo <b data-stringify-type=\"bold\">in-place</b> com <code data-stringify-type=\"code\">O(1)</code> de espaço extra?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "152",
    "paidOnly": false,
    "title": "Maximum Product Subarray",
    "titleSlug": "maximum-product-subarray",
    "url": "https://leetcode.com/problems/maximum-product-subarray",
    "description_url": "https://leetcode.com/problems/maximum-product-subarray/description/",
    "description": "<p>Given an integer array <code>nums</code>, find a <span data-keyword=\"subarray-nonempty\">subarray</span> that has the largest product, and return <em>the product</em>.</p>\n\n<p>The test cases are generated so that the answer will fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,-2,4]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> [2,3] has the largest product 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-2,0,-1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The result cannot be 2, because [-2,-1] is not a subarray.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>The product of any subarray of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-product-subarray/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProduct(self, nums: List[int]) -> int:\n    ans = nums[0]\n    prevMin = nums[0]\n    prevMax = nums[0]\n\n    for i in range(1, len(nums)):\n      mini = prevMin * nums[i]\n      maxi = prevMax * nums[i]\n      prevMin = min(nums[i], mini, maxi)\n      prevMax = max(nums[i], mini, maxi)\n      ans = max(ans, prevMax)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProduct(int[] nums) {\n    int ans = nums[0];\n    int dpMin = nums[0]; // Min so far\n    int dpMax = nums[0]; // Max so far\n\n    for (int i = 1; i < nums.length; ++i) {\n      final int num = nums[i];\n      final int prevMin = dpMin; // dpMin[i - 1]\n      final int prevMax = dpMax; // dpMax[i - 1]\n      if (num < 0) {\n        dpMin = Math.min(prevMax * num, num);\n        dpMax = Math.max(prevMin * num, num);\n      } else {\n        dpMin = Math.min(prevMin * num, num);\n        dpMax = Math.max(prevMax * num, num);\n      }\n      ans = Math.max(ans, dpMax);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProduct(vector<int>& nums) {\n    int ans = nums[0];\n    int dpMin = nums[0];  // Min so far\n    int dpMax = nums[0];  // Max so far\n\n    for (int i = 1; i < nums.size(); ++i) {\n      const int num = nums[i];\n      const int prevMin = dpMin;  // dpMin[i - 1]\n      const int prevMax = dpMax;  // dpMax[i - 1]\n      if (num < 0) {\n        dpMin = min(prevMax * num, num);\n        dpMax = max(prevMin * num, num);\n      } else {\n        dpMin = min(prevMin * num, num);\n        dpMax = max(prevMax * num, num);\n      }\n      ans = max(ans, dpMax);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/152.html",
    "category": "Algorithms",
    "acceptance_rate": 34.795055226933115,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 19344,
    "dislikes": 783,
    "similar_questions": "[{\"title\": \"Maximum Subarray\", \"titleSlug\": \"maximum-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber\", \"titleSlug\": \"house-robber\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product of Array Except Self\", \"titleSlug\": \"product-of-array-except-self\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Product of Three Numbers\", \"titleSlug\": \"maximum-product-of-three-numbers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Subarray Product Less Than K\", \"titleSlug\": \"subarray-product-less-than-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"4.6M\", \"totalAcceptedRaw\": 1616928, \"totalSubmissionRaw\": 4647004, \"acRate\": \"34.8%\"}",
    "title_pt": "Subarray de Produto Máximo",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, encontre um <span data-keyword=\"subarray-nonempty\">subarray</span> que tenha o maior produto e retorne <em>o produto</em>.</p>\n\n<p>Os casos de teste são gerados de modo que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,-2,4]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> [2,3] tem o maior produto, 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-2,0,-1]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> O resultado não pode ser 2, porque [-2,-1] não é um subarray.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>\n\t<li>O produto de qualquer subarray de <code>nums</code> é <strong>garantido</strong> caber em um inteiro de <strong>32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "153",
    "paidOnly": false,
    "title": "Find Minimum in Rotated Sorted Array",
    "titleSlug": "find-minimum-in-rotated-sorted-array",
    "url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array",
    "description_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/",
    "description": "<p>Suppose an array of length <code>n</code> sorted in ascending order is <strong>rotated</strong> between <code>1</code> and <code>n</code> times. For example, the array <code>nums = [0,1,2,4,5,6,7]</code> might become:</p>\n\n<ul>\n\t<li><code>[4,5,6,7,0,1,2]</code> if it was rotated <code>4</code> times.</li>\n\t<li><code>[0,1,2,4,5,6,7]</code> if it was rotated <code>7</code> times.</li>\n</ul>\n\n<p>Notice that <strong>rotating</strong> an array <code>[a[0], a[1], a[2], ..., a[n-1]]</code> 1 time results in the array <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code>.</p>\n\n<p>Given the sorted rotated array <code>nums</code> of <strong>unique</strong> elements, return <em>the minimum element of this array</em>.</p>\n\n<p>You must write an algorithm that runs in&nbsp;<code>O(log n) time</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,4,5,1,2]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The original array was [1,2,3,4,5] rotated 3 times.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,5,6,7,0,1,2]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [11,13,15,17]\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> The original array was [11,13,15,17] and it was rotated 4 times. \n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>-5000 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li>All the integers of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is sorted and rotated between <code>1</code> and <code>n</code> times.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMin(self, nums: List[int]) -> int:\n    l = 0\n    r = len(nums) - 1\n\n    while l < r:\n      m = (l + r) // 2\n      if nums[m] < nums[r]:\n        r = m\n      else:\n        l = m + 1\n\n    return nums[l]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMin(int[] nums) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (nums[m] < nums[r])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return nums[l];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMin(vector<int>& nums) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (nums[m] < nums[r])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return nums[l];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/153.html",
    "category": "Algorithms",
    "acceptance_rate": 52.48146439245402,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [
      "Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2].",
      "You can divide the search space into two and see which direction to go.\r\nCan you think of an algorithm which has O(logN) search complexity?",
      "<ol>\r\n<li>All the elements to the left of inflection point > first element of the array.</li>\r\n<li>All the elements to the right of inflection point < first element of the array.</li>\r\n<ol>"
    ],
    "likes": 14163,
    "dislikes": 621,
    "similar_questions": "[{\"title\": \"Search in Rotated Sorted Array\", \"titleSlug\": \"search-in-rotated-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum in Rotated Sorted Array II\", \"titleSlug\": \"find-minimum-in-rotated-sorted-array-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.4M\", \"totalSubmission\": \"4.6M\", \"totalAcceptedRaw\": 2394291, \"totalSubmissionRaw\": 4562165, \"acRate\": \"52.5%\"}",
    "title_pt": "Encontrar o Mínimo em um Array Ordenado Rotacionado",
    "description_pt": "<p>Suponha que um array de comprimento <code>n</code> ordenado em ordem crescente seja <strong>rotacionado</strong> entre <code>1</code> e <code>n</code> vezes. Por exemplo, o array <code>nums = [0,1,2,4,5,6,7]</code> pode se tornar:</p>\n\n<ul>\n\t<li><code>[4,5,6,7,0,1,2]</code> se foi rotacionado <code>4</code> vezes.</li>\n\t<li><code>[0,1,2,4,5,6,7]</code> se foi rotacionado <code>7</code> vezes.</li>\n</ul>\n\n<p>Observe que <strong>rotacionar</strong> um array <code>[a[0], a[1], a[2], ..., a[n-1]]</code> 1 vez resulta no array <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code>.</p>\n\n<p>Dado o array ordenado rotacionado <code>nums</code> de elementos <strong>únicos</strong>, retorne <em>o elemento mínimo deste array</em>.</p>\n\n<p>Você deve escrever um algoritmo que execute em&nbsp;<code>O(log n) time</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,4,5,1,2]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> O array original era [1,2,3,4,5] rotacionado 3 vezes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,5,6,7,0,1,2]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> O array original era [0,1,2,4,5,6,7] e foi rotacionado 4 vezes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [11,13,15,17]\n<strong>Saída:</strong> 11\n<strong>Explicação:</strong> O array original era [11,13,15,17] e foi rotacionado 4 vezes. \n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>-5000 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li>Todos os inteiros de <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li><code>nums</code> é ordenado e rotacionado entre <code>1</code> e <code>n</code> vezes.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: O array era originalmente em ordem crescente. Agora que o array foi rotacionado, haveria um ponto no array onde existe uma pequena deflexão em relação à sequência crescente. por exemplo, o array seria algo como [4, 5, 6, 7, 0, 1, 2].",
      "- Dica 2: Você pode dividir o espaço de busca em duas partes e ver para qual direção ir.\nConsegue pensar em um algoritmo que tenha complexidade de busca O(logN)?",
      "- Dica 3: <ol>\n<li>Todos os elementos à esquerda do ponto de inflexão > primeiro elemento do array.</li>\n<li>Todos os elementos à direita do ponto de inflexão < primeiro elemento do array.</li>\n<ol>"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "154",
    "paidOnly": false,
    "title": "Find Minimum in Rotated Sorted Array II",
    "titleSlug": "find-minimum-in-rotated-sorted-array-ii",
    "url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii",
    "description_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/",
    "description": "<p>Suppose an array of length <code>n</code> sorted in ascending order is <strong>rotated</strong> between <code>1</code> and <code>n</code> times. For example, the array <code>nums = [0,1,4,4,5,6,7]</code> might become:</p>\n\n<ul>\n\t<li><code>[4,5,6,7,0,1,4]</code> if it was rotated <code>4</code> times.</li>\n\t<li><code>[0,1,4,4,5,6,7]</code> if it was rotated <code>7</code> times.</li>\n</ul>\n\n<p>Notice that <strong>rotating</strong> an array <code>[a[0], a[1], a[2], ..., a[n-1]]</code> 1 time results in the array <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code>.</p>\n\n<p>Given the sorted rotated array <code>nums</code> that may contain <strong>duplicates</strong>, return <em>the minimum element of this array</em>.</p>\n\n<p>You must decrease the overall operation steps as much as possible.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,3,5]\n<strong>Output:</strong> 1\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [2,2,2,0,1]\n<strong>Output:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>-5000 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li><code>nums</code> is sorted and rotated between <code>1</code> and <code>n</code> times.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> This problem is similar to&nbsp;<a href=\"https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/\" target=\"_blank\">Find Minimum in Rotated Sorted Array</a>, but&nbsp;<code>nums</code> may contain <strong>duplicates</strong>. Would this affect the runtime complexity? How and why?</p>\n\n<p>&nbsp;</p>\n",
    "solution_url": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMin(self, nums: List[int]) -> int:\n    l = 0\n    r = len(nums) - 1\n\n    while l < r:\n      m = (l + r) // 2\n      if nums[m] == nums[r]:\n        r -= 1\n      elif nums[m] < nums[r]:\n        r = m\n      else:\n        l = m + 1\n\n    return nums[l]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMin(int[] nums) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (nums[m] == nums[r])\n        --r;\n      else if (nums[m] < nums[r])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return nums[l];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMin(vector<int>& nums) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (nums[m] == nums[r])\n        --r;\n      else if (nums[m] < nums[r])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return nums[l];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/154.html",
    "category": "Algorithms",
    "acceptance_rate": 44.08704363088427,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 4865,
    "dislikes": 505,
    "similar_questions": "[{\"title\": \"Find Minimum in Rotated Sorted Array\", \"titleSlug\": \"find-minimum-in-rotated-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"525.5K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 525475, \"totalSubmissionRaw\": 1191902, \"acRate\": \"44.1%\"}",
    "title_pt": "Encontrar o Mínimo em um Array Ordenado Rotacionado II",
    "description_pt": "<p>Suponha que um array de comprimento <code>n</code> ordenado em ordem crescente seja <strong>rotacionado</strong> entre <code>1</code> e <code>n</code> vezes. Por exemplo, o array <code>nums = [0,1,4,4,5,6,7]</code> pode se tornar:</p>\n\n<ul>\n\t<li><code>[4,5,6,7,0,1,4]</code> se tivesse sido rotacionado <code>4</code> vezes.</li>\n\t<li><code>[0,1,4,4,5,6,7]</code> se tivesse sido rotacionado <code>7</code> vezes.</li>\n</ul>\n\n<p>Observe que <strong>rotacionar</strong> um array <code>[a[0], a[1], a[2], ..., a[n-1]]</code> 1 vez resulta no array <code>[a[n-1], a[0], a[1], a[2], ..., a[n-2]]</code>.</p>\n\n<p>Dado o array ordenado rotacionado <code>nums</code>, que pode conter <strong>duplicatas</strong>, retorne <em>o menor elemento deste array</em>.</p>\n\n<p>Você deve reduzir ao máximo possível a quantidade total de passos da operação.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,3,5]\n<strong>Saída:</strong> 1\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [2,2,2,0,1]\n<strong>Saída:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>-5000 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li><code>nums</code> é ordenado e rotacionado entre <code>1</code> e <code>n</code> vezes.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Este problema é semelhante a&nbsp;<a href=\"https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/\" target=\"_blank\">Encontrar o Mínimo em um Array Ordenado Rotacionado</a>, mas&nbsp;<code>nums</code> pode conter <strong>duplicatas</strong>. Isso afetaria a complexidade de tempo de execução? Como e por quê?</p>\n\n<p>&nbsp;</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "155",
    "paidOnly": false,
    "title": "Min Stack",
    "titleSlug": "min-stack",
    "url": "https://leetcode.com/problems/min-stack",
    "description_url": "https://leetcode.com/problems/min-stack/description/",
    "description": "<p>Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p>\n\n<p>Implement the <code>MinStack</code> class:</p>\n\n<ul>\n\t<li><code>MinStack()</code> initializes the stack object.</li>\n\t<li><code>void push(int val)</code> pushes the element <code>val</code> onto the stack.</li>\n\t<li><code>void pop()</code> removes the element on the top of the stack.</li>\n\t<li><code>int top()</code> gets the top element of the stack.</li>\n\t<li><code>int getMin()</code> retrieves the minimum element in the stack.</li>\n</ul>\n\n<p>You must implement a solution with <code>O(1)</code> time complexity for each function.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]\n[[],[-2],[0],[-3],[],[],[],[]]\n\n<strong>Output</strong>\n[null,null,null,null,-3,null,0,-2]\n\n<strong>Explanation</strong>\nMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top();    // return 0\nminStack.getMin(); // return -2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Methods <code>pop</code>, <code>top</code> and <code>getMin</code> operations will always be called on <strong>non-empty</strong> stacks.</li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>getMin</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/min-stack/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass MinStack:\n  def __init__(self):\n    self.stack = []\n\n  def push(self, x: int) -> None:\n    mini = x if not self.stack else min(self.stack[-1][1], x)\n    self.stack.append([x, mini])\n\n  def pop(self) -> None:\n    self.stack.pop()\n\n  def top(self) -> int:\n    return self.stack[-1][0]\n\n  def getMin(self) -> int:\n    return self.stack[-1][1]",
    "solution_code_java": "\t\t\t\n\nclass MinStack {\n  public void push(int x) {\n    if (stack.isEmpty())\n      stack.push(new int[] {x, x});\n    else\n      stack.push(new int[] {x, Math.min(x, stack.peek()[1])});\n  }\n\n  public void pop() {\n    stack.pop();\n  }\n\n  public int top() {\n    return stack.peek()[0];\n  }\n\n  public int getMin() {\n    return stack.peek()[1];\n  }\n\n  private Stack<int[]> stack = new Stack<>(); // {x, min}\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MinStack {\n public:\n  void push(int x) {\n    if (stack.empty())\n      stack.emplace(x, x);\n    else\n      stack.emplace(x, min(x, stack.top().second));\n  }\n\n  void pop() {\n    stack.pop();\n  }\n\n  int top() {\n    return stack.top().first;\n  }\n\n  int getMin() {\n    return stack.top().second;\n  }\n\n private:\n  stack<pair<int, int>> stack;  // {x, min}\n};",
    "solution_code_url": "https://leetcodehelp.github.io/155.html",
    "category": "Algorithms",
    "acceptance_rate": 56.258468610204595,
    "topics": [
      "Stack",
      "Design"
    ],
    "hints": [
      "Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)"
    ],
    "likes": 15031,
    "dislikes": 946,
    "similar_questions": "[{\"title\": \"Sliding Window Maximum\", \"titleSlug\": \"sliding-window-maximum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Max Stack\", \"titleSlug\": \"max-stack\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.2M\", \"totalSubmission\": \"3.8M\", \"totalAcceptedRaw\": 2164843, \"totalSubmissionRaw\": 3848027, \"acRate\": \"56.3%\"}",
    "title_pt": "Pilha com Mínimo",
    "description_pt": "<p>Projete uma pilha que suporte push, pop, top e a recuperação do elemento mínimo em tempo constante.</p>\n\n<p>Implemente a classe <code>MinStack</code>:</p>\n\n<ul>\n\t<li><code>MinStack()</code> inicializa o objeto da pilha.</li>\n\t<li><code>void push(int val)</code> empilha o elemento <code>val</code> na pilha.</li>\n\t<li><code>void pop()</code> remove o elemento do topo da pilha.</li>\n\t<li><code>int top()</code> obtém o elemento do topo da pilha.</li>\n\t<li><code>int getMin()</code> recupera o elemento mínimo na pilha.</li>\n</ul>\n\n<p>Você deve implementar uma solução com complexidade de tempo <code>O(1)</code> para cada função.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]\n[[],[-2],[0],[-3],[],[],[],[]]\n\n<strong>Saída</strong>\n[null,null,null,null,-3,null,0,-2]\n\n<strong>Explicação</strong>\nMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top();    // return 0\nminStack.getMin(); // return -2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>As operações dos métodos <code>pop</code>, <code>top</code> e <code>getMin</code> sempre serão chamadas em pilhas <strong>não vazias</strong>.</li>\n\t<li>No máximo <code>3 * 10<sup>4</sup></code> chamadas serão feitas a <code>push</code>, <code>pop</code>, <code>top</code> e <code>getMin</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Considere cada nó na pilha tendo um valor mínimo. (Créditos para @aakarshmadhavan)"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "160",
    "paidOnly": false,
    "title": "Intersection of Two Linked Lists",
    "titleSlug": "intersection-of-two-linked-lists",
    "url": "https://leetcode.com/problems/intersection-of-two-linked-lists",
    "description_url": "https://leetcode.com/problems/intersection-of-two-linked-lists/description/",
    "description": "<p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p>\n\n<p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_statement.png\" style=\"width: 500px; height: 162px;\" />\n<p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p>\n\n<p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p>\n\n<p><strong>Custom Judge:</strong></p>\n\n<p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p>\n\n<ul>\n\t<li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li>\n\t<li><code>listA</code> - The first linked list.</li>\n\t<li><code>listB</code> - The second linked list.</li>\n\t<li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li>\n\t<li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li>\n</ul>\n\n<p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code> to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png\" style=\"width: 500px; height: 162px;\" />\n<pre>\n<strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\n<strong>Output:</strong> Intersected at &#39;8&#39;\n<strong>Explanation:</strong> The intersected node&#39;s value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node&#39;s value is not 1 because the nodes with value 1 in A and B (2<sup>nd</sup> node in A and 3<sup>rd</sup> node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3<sup>rd</sup> node in A and 4<sup>th</sup> node in B) point to the same location in memory.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png\" style=\"width: 500px; height: 194px;\" />\n<pre>\n<strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n<strong>Output:</strong> Intersected at &#39;2&#39;\n<strong>Explanation:</strong> The intersected node&#39;s value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png\" style=\"width: 300px; height: 189px;\" />\n<pre>\n<strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n<strong>Output:</strong> No intersection\n<strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li>\n\t<li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= skipA &lt;= m</code></li>\n\t<li><code>0 &lt;= skipB &lt;= n</code></li>\n\t<li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li>\n\t<li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?",
    "solution_url": "https://leetcode.com/problems/intersection-of-two-linked-lists/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n    a = headA\n    b = headB\n\n    while a != b:\n      a = a.next if a else headB\n      b = b.next if b else headA\n\n    return a",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  public ListNode getIntersectionNode(ListNode headA, ListNode headB) {\n    ListNode a = headA;\n    ListNode b = headB;\n\n    while (a != b) {\n      a = a == null ? headB : a.next;\n      b = b == null ? headA : b.next;\n    }\n\n    return a;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {\n    ListNode* a = headA;\n    ListNode* b = headB;\n\n    while (a != b) {\n      a = a ? a->next : headB;\n      b = b ? b->next : headA;\n    }\n\n    return a;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/160.html",
    "category": "Algorithms",
    "acceptance_rate": 60.812794428361464,
    "topics": [
      "Hash Table",
      "Linked List",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 15707,
    "dislikes": 1430,
    "similar_questions": "[{\"title\": \"Minimum Index Sum of Two Lists\", \"titleSlug\": \"minimum-index-sum-of-two-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 1951712, \"totalSubmissionRaw\": 3209374, \"acRate\": \"60.8%\"}",
    "title_pt": "Interseção de Duas Listas Encadeadas",
    "description_pt": "<p>Dadas as cabeças de duas listas encadeadas simplesmente encadeadas <code>headA</code> e <code>headB</code>, retorne <em>o nó no qual as duas listas se intersectam</em>. Se as duas listas encadeadas não tiverem interseção alguma, retorne <code>null</code>.</p>\n\n<p>Por exemplo, as duas listas encadeadas a seguir começam a se intersectar no nó <code>c1</code>:</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_statement.png\" style=\"width: 500px; height: 162px;\" />\n<p>Os casos de teste são gerados de modo que não haja ciclos em lugar algum em toda a estrutura encadeada.</p>\n\n<p><strong>Nota</strong> que as listas encadeadas devem <strong>manter sua estrutura original</strong> após a função retornar.</p>\n\n<p><strong>Julgador Personalizado:</strong></p>\n\n<p>As entradas para o <strong>julgador</strong> são dadas da seguinte forma (seu programa <strong>não</strong> recebe essas entradas):</p>\n\n<ul>\n\t<li><code>intersectVal</code> - O valor do nó onde a interseção ocorre. Este é <code>0</code> se não houver nó intersectado.</li>\n\t<li><code>listA</code> - A primeira lista encadeada.</li>\n\t<li><code>listB</code> - A segunda lista encadeada.</li>\n\t<li><code>skipA</code> - O número de nós a avançar em <code>listA</code> (a partir da cabeça) para chegar ao nó intersectado.</li>\n\t<li><code>skipB</code> - O número de nós a avançar em <code>listB</code> (a partir da cabeça) para chegar ao nó intersectado.</li>\n</ul>\n\n<p>O julgador então criará a estrutura encadeada com base nessas entradas e passará as duas cabeças, <code>headA</code> e <code>headB</code>, para o seu programa. Se você retornar corretamente o nó intersectado, então sua solução será <strong>aceita</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png\" style=\"width: 500px; height: 162px;\" />\n<pre>\n<strong>Entrada:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\n<strong>Saída:</strong> Intersectado em &#39;8&#39;\n<strong>Explicação:</strong> O valor do nó intersectado é 8 (note que isso não deve ser 0 se as duas listas se intersectarem).\nA partir da cabeça de A, lê-se [4,1,8,4,5]. A partir da cabeça de B, lê-se [5,6,1,8,4,5]. Há 2 nós antes do nó intersectado em A; Há 3 nós antes do nó intersectado em B.\n- Observe que o valor do nó intersectado não é 1 porque os nós com valor 1 em A e B (2<sup>o</sup> nó em A e 3<sup>o</sup> nó em B) são referências de nó diferentes. Em outras palavras, eles apontam para dois locais diferentes na memória, enquanto os nós com valor 8 em A e B (3<sup>o</sup> nó em A e 4<sup>o</sup> nó em B) apontam para o mesmo local na memória.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png\" style=\"width: 500px; height: 194px;\" />\n<pre>\n<strong>Entrada:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n<strong>Saída:</strong> Intersectado em &#39;2&#39;\n<strong>Explicação:</strong> O valor do nó intersectado é 2 (note que isso não deve ser 0 se as duas listas se intersectarem).\nA partir da cabeça de A, lê-se [1,9,1,2,4]. A partir da cabeça de B, lê-se [3,2,4]. Há 3 nós antes do nó intersectado em A; Há 1 nó antes do nó intersectado em B.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png\" style=\"width: 300px; height: 189px;\" />\n<pre>\n<strong>Entrada:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n<strong>Saída:</strong> Sem interseção\n<strong>Explicação:</strong> A partir da cabeça de A, lê-se [2,6,4]. A partir da cabeça de B, lê-se [1,5]. Como as duas listas não se intersectam, intersectVal deve ser 0, enquanto skipA e skipB podem ser valores arbitrários.\nExplicação: As duas listas não se intersectam, então retorne null.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós de <code>listA</code> está em <code>m</code>.</li>\n\t<li>O número de nós de <code>listB</code> está em <code>n</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= skipA &lt;= m</code></li>\n\t<li><code>0 &lt;= skipB &lt;= n</code></li>\n\t<li><code>intersectVal</code> é <code>0</code> se <code>listA</code> e <code>listB</code> não se intersectarem.</li>\n\t<li><code>intersectVal == listA[skipA] == listB[skipB]</code> se <code>listA</code> e <code>listB</code> se intersectarem.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você poderia escrever uma solução que execute em tempo <code>O(m + n)</code> e use apenas memória <code>O(1)</code>?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "162",
    "paidOnly": false,
    "title": "Find Peak Element",
    "titleSlug": "find-peak-element",
    "url": "https://leetcode.com/problems/find-peak-element",
    "description_url": "https://leetcode.com/problems/find-peak-element/description/",
    "description": "<p>A peak element is an element that is strictly greater than its neighbors.</p>\n\n<p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p>\n\n<p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p>\n\n<p>You must write an algorithm that runs in <code>O(log n)</code> time.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,1,3,5,6,4]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-peak-element/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findPeakElement(self, nums: List[int]) -> int:\n    l = 0\n    r = len(nums) - 1\n\n    while l < r:\n      m = (l + r) // 2\n      if nums[m] >= nums[m + 1]:\n        r = m\n      else:\n        l = m + 1\n\n    return l",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findPeakElement(int[] nums) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (nums[m] >= nums[m + 1])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findPeakElement(vector<int>& nums) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (nums[m] >= nums[m + 1])\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/162.html",
    "category": "Algorithms",
    "acceptance_rate": 46.47250077389026,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 13247,
    "dislikes": 4838,
    "similar_questions": "[{\"title\": \"Peak Index in a Mountain Array\", \"titleSlug\": \"peak-index-in-a-mountain-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find a Peak Element II\", \"titleSlug\": \"find-a-peak-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Pour Water Between Buckets to Make Water Levels Equal\", \"titleSlug\": \"pour-water-between-buckets-to-make-water-levels-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Hills and Valleys in an Array\", \"titleSlug\": \"count-hills-and-valleys-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Peaks\", \"titleSlug\": \"find-the-peaks\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"4.1M\", \"totalAcceptedRaw\": 1903590, \"totalSubmissionRaw\": 4096161, \"acRate\": \"46.5%\"}",
    "title_pt": "Encontrar Elemento de Pico",
    "description_pt": "<p>Um elemento de pico é um elemento que é estritamente maior do que seus vizinhos.</p>\n\n<p>Dado um array de inteiros <strong>indexado em 0</strong> <code>nums</code>, encontre um elemento de pico e retorne seu índice. Se o array contiver múltiplos picos, retorne o índice de <strong>qualquer um dos picos</strong>.</p>\n\n<p>Você pode imaginar que <code>nums[-1] = nums[n] = -&infin;</code>. Em outras palavras, um elemento é sempre considerado estritamente maior do que um vizinho que esteja fora do array.</p>\n\n<p>Você deve escrever um algoritmo que execute em tempo <code>O(log n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> 3 é um elemento de pico e sua função deve retornar o número de índice 2.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,1,3,5,6,4]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Sua função pode retornar tanto o número de índice 1, onde o elemento de pico é 2, quanto o número de índice 5, onde o elemento de pico é 6.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>nums[i] != nums[i + 1]</code> para todo <code>i</code> válido.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "164",
    "paidOnly": false,
    "title": "Maximum Gap",
    "titleSlug": "maximum-gap",
    "url": "https://leetcode.com/problems/maximum-gap",
    "description_url": "https://leetcode.com/problems/maximum-gap/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p>\n\n<p>You must write an algorithm that runs in linear time and uses linear extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,6,9,1]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [10]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-gap/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Bucket:\n  def __init__(self, mini: int, maxi: int):\n    self.mini = mini\n    self.maxi = maxi\n\n\nclass Solution:\n  def maximumGap(self, nums: List[int]) -> int:\n    if len(nums) < 2:\n      return 0\n\n    mini = min(nums)\n    maxi = max(nums)\n    if mini == maxi:\n      return 0\n\n    gap = ceil((maxi - mini) / (len(nums) - 1))\n    bucketSize = (maxi - mini) // gap + 1\n    buckets = [Bucket(math.inf, -math.inf) for _ in range(bucketSize)]\n\n    for num in nums:\n      i = (num - mini) // gap\n      buckets[i].mini = min(buckets[i].mini, num)\n      buckets[i].maxi = max(buckets[i].maxi, num)\n\n    ans = 0\n    prevMax = mini\n\n    for bucket in buckets:\n      if bucket.mini == math.inf:\n        continue  # Empty bucket\n      ans = max(ans, bucket.mini - prevMax)\n      prevMax = bucket.maxi\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Bucket {\n  public int min;\n  public int max;\n\n  public Bucket(int min, int max) {\n    this.min = min;\n    this.max = max;\n  }\n}\n\nclass Solution {\n  public int maximumGap(int[] nums) {\n    if (nums.length < 2)\n      return 0;\n\n    final int min = Arrays.stream(nums).min().getAsInt();\n    final int max = Arrays.stream(nums).max().getAsInt();\n    if (min == max)\n      return 0;\n\n    final int gap = (int) Math.ceil((double) (max - min) / (nums.length - 1));\n    final int bucketsLength = (max - min) / gap + 1;\n    Bucket[] buckets = new Bucket[bucketsLength];\n\n    for (int i = 0; i < buckets.length; ++i)\n      buckets[i] = new Bucket(Integer.MAX_VALUE, Integer.MIN_VALUE);\n\n    for (final int num : nums) {\n      final int i = (num - min) / gap;\n      buckets[i].min = Math.min(buckets[i].min, num);\n      buckets[i].max = Math.max(buckets[i].max, num);\n    }\n\n    int ans = 0;\n    int prevMax = min;\n\n    for (final Bucket bucket : buckets) {\n      if (bucket.min == Integer.MAX_VALUE) // Empty bucket\n        continue;\n      ans = Math.max(ans, bucket.min - prevMax);\n      prevMax = bucket.max;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Bucket {\n  int min;\n  int max;\n};\n\nclass Solution {\n public:\n  int maximumGap(vector<int>& nums) {\n    if (nums.size() < 2)\n      return 0;\n\n    const int mini = *min_element(begin(nums), end(nums));\n    const int maxi = *max_element(begin(nums), end(nums));\n    if (mini == maxi)\n      return 0;\n\n    const int gap = ceil((maxi - mini) / (double)(nums.size() - 1));\n    const int bucketSize = (maxi - mini) / gap + 1;\n    vector<Bucket> buckets(bucketSize, {INT_MAX, INT_MIN});\n\n    for (const int num : nums) {\n      const int i = (num - mini) / gap;\n      buckets[i].min = min(buckets[i].min, num);\n      buckets[i].max = max(buckets[i].max, num);\n    }\n\n    int ans = 0;\n    int prevMax = mini;\n\n    for (const Bucket& bucket : buckets) {\n      if (bucket.min == INT_MAX)\n        continue;  // Empty bucket\n      ans = max(ans, bucket.min - prevMax);\n      prevMax = bucket.max;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/164.html",
    "category": "Algorithms",
    "acceptance_rate": 49.1259529728423,
    "topics": [
      "Array",
      "Sorting",
      "Bucket Sort",
      "Radix Sort"
    ],
    "hints": [],
    "likes": 3427,
    "dislikes": 419,
    "similar_questions": "[{\"title\": \"Widest Vertical Area Between Two Points Containing No Points\", \"titleSlug\": \"widest-vertical-area-between-two-points-containing-no-points\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Consecutive Floors Without Special Floors\", \"titleSlug\": \"maximum-consecutive-floors-without-special-floors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"272.3K\", \"totalSubmission\": \"554.3K\", \"totalAcceptedRaw\": 272308, \"totalSubmissionRaw\": 554309, \"acRate\": \"49.1%\"}",
    "title_pt": "Maior Lacuna",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>a maior diferença entre dois elementos sucessivos em sua forma ordenada</em>. Se o array contiver menos de dois elementos, retorne <code>0</code>.</p>\n\n<p>Você deve escrever um algoritmo que execute em tempo linear e use espaço extra linear.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,6,9,1]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A forma ordenada do array é [1,3,6,9], tanto (3,6) quanto (6,9) têm a maior diferença 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [10]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> O array contém menos de 2 elementos, portanto retorne 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "165",
    "paidOnly": false,
    "title": "Compare Version Numbers",
    "titleSlug": "compare-version-numbers",
    "url": "https://leetcode.com/problems/compare-version-numbers",
    "description_url": "https://leetcode.com/problems/compare-version-numbers/description/",
    "description": "<p>Given two <strong>version strings</strong>, <code>version1</code> and <code>version2</code>, compare them. A version string consists of <strong>revisions</strong> separated by dots <code>&#39;.&#39;</code>. The <strong>value of the revision</strong> is its <strong>integer conversion</strong> ignoring leading zeros.</p>\n\n<p>To compare version strings, compare their revision values in <strong>left-to-right order</strong>. If one of the version strings has fewer revisions, treat the missing revision values as <code>0</code>.</p>\n\n<p>Return the following:</p>\n\n<ul>\n\t<li>If <code>version1 &lt; version2</code>, return -1.</li>\n\t<li>If <code>version1 &gt; version2</code>, return 1.</li>\n\t<li>Otherwise, return 0.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">-1</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>version1&#39;s second revision is &quot;2&quot; and version2&#39;s second revision is &quot;10&quot;: 2 &lt; 10, so version1 &lt; version2.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Ignoring leading zeroes, both &quot;01&quot; and &quot;001&quot; represent the same integer &quot;1&quot;.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>version1 has less revisions, which means every missing revision are treated as &quot;0&quot;.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li>\n\t<li><code>version1</code> and <code>version2</code>&nbsp;only contain digits and <code>&#39;.&#39;</code>.</li>\n\t<li><code>version1</code> and <code>version2</code>&nbsp;<strong>are valid version numbers</strong>.</li>\n\t<li>All the given revisions in&nbsp;<code>version1</code> and <code>version2</code>&nbsp;can be stored in&nbsp;a&nbsp;<strong>32-bit integer</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/compare-version-numbers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def compareVersion(self, version1: str, version2: str) -> int:\n    levels1 = version1.split('.')\n    levels2 = version2.split('.')\n    length = max(len(levels1), len(levels2))\n\n    for i in range(length):\n      v1 = int(levels1[i]) if i < len(levels1) else 0\n      v2 = int(levels2[i]) if i < len(levels2) else 0\n      if v1 < v2:\n        return -1\n      if v1 > v2:\n        return 1\n\n    return 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int compareVersion(String version1, String version2) {\n    final String[] levels1 = version1.split(\"\\\\.\");\n    final String[] levels2 = version2.split(\"\\\\.\");\n    final int length = Math.max(levels1.length, levels2.length);\n\n    for (int i = 0; i < length; ++i) {\n      final Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;\n      final Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;\n      final int compare = v1.compareTo(v2);\n      if (compare != 0)\n        return compare;\n    }\n\n    return 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int compareVersion(string version1, string version2) {\n    istringstream iss1(version1);\n    istringstream iss2(version2);\n    int v1;\n    int v2;\n    char dotChar;\n\n    while (bool(iss1 >> v1) + bool(iss2 >> v2)) {\n      if (v1 < v2)\n        return -1;\n      if (v1 > v2)\n        return 1;\n      iss1 >> dotChar;\n      iss2 >> dotChar;\n      v1 = 0;\n      v2 = 0;\n    }\n\n    return 0;\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/165.html",
    "category": "Algorithms",
    "acceptance_rate": 42.211886104430135,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [
      "You can use two pointers for each version string to traverse them together while comparing the corresponding segments.",
      "Utilize the substring method to extract each version segment delimited by '.'. Ensure you're extracting the segments correctly by adjusting the start and end indices accordingly."
    ],
    "likes": 2756,
    "dislikes": 2760,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"544.1K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 544061, \"totalSubmissionRaw\": 1288885, \"acRate\": \"42.2%\"}",
    "title_pt": "Comparar Números de Versão",
    "description_pt": "<p>Dadas duas <strong>strings de versão</strong>, <code>version1</code> e <code>version2</code>, compare-as. Uma string de versão consiste em <strong>revisões</strong> separadas por pontos <code>&#39;.&#39;</code>. O <strong>valor da revisão</strong> é sua <strong>conversão para inteiro</strong>, ignorando zeros à esquerda.</p>\n\n<p>Para comparar strings de versão, compare os valores de suas revisões em <strong>ordem da esquerda para a direita</strong>. Se uma das strings de versão tiver menos revisões, trate os valores das revisões ausentes como <code>0</code>.</p>\n\n<p>Retorne o seguinte:</p>\n\n<ul>\n\t<li>Se <code>version1 &lt; version2</code>, retorne -1.</li>\n\t<li>Se <code>version1 &gt; version2</code>, retorne 1.</li>\n\t<li>Caso contrário, retorne 0.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">version1 = &quot;1.2&quot;, version2 = &quot;1.10&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">-1</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A segunda revisão de version1 é &quot;2&quot; e a segunda revisão de version2 é &quot;10&quot;: 2 &lt; 10, então version1 &lt; version2.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">version1 = &quot;1.01&quot;, version2 = &quot;1.001&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Ignorando zeros à esquerda, tanto &quot;01&quot; quanto &quot;001&quot; representam o mesmo inteiro &quot;1&quot;.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">version1 = &quot;1.0&quot;, version2 = &quot;1.0.0.0&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>version1 tem menos revisões, o que significa que toda revisão ausente é tratada como &quot;0&quot;.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= version1.length, version2.length &lt;= 500</code></li>\n\t<li><code>version1</code> e <code>version2</code>&nbsp;contêm apenas dígitos e <code>&#39;.&#39;</code>.</li>\n\t<li><code>version1</code> e <code>version2</code>&nbsp;<strong>são números de versão válidos</strong>.</li>\n\t<li>Todas as revisões fornecidas em&nbsp;<code>version1</code> e <code>version2</code>&nbsp;podem ser armazenadas em&nbsp;um&nbsp;<strong>inteiro de 32 bits</strong>.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Você pode usar dois ponteiros para cada string de versão para percorrê-las juntas enquanto compara os segmentos correspondentes.",
      "- Dica 2: Utilize o método substring para extrair cada segmento da versão delimitado por '.'. Certifique-se de extrair os segmentos corretamente ajustando os índices de início e fim de acordo."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "166",
    "paidOnly": false,
    "title": "Fraction to Recurring Decimal",
    "titleSlug": "fraction-to-recurring-decimal",
    "url": "https://leetcode.com/problems/fraction-to-recurring-decimal",
    "description_url": "https://leetcode.com/problems/fraction-to-recurring-decimal/description/",
    "description": "<p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p>\n\n<p>If the fractional part is repeating, enclose the repeating part in parentheses.</p>\n\n<p>If multiple answers are possible, return <strong>any of them</strong>.</p>\n\n<p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> numerator = 1, denominator = 2\n<strong>Output:</strong> &quot;0.5&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> numerator = 2, denominator = 1\n<strong>Output:</strong> &quot;2&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> numerator = 4, denominator = 333\n<strong>Output:</strong> &quot;0.(012)&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>denominator != 0</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/fraction-to-recurring-decimal/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n    if numerator == 0:\n      return '0'\n\n    ans = ''\n\n    if (numerator < 0) ^ (denominator < 0):\n      ans += '-'\n\n    numerator = abs(numerator)\n    denominator = abs(denominator)\n    ans += str(numerator // denominator)\n\n    if numerator % denominator == 0:\n      return ans\n\n    ans += '.'\n    dict = {}\n\n    remainder = numerator % denominator\n    while remainder:\n      if remainder in dict:\n        ans = ans[:dict[remainder]] + '(' + ans[dict[remainder]:] + ')'\n        break\n      dict[remainder] = len(ans)\n      remainder *= 10\n      ans += str(remainder // denominator)\n      remainder %= denominator\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String fractionToDecimal(int numerator, int denominator) {\n    if (numerator == 0)\n      return \"0\";\n\n    StringBuilder sb = new StringBuilder();\n\n    if (numerator < 0 ^ denominator < 0)\n      sb.append(\"-\");\n\n    long n = Math.abs((long) numerator);\n    long d = Math.abs((long) denominator);\n    sb.append(n / d);\n\n    if (n % d == 0)\n      return sb.toString();\n\n    sb.append(\".\");\n    Map<Long, Integer> seen = new HashMap<>();\n\n    for (long r = n % d; r > 0; r %= d) {\n      if (seen.containsKey(r)) {\n        sb.insert(seen.get(r), \"(\");\n        sb.append(\")\");\n        break;\n      }\n      seen.put(r, sb.length());\n      r *= 10;\n      sb.append(r / d);\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string fractionToDecimal(int numerator, int denominator) {\n    if (numerator == 0)\n      return \"0\";\n\n    string ans;\n\n    if (numerator < 0 ^ denominator < 0)\n      ans += \"-\";\n\n    long n = labs(numerator);\n    long d = labs(denominator);\n    ans += to_string(n / d);\n\n    if (n % d == 0)\n      return ans;\n\n    ans += '.';\n    unordered_map<int, int> seen;\n\n    for (long r = n % d; r; r %= d) {\n      if (seen.count(r)) {\n        ans.insert(seen[r], 1, '(');\n        ans += ')';\n        break;\n      }\n      seen[r] = ans.size();\n      r *= 10;\n      ans += to_string(r / d);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/166.html",
    "category": "Algorithms",
    "acceptance_rate": 26.124512420447548,
    "topics": [
      "Hash Table",
      "Math",
      "String"
    ],
    "hints": [
      "No scary math, just apply elementary math knowledge. Still remember how to perform a <i>long division</i>?",
      "Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern?",
      "Notice that once the remainder starts repeating, so does the divided result.",
      "Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly."
    ],
    "likes": 2164,
    "dislikes": 3729,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"254.5K\", \"totalSubmission\": \"974.2K\", \"totalAcceptedRaw\": 254505, \"totalSubmissionRaw\": 974200, \"acRate\": \"26.1%\"}",
    "title_pt": "Fração para Decimal Recorrente",
    "description_pt": "<p>Dados dois inteiros representando o <code>numerator</code> e o <code>denominator</code> de uma fração, retorne <em>a fração em formato de string</em>.</p>\n\n<p>Se a parte fracionária for repetitiva, coloque a parte repetitiva entre parênteses.</p>\n\n<p>Se múltiplas respostas forem possíveis, retorne <strong>qualquer uma delas</strong>.</p>\n\n<p>É <strong>garantido</strong> que o comprimento da string de resposta é menor que <code>10<sup>4</sup></code> para todas as entradas fornecidas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numerator = 1, denominator = 2\n<strong>Saída:</strong> &quot;0.5&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numerator = 2, denominator = 1\n<strong>Saída:</strong> &quot;2&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numerator = 4, denominator = 333\n<strong>Saída:</strong> &quot;0.(012)&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>denominator != 0</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Nada de matemática assustadora, apenas aplique conhecimentos elementares de matemática. Ainda se lembra de como fazer uma <i>divisão longa</i>?",
      "Dica 2: Tente uma divisão longa em 4/9, a parte repetitiva é óbvia. Agora tente 4/333. Você percebe um padrão?",
      "Dica 3: Observe que, assim que o resto começa a se repetir, o resultado da divisão também se repete.",
      "Dica 4: Tenha cuidado com casos extremos! Liste o máximo de casos de teste que você conseguir imaginar e teste seu código minuciosamente."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "167",
    "paidOnly": false,
    "title": "Two Sum II - Input Array Is Sorted",
    "titleSlug": "two-sum-ii-input-array-is-sorted",
    "url": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted",
    "description_url": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/",
    "description": "<p>Given a <strong>1-indexed</strong> array of integers <code>numbers</code> that is already <strong><em>sorted in non-decreasing order</em></strong>, find two numbers such that they add up to a specific <code>target</code> number. Let these two numbers be <code>numbers[index<sub>1</sub>]</code> and <code>numbers[index<sub>2</sub>]</code> where <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p>\n\n<p>Return<em> the indices of the two numbers, </em><code>index<sub>1</sub></code><em> and </em><code>index<sub>2</sub></code><em>, <strong>added by one</strong> as an integer array </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> of length 2.</em></p>\n\n<p>The tests are generated such that there is <strong>exactly one solution</strong>. You <strong>may not</strong> use the same element twice.</p>\n\n<p>Your solution must use only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9\n<strong>Output:</strong> [1,2]\n<strong>Explanation:</strong> The sum of 2 and 7 is 9. Therefore, index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6\n<strong>Output:</strong> [1,3]\n<strong>Explanation:</strong> The sum of 2 and 4 is 6. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 3. We return [1, 3].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1\n<strong>Output:</strong> [1,2]\n<strong>Explanation:</strong> The sum of -1 and 0 is -1. Therefore index<sub>1</sub> = 1, index<sub>2</sub> = 2. We return [1, 2].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li>\n\t<li><code>numbers</code> is sorted in <strong>non-decreasing order</strong>.</li>\n\t<li><code>-1000 &lt;= target &lt;= 1000</code></li>\n\t<li>The tests are generated such that there is <strong>exactly one solution</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def twoSum(self, numbers: List[int], target: int) -> List[int]:\n    l = 0\n    r = len(numbers) - 1\n\n    while l < r:\n      summ = numbers[l] + numbers[r]\n      if summ == target:\n        return [l + 1, r + 1]\n      if summ < target:\n        l += 1\n      else:\n        r -= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] twoSum(int[] numbers, int target) {\n    int l = 0;\n    int r = numbers.length - 1;\n\n    while (numbers[l] + numbers[r] != target)\n      if (numbers[l] + numbers[r] < target)\n        ++l;\n      else\n        --r;\n\n    return new int[] {l + 1, r + 1};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> twoSum(vector<int>& numbers, int target) {\n    int l = 0;\n    int r = numbers.size() - 1;\n\n    while (numbers[l] + numbers[r] != target)\n      if (numbers[l] + numbers[r] < target)\n        ++l;\n      else\n        --r;\n\n    return {l + 1, r + 1};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/167.html",
    "category": "Algorithms",
    "acceptance_rate": 63.230284213221196,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search"
    ],
    "hints": [],
    "likes": 12488,
    "dislikes": 1469,
    "similar_questions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum IV - Input is a BST\", \"titleSlug\": \"two-sum-iv-input-is-a-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum Less Than K\", \"titleSlug\": \"two-sum-less-than-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.7M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2672321, \"totalSubmissionRaw\": 4226331, \"acRate\": \"63.2%\"}",
    "title_pt": "Soma de Dois Números II - O Array de Entrada Está Ordenado",
    "description_pt": "<p>Dado um array <strong>indexado em 1</strong> de inteiros <code>numbers</code> que já está <strong><em>ordenado em ordem não decrescente</em></strong>, encontre dois números tais que eles somem até um número específico <code>target</code>. Seja esses dois números <code>numbers[index<sub>1</sub>]</code> e <code>numbers[index<sub>2</sub>]</code>, onde <code>1 &lt;= index<sub>1</sub> &lt; index<sub>2</sub> &lt;= numbers.length</code>.</p>\n\n<p>Retorne<em> os índices dos dois números, </em><code>index<sub>1</sub></code><em> e </em><code>index<sub>2</sub></code><em>, <strong>somados de um</strong> como um array de inteiros </em><code>[index<sub>1</sub>, index<sub>2</sub>]</code><em> de comprimento 2.</em></p>\n\n<p>Os testes são gerados de forma que exista <strong>exatamente uma solução</strong>. Você <strong>não pode</strong> usar o mesmo elemento duas vezes.</p>\n\n<p>Sua solução deve usar apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numbers = [<u>2</u>,<u>7</u>,11,15], target = 9\n<strong>Saída:</strong> [1,2]\n<strong>Explicação:</strong> A soma de 2 e 7 é 9. Portanto, index<sub>1</sub> = 1, index<sub>2</sub> = 2. Retornamos [1, 2].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numbers = [<u>2</u>,3,<u>4</u>], target = 6\n<strong>Saída:</strong> [1,3]\n<strong>Explicação:</strong> A soma de 2 e 4 é 6. Portanto index<sub>1</sub> = 1, index<sub>2</sub> = 3. Retornamos [1, 3].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numbers = [<u>-1</u>,<u>0</u>], target = -1\n<strong>Saída:</strong> [1,2]\n<strong>Explicação:</strong> A soma de -1 e 0 é -1. Portanto index<sub>1</sub> = 1, index<sub>2</sub> = 2. Retornamos [1, 2].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= numbers.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= numbers[i] &lt;= 1000</code></li>\n\t<li><code>numbers</code> está ordenado em <strong>ordem não decrescente</strong>.</li>\n\t<li><code>-1000 &lt;= target &lt;= 1000</code></li>\n\t<li>Os testes são gerados de forma que exista <strong>exatamente uma solução</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "168",
    "paidOnly": false,
    "title": "Excel Sheet Column Title",
    "titleSlug": "excel-sheet-column-title",
    "url": "https://leetcode.com/problems/excel-sheet-column-title",
    "description_url": "https://leetcode.com/problems/excel-sheet-column-title/description/",
    "description": "<p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p>\n\n<p>For example:</p>\n\n<pre>\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnNumber = 1\n<strong>Output:</strong> &quot;A&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnNumber = 28\n<strong>Output:</strong> &quot;AB&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnNumber = 701\n<strong>Output:</strong> &quot;ZY&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/excel-sheet-column-title/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach: Convert\n\n#### Intuition\n\nIn Excel, the columns are letters that correspond to numbers. We start with `A = 1`. Similarly, `2` corresponds to `B`  until `26` for `Z`. Once we run out of letters, we start appending them. `27` will correspond to `AA`, `28` for `AB`, and so on. In this problem, we are given the integer which is the column number and we need to return the corresponding letters for it.\n\nAt first glance, it might be tempting to say that these numbers are just base 26, but the catch is that in a base 26 system, the numbers would start from `0`. The mapping would be like below:\n\n![fig](../Figures/168/168A_resize.png)\n\nHowever, in the problem, we have the number starting from `1`, not `0`. But we can change them to process them like base 26 numbers. The important point to observe here is that every column title has the corresponding column number as a number in base 26 plus one. For example, let's convert the number `2002` to the letters `BXZ` by representing it as a number in base 26. Note that each part will have an extra `1` added to compensate for the fact that we are starting from `1` in our system. See the below example for a better understanding of the algorithm:\n\n`N = 2002` corresponds to `BXZ`.\n\nIn terms of base 26:\n\n$N = (B + 1) \\cdot 26^2 + (X + 1) \\cdot 26^1 + (Z + 1) * 26^0$\n\n$N = (1 + 1) \\cdot 676 + (23 + 1) \\cdot 26 + (25 + 1) \\cdot 1 = 2002$\n\nSteps to get the letters:\n\n1. Subtract `1` from `N`. Now, `N = 2001`. Take N modulo 26 and convert the result to the corresponding position in the alphabet. `2001 % 26 = 25`, which corresponds to `Z`, since we start with `A = 0`.\n2. Divide `N` by 26. We have $N = \\frac{2001}{26} = 76$.\n3. Repeat the process until `N = 0`. We subtract `1`, so now `N = 75`. Take it modulo 26: `75 % 26 = 23`. This corresponds to `X`.\n4. Divide `N` by 26. We have $N = \\frac{75}{26} = 2$.\n5. Subtract `1`, so now `N = 1`. Take it modulo 26: `1 % 26 = 1`. This corresponds to `B`.\n\nFinally, we are done, because $\\frac{N}{26} = 0$. The result is `BXZ`, the reverse order in which we found the letters.\n\n#### Algorithm\n\n1. Initialize an empty string `ans` which would store the column title.\n2. Do the following as long as `columnNumber` is greater than `0`:\n\n    1. Subtract `1` from the `columnNumber`\n    2. Find the character corresponding to `columnNumber % 26` and append it to the `ans` in the end.\n    3. Assign `columnNumber` to `columnNumber / 26`.\n3. Reverse the string `columnNumber` and return it.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/EhA2CHh8/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"EhA2CHh8\"></iframe>\n\n#### Complexity Analysis\n\nHere, $N$ is the column number given in the problem.\n\n* Time complexity: $O(\\log N)$\n\n  The number of operations would be equal to the number of while loop iterations. In each iteration, the number $N$ gets divided by $26$. Hence the time complexity would be $O(\\log{_{26}}{N})$. Note that the base of the logarithm is not relevant when it comes to big O, since all logarithms are related by a constant factor.\n\n* Space complexity: $O(1)$\n\n  We only need one string to store the output, but generally the space to store the output is not considered as part of space complexity and hence the space complexity is constant.\n  <br/>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def convertToTitle(self, n: int) -> str:\n    return self.convertToTitle((n - 1) // 26) + \\\n        chr(ord('A') + (n - 1) % 26) if n else ''",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String convertToTitle(int n) {\n    return n == 0 ? \"\" : convertToTitle((n - 1) / 26) + (char) ('A' + ((n - 1) % 26));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string convertToTitle(int n) {\n    return n == 0 ? \"\"\n                  : convertToTitle((n - 1) / 26) + (char)('A' + ((n - 1) % 26));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/168.html",
    "category": "Algorithms",
    "acceptance_rate": 43.31689588915539,
    "topics": [
      "Math",
      "String"
    ],
    "hints": [],
    "likes": 5802,
    "dislikes": 874,
    "similar_questions": "[{\"title\": \"Excel Sheet Column Number\", \"titleSlug\": \"excel-sheet-column-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Cells in a Range on an Excel Sheet\", \"titleSlug\": \"cells-in-a-range-on-an-excel-sheet\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Design Spreadsheet\", \"titleSlug\": \"design-spreadsheet\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"622.9K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 622886, \"totalSubmissionRaw\": 1437976, \"acRate\": \"43.3%\"}",
    "title_pt": "Título da Coluna de Planilha do Excel",
    "description_pt": "<p>Dado um inteiro <code>columnNumber</code>, retorne <em>seu título de coluna correspondente, como ele aparece em uma planilha do Excel</em>.</p>\n\n<p>Por exemplo:</p>\n\n<pre>\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnNumber = 1\n<strong>Saída:</strong> &quot;A&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnNumber = 28\n<strong>Saída:</strong> &quot;AB&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnNumber = 701\n<strong>Saída:</strong> &quot;ZY&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "169",
    "paidOnly": false,
    "title": "Majority Element",
    "titleSlug": "majority-element",
    "url": "https://leetcode.com/problems/majority-element",
    "description_url": "https://leetcode.com/problems/majority-element/description/",
    "description": "<p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p>\n\n<p>The majority element is the element that appears more than <code>&lfloor;n / 2&rfloor;</code> times. You may assume that the majority element always exists in the array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [3,2,3]\n<strong>Output:</strong> 3\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2]\n<strong>Output:</strong> 2\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?",
    "solution_url": "https://leetcode.com/problems/majority-element/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def majorityElement(self, nums: List[int]) -> int:\n    ans = None\n    count = 0\n\n    for num in nums:\n      if count == 0:\n        ans = num\n      count += (1 if num == ans else -1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int majorityElement(int[] nums) {\n    Integer ans = null;\n    int count = 0;\n\n    for (final int num : nums) {\n      if (count == 0)\n        ans = num;\n      count += num == ans ? 1 : -1;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int majorityElement(vector<int>& nums) {\n    int ans;\n    int count = 0;\n\n    for (const int num : nums) {\n      if (count == 0)\n        ans = num;\n      count += num == ans ? 1 : -1;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/169.html",
    "category": "Algorithms",
    "acceptance_rate": 65.66321328616299,
    "topics": [
      "Array",
      "Hash Table",
      "Divide and Conquer",
      "Sorting",
      "Counting"
    ],
    "hints": [],
    "likes": 20857,
    "dislikes": 729,
    "similar_questions": "[{\"title\": \"Majority Element II\", \"titleSlug\": \"majority-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check If a Number Is Majority Element in a Sorted Array\", \"titleSlug\": \"check-if-a-number-is-majority-element-in-a-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Index of a Valid Split\", \"titleSlug\": \"minimum-index-of-a-valid-split\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Exceed Threshold Value I\", \"titleSlug\": \"minimum-operations-to-exceed-threshold-value-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Most Common Response\", \"titleSlug\": \"find-the-most-common-response\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Valid Pair of Adjacent Digits in String\", \"titleSlug\": \"find-valid-pair-of-adjacent-digits-in-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.2M\", \"totalSubmission\": \"6.4M\", \"totalAcceptedRaw\": 4222149, \"totalSubmissionRaw\": 6430010, \"acRate\": \"65.7%\"}",
    "title_pt": "Elemento Majoritário",
    "description_pt": "<p>Dado um array <code>nums</code> de tamanho <code>n</code>, retorne <em>o elemento majoritário</em>.</p>\n\n<p>O elemento majoritário é o elemento que aparece mais do que <code>&lfloor;n / 2&rfloor;</code> vezes. Você pode assumir que o elemento majoritário sempre existe no array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [3,2,3]\n<strong>Saída:</strong> 3\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [2,2,1,1,1,2,2]\n<strong>Saída:</strong> 2\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria resolver o problema em tempo linear e em espaço <code>O(1)</code>?",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "171",
    "paidOnly": false,
    "title": "Excel Sheet Column Number",
    "titleSlug": "excel-sheet-column-number",
    "url": "https://leetcode.com/problems/excel-sheet-column-number",
    "description_url": "https://leetcode.com/problems/excel-sheet-column-number/description/",
    "description": "<p>Given a string <code>columnTitle</code> that represents the column title as appears in an Excel sheet, return <em>its corresponding column number</em>.</p>\n\n<p>For example:</p>\n\n<pre>\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnTitle = &quot;A&quot;\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnTitle = &quot;AB&quot;\n<strong>Output:</strong> 28\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> columnTitle = &quot;ZY&quot;\n<strong>Output:</strong> 701\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= columnTitle.length &lt;= 7</code></li>\n\t<li><code>columnTitle</code> consists only of uppercase English letters.</li>\n\t<li><code>columnTitle</code> is in the range <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/excel-sheet-column-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def titleToNumber(self, s: str) -> int:\n    ans = 0\n\n    for c in s:\n      ans = ans * 26 + ord(c) - ord('@')\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int titleToNumber(String s) {\n    int ans = 0;\n\n    for (final char c : s.toCharArray())\n      ans = ans * 26 + c - '@';\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int titleToNumber(string s) {\n    return accumulate(begin(s), end(s), 0,\n                      [](int a, int b) { return a * 26 + (b - 'A' + 1); });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/171.html",
    "category": "Algorithms",
    "acceptance_rate": 65.59480835056485,
    "topics": [
      "Math",
      "String"
    ],
    "hints": [],
    "likes": 4915,
    "dislikes": 387,
    "similar_questions": "[{\"title\": \"Excel Sheet Column Title\", \"titleSlug\": \"excel-sheet-column-title\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Cells in a Range on an Excel Sheet\", \"titleSlug\": \"cells-in-a-range-on-an-excel-sheet\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"786.1K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 786079, \"totalSubmissionRaw\": 1198386, \"acRate\": \"65.6%\"}",
    "title_pt": "Número da Coluna da Planilha Excel",
    "description_pt": "<p>Dada uma string <code>columnTitle</code> que representa o título da coluna como aparece em uma planilha Excel, retorne <em>seu número de coluna correspondente</em>.</p>\n\n<p>Por exemplo:</p>\n\n<pre>\nA -&gt; 1\nB -&gt; 2\nC -&gt; 3\n...\nZ -&gt; 26\nAA -&gt; 27\nAB -&gt; 28 \n...\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnTitle = &quot;A&quot;\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnTitle = &quot;AB&quot;\n<strong>Saída:</strong> 28\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> columnTitle = &quot;ZY&quot;\n<strong>Saída:</strong> 701\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= columnTitle.length &lt;= 7</code></li>\n\t<li><code>columnTitle</code> consiste apenas de letras maiúsculas do alfabeto inglês.</li>\n\t<li><code>columnTitle</code> está no intervalo <code>[&quot;A&quot;, &quot;FXSHRXW&quot;]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "172",
    "paidOnly": false,
    "title": "Factorial Trailing Zeroes",
    "titleSlug": "factorial-trailing-zeroes",
    "url": "https://leetcode.com/problems/factorial-trailing-zeroes",
    "description_url": "https://leetcode.com/problems/factorial-trailing-zeroes/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>the number of trailing zeroes in </em><code>n!</code>.</p>\n\n<p>Note that <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> 3! = 6, no trailing zero.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 5\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 5! = 120, one trailing zero.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you write a solution that works in logarithmic time complexity?</p>\n",
    "solution_url": "https://leetcode.com/problems/factorial-trailing-zeroes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def trailingZeroes(self, n: int) -> int:\n    return 0 if n == 0 else n // 5 + self.trailingZeroes(n // 5)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int trailingZeroes(int n) {\n    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int trailingZeroes(int n) {\n    return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/172.html",
    "category": "Algorithms",
    "acceptance_rate": 44.72988538684261,
    "topics": [
      "Math"
    ],
    "hints": [],
    "likes": 3355,
    "dislikes": 1974,
    "similar_questions": "[{\"title\": \"Number of Digit One\", \"titleSlug\": \"number-of-digit-one\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Preimage Size of Factorial Zeroes Function\", \"titleSlug\": \"preimage-size-of-factorial-zeroes-function\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Abbreviating the Product of a Range\", \"titleSlug\": \"abbreviating-the-product-of-a-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Trailing Zeros in a Cornered Path\", \"titleSlug\": \"maximum-trailing-zeros-in-a-cornered-path\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"554.1K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 554137, \"totalSubmissionRaw\": 1238857, \"acRate\": \"44.7%\"}",
    "title_pt": "Zeros à Direita de Fatorial",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>a quantidade de zeros à direita em </em><code>n!</code>.</p>\n\n<p>Observe que <code>n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> 3! = 6, sem zero à direita.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> 5! = 120, um zero à direita.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você poderia escrever uma solução que funcione em complexidade de tempo logarítmica?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "173",
    "paidOnly": false,
    "title": "Binary Search Tree Iterator",
    "titleSlug": "binary-search-tree-iterator",
    "url": "https://leetcode.com/problems/binary-search-tree-iterator",
    "description_url": "https://leetcode.com/problems/binary-search-tree-iterator/description/",
    "description": "<p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href=\"https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)\" target=\"_blank\">in-order traversal</a></strong> of a binary search tree (BST):</p>\n\n<ul>\n\t<li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li>\n\t<li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li>\n\t<li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li>\n</ul>\n\n<p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p>\n\n<p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png\" style=\"width: 189px; height: 178px;\" />\n<pre>\n<strong>Input</strong>\n[&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\n<strong>Output</strong>\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\n<strong>Explanation</strong>\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next();    // return 3\nbSTIterator.next();    // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 20\nbSTIterator.hasNext(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li>\n\t<li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-search-tree-iterator/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass BSTIterator:\n  def __init__(self, root: Optional[TreeNode]):\n    self.stack = []\n    self.pushLeftsUntilNone(root)\n\n  def next(self) -> int:\n    root = self.stack.pop()\n    self.pushLeftsUntilNone(root.right)\n    return root.val\n\n  def hasNext(self) -> bool:\n    return self.stack\n\n  def pushLeftsUntilNone(self, root: Optional[TreeNode]):\n    while root:\n      self.stack.append(root)\n      root = root.left",
    "solution_code_java": "\t\t\t\n\nclass BSTIterator {\n  public BSTIterator(TreeNode root) {\n    inorder(root);\n  }\n\n  /** @return the next smallest number */\n  public int next() {\n    return vals.get(i++);\n  }\n\n  /** @return whether we have a next smallest number */\n  public boolean hasNext() {\n    return i < vals.size();\n  }\n\n  private int i = 0;\n  private List<Integer> vals = new ArrayList<>();\n\n  private void inorder(TreeNode root) {\n    if (root == null)\n      return;\n\n    inorder(root.left);\n    vals.add(root.val);\n    inorder(root.right);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass BSTIterator {\n public:\n  BSTIterator(TreeNode* root) {\n    inorder(root);\n  }\n\n  /** @return the next smallest number */\n  int next() {\n    return vals[i++];\n  }\n\n  /** @return whether we have a next smallest number */\n  bool hasNext() {\n    return i < vals.size();\n  }\n\n private:\n  int i = 0;\n  vector<int> vals;\n\n  void inorder(TreeNode* root) {\n    if (root == nullptr)\n      return;\n\n    inorder(root->left);\n    vals.push_back(root->val);\n    inorder(root->right);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/173.html",
    "category": "Algorithms",
    "acceptance_rate": 74.64213852747818,
    "topics": [
      "Stack",
      "Tree",
      "Design",
      "Binary Search Tree",
      "Binary Tree",
      "Iterator"
    ],
    "hints": [],
    "likes": 8889,
    "dislikes": 543,
    "similar_questions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Flatten 2D Vector\", \"titleSlug\": \"flatten-2d-vector\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Peeking Iterator\", \"titleSlug\": \"peeking-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Inorder Successor in BST\", \"titleSlug\": \"inorder-successor-in-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Search Tree Iterator II\", \"titleSlug\": \"binary-search-tree-iterator-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"949.3K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 949289, \"totalSubmissionRaw\": 1271788, \"acRate\": \"74.6%\"}",
    "title_pt": "Iterador de Árvore Binária de Busca",
    "description_pt": "<p>Implemente a classe <code>BSTIterator</code> que representa um iterador sobre a <strong><a href=\"https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)\" target=\"_blank\">travessia em ordem</a></strong> de uma árvore binária de busca (BST):</p>\n\n<ul>\n\t<li><code>BSTIterator(TreeNode root)</code> Inicializa um objeto da classe <code>BSTIterator</code>. A <code>root</code> da BST é fornecida como parte do construtor. O ponteiro deve ser inicializado para um número inexistente menor do que qualquer elemento na BST.</li>\n\t<li><code>boolean hasNext()</code> Retorna <code>true</code> se existir um número na travessia à direita do ponteiro; caso contrário, retorna <code>false</code>.</li>\n\t<li><code>int next()</code> Move o ponteiro para a direita e, então, retorna o número no ponteiro.</li>\n</ul>\n\n<p>Observe que, ao inicializar o ponteiro para um menor número inexistente, a primeira chamada de <code>next()</code> retornará o menor elemento na BST.</p>\n\n<p>Você pode assumir que as chamadas de <code>next()</code> sempre serão válidas. Isto é, haverá pelo menos um próximo número na travessia em ordem quando <code>next()</code> for chamado.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png\" style=\"width: 189px; height: 178px;\" />\n<pre>\n<strong>Entrada</strong>\n[&quot;BSTIterator&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;, &quot;next&quot;, &quot;hasNext&quot;]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\n<strong>Saída</strong>\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\n<strong>Explicação</strong>\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next();    // return 3\nbSTIterator.next();    // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next();    // return 20\nbSTIterator.hasNext(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li>\n\t<li>No máximo <code>10<sup>5</sup></code> chamadas serão feitas para <code>hasNext</code> e <code>next</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Você poderia implementar <code>next()</code> e <code>hasNext()</code> para executarem em tempo médio <code>O(1)</code> e usarem <code>O(h)</code> memória, onde <code>h</code> é a altura da árvore?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "174",
    "paidOnly": false,
    "title": "Dungeon Game",
    "titleSlug": "dungeon-game",
    "url": "https://leetcode.com/problems/dungeon-game",
    "description_url": "https://leetcode.com/problems/dungeon-game/description/",
    "description": "<p>The demons had captured the princess and imprisoned her in <strong>the bottom-right corner</strong> of a <code>dungeon</code>. The <code>dungeon</code> consists of <code>m x n</code> rooms laid out in a 2D grid. Our valiant knight was initially positioned in <strong>the top-left room</strong> and must fight his way through <code>dungeon</code> to rescue the princess.</p>\n\n<p>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</p>\n\n<p>Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight&#39;s health (represented by positive integers).</p>\n\n<p>To reach the princess as quickly as possible, the knight decides to move only <strong>rightward</strong> or <strong>downward</strong> in each step.</p>\n\n<p>Return <em>the knight&#39;s minimum initial health so that he can rescue the princess</em>.</p>\n\n<p><strong>Note</strong> that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> dungeon = [[0]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == dungeon.length</code></li>\n\t<li><code>n == dungeon[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/dungeon-game/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n    m = len(dungeon)\n    n = len(dungeon[0])\n    dp = [math.inf] * (n + 1)\n    dp[n - 1] = 1\n\n    for i in reversed(range(m)):\n      for j in reversed(range(n)):\n        dp[j] = min(dp[j], dp[j + 1]) - dungeon[i][j]\n        dp[j] = max(dp[j], 1)\n\n    return dp[0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int calculateMinimumHP(int[][] dungeon) {\n    final int m = dungeon.length;\n    final int n = dungeon[0].length;\n    int[][] dp = new int[m + 1][n + 1];\n    Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n    dp[m][n - 1] = 1;\n    dp[m - 1][n] = 1;\n\n    for (int i = m - 1; i >= 0; --i)\n      for (int j = n - 1; j >= 0; --j) {\n        dp[i][j] = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];\n        dp[i][j] = Math.max(dp[i][j], 1);\n      }\n\n    return dp[0][0];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int calculateMinimumHP(vector<vector<int>>& dungeon) {\n    const int m = dungeon.size();\n    const int n = dungeon[0].size();\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));\n    dp[m][n - 1] = 1;\n    dp[m - 1][n] = 1;\n\n    for (int i = m - 1; i >= 0; --i)\n      for (int j = n - 1; j >= 0; --j) {\n        dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];\n        dp[i][j] = max(dp[i][j], 1);\n      }\n\n    return dp[0][0];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/174.html",
    "category": "Algorithms",
    "acceptance_rate": 39.37580536295023,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Matrix"
    ],
    "hints": [],
    "likes": 5996,
    "dislikes": 114,
    "similar_questions": "[{\"title\": \"Unique Paths\", \"titleSlug\": \"unique-paths\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Sum\", \"titleSlug\": \"minimum-path-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Cherry Pickup\", \"titleSlug\": \"cherry-pickup\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Cost in a Grid\", \"titleSlug\": \"minimum-path-cost-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Health to Beat Game\", \"titleSlug\": \"minimum-health-to-beat-game\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paths in Matrix Whose Sum Is Divisible by K\", \"titleSlug\": \"paths-in-matrix-whose-sum-is-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check if There is a Path With Equal Number of 0's And 1's\", \"titleSlug\": \"check-if-there-is-a-path-with-equal-number-of-0s-and-1s\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"256.7K\", \"totalSubmission\": \"651.9K\", \"totalAcceptedRaw\": 256683, \"totalSubmissionRaw\": 651880, \"acRate\": \"39.4%\"}",
    "title_pt": "Jogo da Masmorra",
    "description_pt": "<p>Os demônios capturaram a princesa e a aprisionaram no <strong>canto inferior direito</strong> de uma <code>dungeon</code>. A <code>dungeon</code> consiste em <code>m x n</code> salas dispostas em uma grade 2D. Nosso valente cavaleiro estava inicialmente posicionado na <strong>sala superior esquerda</strong> e deve lutar seu caminho através da <code>dungeon</code> para resgatar a princesa.</p>\n\n<p>O cavaleiro tem um ponto de saúde inicial representado por um inteiro positivo. Se, em qualquer momento, seu ponto de saúde cair para <code>0</code> ou menos, ele morre imediatamente.</p>\n\n<p>Algumas das salas são guardadas por demônios (representados por inteiros negativos), então o cavaleiro perde saúde ao entrar nessas salas; outras salas estão vazias (representadas por 0) ou contêm orbes mágicos que aumentam a saúde do cavaleiro (representados por inteiros positivos).</p>\n\n<p>Para alcançar a princesa o mais rápido possível, o cavaleiro decide mover-se apenas para a <strong>direita</strong> ou para <strong>baixo</strong> em cada passo.</p>\n\n<p>Retorne <em>a saúde inicial mínima do cavaleiro para que ele possa resgatar a princesa</em>.</p>\n\n<p><strong>Nota</strong> que qualquer sala pode conter ameaças ou power-ups, inclusive a primeira sala em que o cavaleiro entra e a sala do canto inferior direito onde a princesa está aprisionada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/13/dungeon-grid-1.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> A saúde inicial do cavaleiro deve ser de pelo menos 7 se ele seguir o caminho ótimo: RIGHT-&gt; RIGHT -&gt; DOWN -&gt; DOWN.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> dungeon = [[0]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == dungeon.length</code></li>\n\t<li><code>n == dungeon[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-1000 &lt;= dungeon[i][j] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "175",
    "paidOnly": false,
    "title": "Combine Two Tables",
    "titleSlug": "combine-two-tables",
    "url": "https://leetcode.com/problems/combine-two-tables",
    "description_url": "https://leetcode.com/problems/combine-two-tables/description/",
    "description": "<p>Table: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| personId    | int     |\n| lastName    | varchar |\n| firstName   | varchar |\n+-------------+---------+\npersonId is the primary key (column with unique values) for this table.\nThis table contains information about the ID of some persons and their first and last names.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Address</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| addressId   | int     |\n| personId    | int     |\n| city        | varchar |\n| state       | varchar |\n+-------------+---------+\naddressId is the primary key (column with unique values) for this table.\nEach row of this table contains information about the city and state of one person with ID = PersonId.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nPerson table:\n+----------+----------+-----------+\n| personId | lastName | firstName |\n+----------+----------+-----------+\n| 1        | Wang     | Allen     |\n| 2        | Alice    | Bob       |\n+----------+----------+-----------+\nAddress table:\n+-----------+----------+---------------+------------+\n| addressId | personId | city          | state      |\n+-----------+----------+---------------+------------+\n| 1         | 2        | New York City | New York   |\n| 2         | 3        | Leetcode      | California |\n+-----------+----------+---------------+------------+\n<strong>Output:</strong> \n+-----------+----------+---------------+----------+\n| firstName | lastName | city          | state    |\n+-----------+----------+---------------+----------+\n| Allen     | Wang     | Null          | Null     |\n| Bob       | Alice    | New York City | New York |\n+-----------+----------+---------------+----------+\n<strong>Explanation:</strong> \nThere is no address in the address table for the personId = 1 so we return null in their city and state.\naddressId = 1 contains information about the address of personId = 2.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/combine-two-tables/solutions/",
    "solution": "[TOC]\n\n# Solution\n---\n\n## pandas\n\n### Approach 1: Using `merge`\n\n**Visualization of approach 1**\n\n![fig](../Figures/175/175-1.png)\n\n#### Intuition\n\nLet's breakdown the steps given the following input DataFrames:\n\n`person`:\n<table>\n  <tr>\n    <th>personId</th>\n    <th>lastName</th>\n    <th>firstName</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>Wang</td>\n    <td>Allen</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>Alice</td>\n    <td>Bob</td>\n  </tr>\n</table>\n<br>\n\n`address`:\n<table>\n  <tr>\n    <th>addressId</th>\n    <th>personId</th>\n    <th>city</th>\n    <th>state</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>2</td>\n    <td>New York City</td>\n    <td>New York</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>3</td>\n    <td>Leetcode</td>\n    <td>California</td>\n  </tr>\n</table>\n<br>\n\n1. **Merging the DataFrames**\n   \n   ```python\n   result = pd.merge(person, address, on='personId', how='left')\n   ```\n   In this step, we are merging the `person` and `address` dataframes using a left join operation with the `pd.merge()` function. Here:\n   - `on='personId'` specifies that we are using the 'personId' column as the key for merging the data. This column is present in both dataframes, and it holds unique identifiers for the individuals.\n   - `how='left'` specifies that we are performing a left join, meaning all the records from the `person` dataframe (the left dataframe) will be retained, and the matching records from the `address` dataframe (the right dataframe) will be merged where the 'personId' values match. If a 'personId' from the `person` dataframe does not have a matching 'personId' in the `address` dataframe, the 'city' and 'state' columns for that record will contain Null values (representing missing data).\n\n<table>\n  <tr>\n    <th>personId</th>\n    <th>lastName</th>\n    <th>firstName</th>\n    <th>addressId</th>\n    <th>city</th>\n    <th>state</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>Wang</td>\n    <td>Allen</td>\n    <td>Null</td>\n    <td>Null</td>\n    <td>Null</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>Alice</td>\n    <td>Bob</td>\n    <td>1.0</td>\n    <td>New York City</td>\n    <td>New York</td>\n  </tr>\n</table>\n<br>\n\n2. **Selecting Relevant Columns**\n\n   ```python\n   result = result[['firstName', 'lastName', 'city', 'state']]\n   ```\n   In this step, we select only the columns that we are interested in for the final output. Since the merging operation can potentially bring in other columns from the `address` dataframe, we are explicitly selecting only the 'firstName', 'lastName', 'city', and 'state' columns to be in our final result. This helps in maintaining a clean and focused dataset which contains only the information we are interested in.\n\n<table>\n  <tr>\n    <th>firstName</th>\n    <th>lastName</th>\n    <th>city</th>\n    <th>state</th>\n  </tr>\n  <tr>\n    <td>Allen</td>\n    <td>Wang</td>\n    <td>Null</td>\n    <td>Null</td>\n  </tr>\n  <tr>\n    <td>Bob</td>\n    <td>Alice</td>\n    <td>New York City</td>\n    <td>New York</td>\n  </tr>\n</table>\n<br>\n\nIn summary, this script is taking two separate dataframes and merging them into a single dataframe where each row represents a person and contains their first name, last name, city, and state. This is done using the person's unique identifier to correctly match each person with their address. It's a common operation when you want to bring together information from different sources into a unified view.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/XRUKdTyk/shared\" frameBorder=\"0\" width=\"100%\" height=\"174\" name=\"XRUKdTyk\"></iframe>\n\n\n---\n\n## Database\n\n### Approach 1: Using `outer join`\n\n#### Intuition\n\nSince the *PersonId* in table **Address** is the foreign key of table **Person**, we can join these two tables to get the address information of a person.\n\nConsidering there might be no address information for every person, we should use `outer join` instead of the default `inner join`.\n\n#### Implementation\n\n> Note: For MySQL, an `outer join` is performed either using `left join` or `right join`. \n\n\n```sql\nselect FirstName, LastName, City, State\nfrom Person left join Address\non Person.PersonId = Address.PersonId\n;\n```\n\n> Note: Using the `where` clause to filter the records will fail if there is no address information for a person because it will not display the name information.",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/175.html",
    "category": "Database",
    "acceptance_rate": 77.9355776940997,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 3727,
    "dislikes": 232,
    "similar_questions": "[{\"title\": \"Employee Bonus\", \"titleSlug\": \"employee-bonus\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1272254, \"totalSubmissionRaw\": 1632444, \"acRate\": \"77.9%\"}",
    "title_pt": "Combinar Duas Tabelas",
    "description_pt": "<p>Tabela: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| personId    | int     |\n| lastName    | varchar |\n| firstName   | varchar |\n+-------------+---------+\npersonId is the primary key (column with unique values) for this table.\nThis table contains information about the ID of some persons and their first and last names.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Address</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| addressId   | int     |\n| personId    | int     |\n| city        | varchar |\n| state       | varchar |\n+-------------+---------+\naddressId is the primary key (column with unique values) for this table.\nEach row of this table contains information about the city and state of one person with ID = PersonId.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para relatar o primeiro nome, o sobrenome, a cidade e o estado de cada pessoa na tabela <code>Person</code>. Se o endereço de um <code>personId</code> não estiver presente na tabela <code>Address</code>, reporte <code>null</code> em seu lugar.</p>\n\n<p>Retorne a tabela resultante em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nPerson table:\n+----------+----------+-----------+\n| personId | lastName | firstName |\n+----------+----------+-----------+\n| 1        | Wang     | Allen     |\n| 2        | Alice    | Bob       |\n+----------+----------+-----------+\nAddress table:\n+-----------+----------+---------------+------------+\n| addressId | personId | city          | state      |\n+-----------+----------+---------------+------------+\n| 1         | 2        | New York City | New York   |\n| 2         | 3        | Leetcode      | California |\n+-----------+----------+---------------+------------+\n<strong>Saída:</strong> \n+-----------+----------+---------------+----------+\n| firstName | lastName | city          | state    |\n+-----------+----------+---------------+----------+\n| Allen     | Wang     | Null          | Null     |\n| Bob       | Alice    | New York City | New York |\n+-----------+----------+---------------+----------+\n<strong>Explicação:</strong> \nNão há endereço na tabela address para o personId = 1, então retornamos null para sua cidade e estado.\naddressId = 1 contém informações sobre o endereço de personId = 2.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "176",
    "paidOnly": false,
    "title": "Second Highest Salary",
    "titleSlug": "second-highest-salary",
    "url": "https://leetcode.com/problems/second-highest-salary",
    "description_url": "https://leetcode.com/problems/second-highest-salary/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| salary      | int  |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find&nbsp;the second highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there is no second highest salary,&nbsp;return&nbsp;<code>null (return&nbsp;None in Pandas)</code>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n| 2  | 200    |\n| 3  | 300    |\n+----+--------+\n<strong>Output:</strong> \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| 200                 |\n+---------------------+\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n+----+--------+\n<strong>Output:</strong> \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| null                |\n+---------------------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/second-highest-salary/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/176.html",
    "category": "Database",
    "acceptance_rate": 43.56633234889909,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 3832,
    "dislikes": 991,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1132342, \"totalSubmissionRaw\": 2599123, \"acRate\": \"43.6%\"}",
    "title_pt": "Segundo Maior Salário",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+-------------+------+\n| Nome da Coluna | Tipo |\n+-------------+------+\n| id          | int  |\n| salary      | int  |\n+-------------+------+\nid é a chave primária (coluna com valores únicos) desta tabela.\nCada linha desta tabela contém informações sobre o salário de um empregado.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar o segundo maior salário <strong>distinto</strong> da tabela <code>Employee</code>. Se não houver segundo maior salário, retorne <code>null (return&nbsp;None in Pandas)</code>.</p>\n\n<p>O formato do resultado está no seguinte exemplo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n| 2  | 200    |\n| 3  | 300    |\n+----+--------+\n<strong>Saída:</strong> \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| 200                 |\n+---------------------+\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n+----+--------+\n<strong>Saída:</strong> \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| null                |\n+---------------------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "177",
    "paidOnly": false,
    "title": "Nth Highest Salary",
    "titleSlug": "nth-highest-salary",
    "url": "https://leetcode.com/problems/nth-highest-salary",
    "description_url": "https://leetcode.com/problems/nth-highest-salary/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| salary      | int  |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the <code>n<sup>th</sup></code> highest <strong>distinct</strong> salary from the <code>Employee</code> table. If there are less than <code>n</code> distinct salaries, return&nbsp;<code>null</code>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n| 2  | 200    |\n| 3  | 300    |\n+----+--------+\nn = 2\n<strong>Output:</strong> \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| 200                    |\n+------------------------+\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n+----+--------+\nn = 2\n<strong>Output:</strong> \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| null                   |\n+------------------------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/nth-highest-salary/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/177.html",
    "category": "Database",
    "acceptance_rate": 37.927459847574326,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2102,
    "dislikes": 1089,
    "similar_questions": "[{\"title\": \"The Number of Users That Are Eligible for Discount\", \"titleSlug\": \"the-number-of-users-that-are-eligible-for-discount\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"486.6K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 486597, \"totalSubmissionRaw\": 1282967, \"acRate\": \"37.9%\"}",
    "title_pt": "N-ésimo Maior Salário",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| salary      | int  |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar o <code>n<sup>th</sup></code> maior salário <strong>distinto</strong> da tabela <code>Employee</code>. Se houver menos de <code>n</code> salários distintos, retorne&nbsp;<code>null</code>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n| 2  | 200    |\n| 3  | 300    |\n+----+--------+\nn = 2\n<strong>Saída:</strong> \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| 200                    |\n+------------------------+\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1  | 100    |\n+----+--------+\nn = 2\n<strong>Saída:</strong> \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| null                   |\n+------------------------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "178",
    "paidOnly": false,
    "title": "Rank Scores",
    "titleSlug": "rank-scores",
    "url": "https://leetcode.com/problems/rank-scores",
    "description_url": "https://leetcode.com/problems/rank-scores/description/",
    "description": "<p>Table: <code>Scores</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| score       | decimal |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains the score of a game. Score is a floating point value with two decimal places.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:</p>\n\n<ul>\n\t<li>The scores should be ranked from the highest to the lowest.</li>\n\t<li>If there is a tie between two scores, both should have the same ranking.</li>\n\t<li>After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.</li>\n</ul>\n\n<p>Return the result table ordered by <code>score</code> in descending order.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nScores table:\n+----+-------+\n| id | score |\n+----+-------+\n| 1  | 3.50  |\n| 2  | 3.65  |\n| 3  | 4.00  |\n| 4  | 3.85  |\n| 5  | 4.00  |\n| 6  | 3.65  |\n+----+-------+\n<strong>Output:</strong> \n+-------+------+\n| score | rank |\n+-------+------+\n| 4.00  | 1    |\n| 4.00  | 1    |\n| 3.85  | 2    |\n| 3.65  | 3    |\n| 3.65  | 3    |\n| 3.50  | 4    |\n+-------+------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/rank-scores/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/178.html",
    "category": "Database",
    "acceptance_rate": 65.05270937204669,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2272,
    "dislikes": 283,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"489.4K\", \"totalSubmission\": \"752.3K\", \"totalAcceptedRaw\": 489412, \"totalSubmissionRaw\": 752332, \"acRate\": \"65.1%\"}",
    "title_pt": "Classificação das Pontuações",
    "description_pt": "<p>Tabela: <code>Scores</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Tipo    |\n+-------------+---------+\n| id          | int     |\n| score       | decimal |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains the score of a game. Score is a floating point value with two decimal places.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar a classificação das pontuações. A classificação deve ser calculada de acordo com as seguintes regras:</p>\n\n<ul>\n\t<li>As pontuações devem ser classificadas da maior para a menor.</li>\n\t<li>Se houver empate entre duas pontuações, ambas devem ter a mesma classificação.</li>\n\t<li>Após um empate, o próximo número de classificação deve ser o próximo valor inteiro consecutivo. Em outras palavras, não deve haver lacunas entre as classificações.</li>\n</ul>\n\n<p>Retorne a tabela de resultado ordenada por <code>score</code> em ordem decrescente.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Scores:\n+----+-------+\n| id | score |\n+----+-------+\n| 1  | 3.50  |\n| 2  | 3.65  |\n| 3  | 4.00  |\n| 4  | 3.85  |\n| 5  | 4.00  |\n| 6  | 3.65  |\n+----+-------+\n<strong>Saída:</strong> \n+-------+------+\n| score | rank |\n+-------+------+\n| 4.00  | 1    |\n| 4.00  | 1    |\n| 3.85  | 2    |\n| 3.65  | 3    |\n| 3.65  | 3    |\n| 3.50  | 4    |\n+-------+------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "179",
    "paidOnly": false,
    "title": "Largest Number",
    "titleSlug": "largest-number",
    "url": "https://leetcode.com/problems/largest-number",
    "description_url": "https://leetcode.com/problems/largest-number/description/",
    "description": "<p>Given a list of non-negative integers <code>nums</code>, arrange them such that they form the largest number and return it.</p>\n\n<p>Since the result may be very large, so you need to return a string instead of an integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [10,2]\n<strong>Output:</strong> &quot;210&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,30,34,5,9]\n<strong>Output:</strong> &quot;9534330&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/largest-number/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview \n\nWe need to arrange a list of non-negative integers such that their concatenation results in the largest possible number. Return this largest number as a string.\n\nTo solve this, we use a custom comparator—a function or object that defines how two elements are compared for sorting. It’s used when the default comparison operations (like `<` or `>`) do not fit the requirements of a particular task. In this case, we want to compare numbers based on the result of their concatenation in two different orders.\n\nFirst, we convert each integer to a string. Then, we sort the array of strings.\n\nSorting the numbers in descending order might seem like a good idea, but it leads to issues when numbers share the same leading digit. For example, sorting `[9, 5, 34, 3, 30]` in descending order gives `\"9534303\"`, but the correct answer is `\"9534330\"`. The problem arises because `\"3\"` and `\"30\"` share the same leading digit. \n\nTo fix this, we compare the concatenated results of pairs of numbers. For example, given two numbers `a` and `b`, we compare `a + b` and `b + a` (where `+` denotes string concatenation). If `a + b` is larger, we place `a` before `b`. This ensures that the numbers are ordered correctly for the largest possible result.\n\nThe key is that this comparison ensures that the greedy approach of comparing pairs of numbers leads to the correct result. The difficult part is proving that this greedy logic always gives the correct answer.\n\n##### Proof of Correctness\n\nObjective: To ensure that our custom comparator for sorting numbers produces the largest possible concatenated number.\n\n1. Transitivity of the Comparator:\n\n    To verify the validity of the comparator, we need to prove that it is transitive. In other words, if number `A` should come before `B`, and `B` should come before `C`, then `A` must come before `C` in the final order.\n\n    We define the function:\n\n    $$\n    \\begin{aligned}\n        f(X) &= 10^{\\text{lg}(X) + 1}\n    \\end{aligned}\n    $$\n\n    where $\\text{lg}(X)$ denotes the logarithm base 10 of $X$. This function helps in determining the power of 10 needed to position `X` correctly when concatenating.\n\n2. Comparator Verification:\n\n    If concatenating `A` and `B` as `AB` is less than or equal to `BA`, we need to verify that:\n\n    $$\n    \\begin{aligned}\n        f(B)A + B &\\leq f(A)B + A \\\\\n        (f(B) - 1)A &\\leq (f(A) - 1)B \\\\\n        A &\\leq \\frac{B \\cdot (f(A) - 1)}{f(B) - 1}\n    \\end{aligned}\n    $$\n\n    Similarly, if `B` and `C` satisfy:\n\n    $$\n    \\begin{aligned}\n        BC &\\leq CB \\\\\n        (f(C) - 1)B &\\leq (f(B) - 1)C \\\\\n        B &\\leq \\frac{C \\cdot (f(B) - 1)}{f(C) - 1}\n    \\end{aligned}\n    $$\n\n3. By Combining These Inequalities:\n\n    $$\n    \\begin{aligned}\n        A &\\leq \\frac{C \\cdot (f(A) - 1)}{f(C) - 1} \\\\\n        (f(C) - 1)A &\\leq (f(A) - 1)C \\\\\n        f(C)A + C &\\leq f(A)C + A \\\\\n        AC &\\leq CA\n    \\end{aligned}\n    $$\n\n    This demonstrates that if `A` is before `B` and `B` is before `C`, then `A` must come before `C`, maintaining a consistent ordering.\n\n4. By Establishing the Consistency of the Comparator:\n\n    We confirm that sorting numbers with this comparator yields the largest concatenated number. For example, sorting `[3, 30, 34, 5, 9]` yields `[9, 5, 34, 3, 30]`, which concatenates to `\"9534330\"`, the largest possible number.\n\n---\n\n### Approach 1: Using Built-in Function  \n\n#### Intuition\n\nTo begin with, we need to determine the best order for the numbers to form the largest possible number when concatenated. We first convert each integer in the list to a string. This conversion allows us to compare different concatenated results. For instance, if we have the numbers `56` and `9`, converting them to strings allows us to compare `\"569\"` and `\"956\"`.\n\nNext, we use a custom sorting function to order these strings. This function compares two strings, `a` and `b`, by evaluating `a + b` against `b + a`. If `a + b` is greater, then `a` should come before `b` in the sorted list to maximize the final result.\n\nOnce sorted, we concatenate all the strings. If the first element in this sorted list is \"0\", it indicates that all numbers were zeros, so the largest number possible is \"0\". In this case, we return \"0\". If not, we return the concatenated result. \n\n#### Algorithm\n\n- Initialize `numStrings` as an array of strings to hold string representations of numbers.\n\n- Convert each integer in `nums` to a string and store it in `numStrings`.\n\n- Sort `numStrings` based on concatenated values:\n  - Use a lambda function to compare concatenated results (`a + b` and `b + a`).\n  - Ensure that the concatenation which forms a larger number determines the order.\n\n- Check if the largest number formed is \"0\":\n  - If the first element in `numStrings` is \"0\", return \"0\" (handles cases where all numbers are zero).\n\n- Concatenate all strings in `numStrings` to form the largest number.\n\n- Return the concatenated result as the largest number.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/me8hcMir/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"me8hcMir\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the `nums` array.\n\n- Time Complexity: $O(n \\log n)$\n\n    The most time-consuming operation is the sorting step, which uses a custom comparator. The sorting algorithm has a time complexity of $O(n \\log n)$. The conversion of numbers to strings and concatenation operations are linear with respect to the number of elements.\n\n- Space Complexity: $O(n + S)$\n\n    Additional space is used for storing the string representations of the numbers and the final concatenated result, which scales linearly with the size of the input array.\n\n    Some extra space is used when we sort an array of size $n$ in place. The space complexity of the sorting algorithm ($S$) depends on the programming language. The value of $S$ depends on the programming language and the sorting algorithm being used:\n    - In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has a space complexity of $O(n)$\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worst-case space complexity of $O( \\log n )$\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$\n\n    Thus, the total space complexity of the algorithm is $O(n + S)$.\n\n---\n\n### Approach 2: Quick Sort\n\n#### Intuition\n\nQuick Sort uses a divide-and-conquer method to sort the numbers. We start by selecting a pivot and partitioning the list into two parts based on how each number compares with the pivot. Specifically, we compare concatenated results like `a + pivot` with `pivot + a`.\n\nWe recursively sort the two partitions and then combine them. This recursive sorting ensures that the entire list is ordered such that concatenating all numbers results in the largest possible number.\n\nAfter sorting, we concatenate the numbers. If the final string starts with '0', it means all numbers were zeros, so we return \"0\". Otherwise, we return the concatenated result. This approach efficiently sorts and merges numbers to achieve the desired outcome.\n\nEach of these approaches aims to sort the numbers in such a way that their concatenation produces the largest possible number. By using different sorting techniques and comparison methods, we can achieve the correct order efficiently.\n\n</br>\n \nLet’s take the list `[3, 30, 34, 5, 9]`. To apply quick sort, we first select a pivot, such as `34`. We then partition the list so that numbers that produce a larger concatenated result with the pivot come before it, and those that produce a smaller result come after it.\n\nFor each number compared to `34`:\n- Compare `\"3\"` with `\"34\"`. Concatenate as `\"34\" + \"3\" = \"343\"` and `\"3\" + \"34\" = \"334\"`. Since `\"343\"` is greater, `\"3\"` is placed after `\"34\"`.\n- Compare `\"30\"` with `\"34\"`. Concatenate as `\"34\" + \"30\" = \"3430\"` and `\"30\" + \"34\" = \"3034\"`. Since `\"3430\"` is greater, `\"30\"` is placed after `\"34\"`.\n\nThe same process applies to `\"5\"` and `\"9\"`. The result of the partitioning places `\"9\"`, `\"5\"`, and `\"34\"` correctly relative to each other, but in the final list, we sort based on which numbers yield larger concatenated results when placed in various orders.\n\nAfter applying quick sort recursively to each partition, the list gets sorted to `[9, 5, 34, 3, 30]`. Concatenating these numbers results in `\"9534330\"`, which is the largest number possible.\n\n#### Algorithm\n\n- Call `quickSort(nums, 0, nums.size() - 1)` to sort the numbers in descending order based on their concatenated values.\n\n- `quickSort` function:\n  - If `left` is greater than or equal to `right`, return (base case: the array or sub-array is already sorted).\n  - Call `partition(nums, left, right)` to partition the array around a pivot and get the pivot index.\n  - Recursively call `quickSort` on the left sub-array (`left` to `pivotIndex - 1`).\n  - Recursively call `quickSort` on the right sub-array (`pivotIndex + 1` to `right`).\n\n- `partition` function:\n  - Choose the rightmost element as the pivot.\n  - Rearrange elements so that elements that, when concatenated with the pivot, form a larger number are moved to the left.\n  - Swap elements to place the pivot in its correct position.\n  - Return the pivot index.\n\n- `compare` function:\n  - Compare the concatenated strings of `firstNum` and `secondNum` to determine their order.\n\n- Concatenate the sorted numbers into a string to form the largest number.\n\n- Handle the edge case where the largest number is zero:\n  - Return \"0\" if the first character of the concatenated string is '0'.\n  - Otherwise, return the concatenated string.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/M4JEvsXx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"M4JEvsXx\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the `nums` array.\n\n- Time Complexity: $O(n \\log n)$ on average, $O(n^2)$ in the worst case\n\n    Quick sort generally has an average time complexity of $O(n \\log n)$, though its worst-case time complexity is $O(n^2)$ if the pivot selection consistently results in unbalanced partitions. The average case is efficient due to its partitioning strategy.\n\n- Space Complexity: $O(\\log n)$ on average, $O(n)$ in the worst case\n\n    The space complexity for quick sort is $O(\\log n)$ due to the depth of the recursion stack in the average case. In the worst case, it can be $O(n)$ if the recursion depth is not balanced.\n\n---\n\n### Approach 3: Merge Sort\n\n#### Intuition\n\nMerge sort involves recursively dividing the list into smaller parts until each part contains a single number. Sorting single-number parts is straightforward, so we focus on merging these parts in the correct order.\n\nDuring the merging process, we compare numbers by concatenating their string representations. We ensure that larger concatenated results come first in the merged list. This is done by comparing combinations like `a + b` and `b + a` and placing the larger result first.\n\nAfter merging all parts, we obtain a sorted list where concatenating all numbers forms the largest number. If this result starts with '0', all numbers are zero, so we return \"0\". Otherwise, we return the concatenated result.\n\nFor example, with the list `[3, 30, 34, 5, 9]`, we first split it into `[3, 30]` and `[34, 5, 9]`.\n\nWe recursively divide these segments further until each segment contains a single number. We then merge these single-number segments, comparing concatenated results to determine the order. For example, merging `[3]` and `[30]`, we find `\"330\"` is greater than `\"303\"`, so `\"30\"` should precede `\"3\"`.\n\nMerging all segments with similar comparisons results in the list `[9, 5, 34, 3, 30]`. Concatenating these numbers gives `\"9534330\"`, the largest possible number.\n\n#### Algorithm\n\n- Sort the `nums` array using a custom merge sort to arrange numbers in a way that forms the largest possible concatenated number.\n\n- `mergeSort` function:\n  - If the range of elements to be sorted (`left` to `right`) is a single element, return it as it is already sorted.\n  - Divide the array into two halves (`left` and `right`) by finding the middle index.\n  - Recursively sort the left and right halves.\n  - Merge the sorted halves using the `merge` function.\n\n- `merge` function:\n  - Initialize two indices to iterate over the left and right halves of the array.\n  - Compare elements from the left and right halves based on custom concatenation order (using the `compare` function).\n  - Append the larger element to the sorted array and move the corresponding index.\n  - After processing all elements from one half, append the remaining elements from the other half.\n\n- `compare` function:\n  - Concatenate `firstNum` and `secondNum` in both possible orders and compare them.\n  - Return `true` if `firstNum` should appear before `secondNum` in the final sorted order based on the concatenated result.\n\n- After sorting, concatenate the sorted numbers to form the largest number.\n  - Return \"0\" if the largest number starts with '0' (handles cases where all numbers are zero); otherwise, return the concatenated result.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/4f5VffNf/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4f5VffNf\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the `nums` array.\n\n- Time Complexity: $O(n \\log n)$\n\n    Merge sort divides the array into halves and merges them in $O(n \\log n)$ time. Each merge operation is linear in the size of the array being merged, and the recursive divide-and-conquer approach ensures a logarithmic depth of recursion.\n\n- Space Complexity: $O(n)$\n\n    Merge sort requires additional space for the temporary arrays used during merging. For each recursive call, we use extra space proportional to the size of the array being merged.\n   \n    The depth of the recursion stack is $O(\\log n)$, and the space used per level of recursion for merging is $O(n)$. So, the total space complexity is $O(n)$.\n\n    Creating the final string involves space proportional to the size of the final string, which is $O(n)$.\n\n---\n\n### Approach 4: HeapSort\n\n#### Intuition\n\n\nHeapsort helps us find the largest concatenated number by using a priority queue, which we often call a max heap.\n\nFirst, we need to turn each number into a string. This way, we can compare different concatenations of these strings. We then insert these string representations into a max heap. The max heap will arrange these strings based on our custom comparison function and The heap uses this comparison to decide which string should come first.\n\nSay we have the numbers `[3, 30, 34, 5, 9]`. We start by converting each number to a string, resulting in `[\"3\", \"30\", \"34\", \"5\", \"9\"]`. We insert these strings into the heap. The heap sorts these strings based on which concatenation yields a larger number. \n\nFor instance, comparing `\"30\"` and `\"3\"` involves checking if `\"303\"` is larger than `\"330\"`. Since `\"330\"` is larger, `\"3\"` will be prioritized over `\"30\"` in the heap. After inserting all strings, the heap will arrange them in a way that ensures the largest number comes out first.\n\nNext, we remove elements from the heap one by one and build our result string. By concatenating these strings in the order they come out of the heap, we get the largest possible number. Finally, if the result starts with '0', we return \"0\" because this means all numbers were zeros.\n\n</br>\n\nThe algorithm is visualized below:\n\n!?!../Documents/179/heapsort.json:925,695!?!\n\n#### Algorithm\n\n- Initialize a max heap to store numbers as strings in a custom sorted order, using the `compare` function.\n\n- Initialize a variable `totalLength` to track the total length of all numbers converted to strings.\n\n- Iterate over each number `num` in `nums`:\n  - Convert the integer `num` to a string `strNum`.\n  - Add the length of `strNum` to `totalLength`.\n  - Push `strNum` into the max heap using the custom comparison function to maintain the order.\n\n- Initialize an empty string `result` and reserve space based on `totalLength` for efficiency.\n\n- While the max heap is not empty:\n  - Append the top element (largest string based on custom comparison) from the max heap to `result`.\n  - Pop the top element from the max heap.\n\n- Check if the resulting string is empty or starts with `'0'`:\n  - If true, return `\"0\"` to handle the edge case where the result might be a string of zeros.\n\n- Otherwise, return the final `result` string, which represents the largest possible number.\n\n- `compare` function:\n  - Given two strings `first` and `second`, compare them by concatenating them in two different orders (`first + second` and `second + first`).\n  - Return `true` if `(first + second)` is less than `(second + first)`, ensuring the correct order for the largest number construction.\\\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/VUHJjLZT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VUHJjLZT\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the `nums` array.\n\n- Time Complexity: $O(n \\log n)$\n\n    Converting each integer to a string takes $O(\\log k)$ time per integer, where $k$ is the integer value. If there are $n$ integers, the total time for conversion is $O(n \\log k)$.\n    \n    Inserting each string into the priority queue takes $O(\\log n)$ time per insertion. Since there are $n$ strings, this step contributes $O(n \\log n)$.\n    \n    Extracting elements from the priority queue and concatenating them into the result string takes $O(n \\log n)$ time due to the heap operations and string concatenations.\n\n    Combining these steps, the overall time complexity is dominated by the heap operations, so:\n    \n    Converting integers to strings takes $O(n \\log k)$ time, and inserting each string into the priority queue takes $O(n \\log n)$. Building the result string takes $O(n \\log n)$. Thus, the overall time complexity is $O(n \\log n)$.\n\n- Space Complexity: $O(n)$\n\n    The priority queue stores $n$ strings, each of which can be up to $O(\\log k)$ in length. Hence, the space required for the priority queue is $O(n \\log k)$.\n\n    The result string stores all $n$ integers, so its space complexity is $O(n \\log k)$. Since these are the main contributors to space complexity, the overall space complexity is $O(n \\log k) = O(n)$.\n\n---\n\n### Approach 5: TimSort \n\n#### Intuition\n\nTimSort is a sorting algorithm that combines insertion sort and merge sort.\n\nWe start by dividing the list into small segments called runs. Each run is a segment of the list that is sorted independently using insertion sort. Insertion sort is well-suited for this task because it efficiently handles small or already partially sorted segments. For instance, in our example list `[3, 30, 34, 5, 9]`, TimSort first breaks it into runs. Since the list is small, it might treat the entire list as a single run or split it into smaller manageable runs like `[3, 30]` and `[34, 5, 9]` [Usually runs are not this small but for the sake of this example lets say its 2].\n\n> Minrun is chosen from the range 32 to 64 inclusive, such that the size of the data, divided by minrun, is equal to, or slightly less than, a power of two.\n\nNext, we merge these sorted runs into larger, sorted segments. During the merging phase, we use a custom comparison function to determine the order of numbers based on which concatenated result is larger.\n\nAfter all runs are merged, we get a fully sorted list arranged to form the largest possible number. Finally, we check if the result starts with '0'. If it does, this indicates that all numbers are zeros, so we return \"0\".\n\nConsider the list `[3, 30, 34, 5, 9]`. TimSort starts by sorting small runs like `[3, 30]` and `[34, 5, 9]` using insertion sort. It then merges these runs, comparing concatenated results to determine the correct order. For instance, it would compare `\"330\"` with `\"303\"` and place `\"3\"` before `\"30\"` because `\"330\"` is larger. The final merge step sorts the list to `[9, 5, 34, 3, 30]`. Concatenating these gives us the largest number, `\"9534330\"`.\n\nTimsort aims to optimize the merging process by ensuring that the number of runs is close to a power of two. Merging is most effective when the number of runs is equal to or just under a power of two, while it becomes less efficient when the number of runs exceeds a power of two. To achieve this, Timsort selects the value of `RUN` so that the total number of runs is close to a power of two.\n\n`RUN` is chosen within the range of 32 to 64. It is set so that the total size of the data divided by `RUN` is either equal to or slightly less than a power of two. The method for determining `RUN` involves taking the six most significant bits of the array size, adding one if any of the remaining bits are set, and using this result for `RUN`. This approach accommodates all array sizes, including those smaller than 64. For arrays with 63 or fewer elements, `RUN` is set equal to the array size, effectively reducing Timsort to insertion sort for those smaller arrays.\n\n> Fun fact: Timsort is highly regarded for its efficiency and stability. It is more advanced compared to older algorithms like bubble sort or insertion sort. Invented by Tim Peters in 2002, it was named after him. Timsort is used in Python sort.\n\n#### Algorithm\n\n- Sort the `nums` array using the custom `timSort` algorithm.\n  \n- `timSort` function:\n  - For each small run of size `RUN` (32 elements), call `insertionSort` to sort the subarrays.\n  - After sorting small runs, iteratively merge them using the `merge` function until the entire array is sorted.\n\n- `insertionSort` function:\n  - Iterate through the subarray from `left + 1` to `right`.\n  - For each element, store it in a temporary variable `temp`.\n  - Compare `temp` with its previous elements (from right to left) using the `compare` function:\n    - If the comparison returns `true` (i.e., `temp` should precede the compared element), shift the previous element to the right.\n  - Insert `temp` in its correct position once all comparisons are done.\n\n- `merge` function:\n  - Split the array into two subarrays: `leftArr` (from `left` to `mid`) and `rightArr` (from `mid + 1` to `right`).\n  - Merge the two subarrays back into the original array:\n    - Compare the elements from both subarrays using the `compare` function.\n    - Insert the smaller element into the original array and proceed until both subarrays are fully merged.\n\n- `compare` function:\n  - Convert the two numbers `firstNum` and `secondNum` into strings.\n  - Concatenate them in both possible orders and return `true` if the first concatenation results in a larger number.\n\n- Once `nums` is sorted, concatenate all elements in `nums` to form the `largestNum` string.\n\n- If the first character of `largestNum` is `'0'`, return `\"0\"` to handle the case where all numbers are zero.\n\n- Otherwise, return `largestNum` as the final result.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/2SDuwQiU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"2SDuwQiU\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the `nums` array.\n\n- Time complexity: $O(n \\log n)$\n\n    The main time-consuming operation here is the sorting step using TimSort. Its time complexity is $O(n \\log n)$ in the average and worst cases. \n\n    Specifically:\n    - The insertion sort runs in $O(n^2)$ time on small segments (runs), but since it operates on a limited size of $RUN$, the total cost for insertion sorting all runs is $O(n)$ in practice.\n    - The merge step involves merging pairs of runs and is performed $\\log n$ times, leading to the overall time complexity of $O(n \\log n)$ for TimSort.\n\n    Concatenating the numbers to form the final string has a linear time complexity $O(n)$, but it doesn't affect the overall complexity since $O(n \\log n)$ dominates.\n\n- Space complexity: $O(n)$\n\n    The space complexity is dominated by the space used for temporary storage during merging:\n    - The `leftArr` and `rightArr` vectors in the merge function require $O(n)$ space in total.\n    - The extra space used for the `largestNum` string is $O(n)$.\n\n    Other auxiliary space used in the algorithm, such as variables and function call stacks, is minimal compared to the space required for arrays.\n\n    Thus, the overall space complexity is $O(n)$.\n\n---\n\n</br>\n\n</br>\n\n### Further Thoughts:\n\nYou might be wondering why merging is most effective when the number of runs is equal to or just below a power of two, and why it becomes less efficient when the number of runs exceeds this number.\n\nThe main reason for this is that merging is most balanced when the number of runs is a power of two. In general, if the data is randomly ordered, each run will typically be about the size of `minrun`. When the number of runs matches a power of two, merging operations can proceed in a perfectly balanced manner throughout the process. This balance minimizes the number of comparisons and data movements needed.\n\nIf the number of runs is slightly more than a power of two, the merging process becomes less balanced. This imbalance results in inefficient merges, as you end up with uneven merge sizes, leading to increased comparisons and data movement.\n\nConversely, if the number of runs is slightly fewer than a power of two, the merges remain relatively balanced, although not perfectly. This slight imbalance causes only a minor increase in inefficiency compared to the ideal scenario.\n\nFor example, if you have nine natural runs with lengths of 800, 100, 100, 100, 100, 100, 100, 100, and 100 elements, the merges will still be well-balanced, even though the number of runs is slightly above a power of two.\n\nTim Peters talks about this in his [listsort.txt](https://github.com/python/cpython/blob/main/Objects/listsort.txt) file. He points out that using a `minrun` of 32 isn't always the best choice. For example, if you have 2,112 elements, splitting them into runs of 32 means it will take 7 steps to merge everything. The first 6 runs merge smoothly, but after reaching 2,048 elements, the final merge becomes less efficient. This leads to more comparisons and extra data movement.\n\nNow, if the run size is 33, it will take 6 steps to merge everything: 33, 66(33 * 2), 132(66 * 2), 264(132 * 2), 528(264 * 2), 1,056(528 * 2) and then 2,112(1,056 * 2). But with a run size of 32, you'll need 7 steps: 32, 64, 128, 256, 512, 1,024, 2,048, and then 2,112.\n\n</br>\n\nYou can view the full implementation of TimSort, including all the detailed aspects, in the file located at [https://svn.python.org/projects/python/trunk/Objects/listobject.c](https://svn.python.org/projects/python/trunk/Objects/listobject.c). This implementation was crafted by Tim Peters.\n\n</br>\n\nHere’s a snippet taken from `listobject.c` showing how to determine the minimum run size for a subarray in the Timsort algorithm based on the size of the initial array `n`.\n\n```c\n/* Compute a good value for the minimum run length; natural runs shorter\n * than this are boosted artificially via binary insertion.\n *\n * If n < 64, return n (it's too small to bother with fancy stuff).\n * Else if n is an exact power of 2, return 32.\n * Else return an int k, 32 <= k <= 64, such that n/k is close to, but\n * strictly less than, an exact power of 2.\n *\n * See listsort.txt for more info.\n */\nstatic Py_ssize_t\nmerge_compute_minrun(Py_ssize_t n)\n{\n    Py_ssize_t r = 0;           /* becomes 1 if any 1 bits are shifted off */\n\n    assert(n >= 0);\n    while (n >= 64) {\n        r |= n & 1;\n        n >>= 1;\n    }\n    return n + r;\n}\n```\n\n---",
    "solution_code_python": "\t\t\t\n\nclass LargerStrKey(str):\n  def __lt__(x: str, y: str) -> bool:\n    return x + y > y + x\n\n\nclass Solution:\n  def largestNumber(self, nums: List[int]) -> str:\n    return ''.join(sorted(map(str, nums), key=LargerStrKey)).lstrip('0') or '0'",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String largestNumber(int[] nums) {\n    final String s = Arrays.stream(nums)\n                         .mapToObj(String::valueOf)\n                         .sorted((a, b) -> (b + a).compareTo(a + b))\n                         .collect(Collectors.joining(\"\"));\n    return s.startsWith(\"00\") ? \"0\" : s;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string largestNumber(vector<int>& nums) {\n    string ans;\n\n    sort(begin(nums), end(nums), [](int a, int b) {\n      return to_string(a) + to_string(b) > to_string(b) + to_string(a);\n    });\n\n    for (const int num : nums)\n      ans += to_string(num);\n\n    return ans[0] == '0' ? \"0\" : ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/179.html",
    "category": "Algorithms",
    "acceptance_rate": 41.13761258417327,
    "topics": [
      "Array",
      "String",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 9079,
    "dislikes": 773,
    "similar_questions": "[{\"title\": \"Smallest Value of the Rearranged Number\", \"titleSlug\": \"smallest-value-of-the-rearranged-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Key of the Numbers\", \"titleSlug\": \"find-the-key-of-the-numbers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"713.5K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 713476, \"totalSubmissionRaw\": 1734363, \"acRate\": \"41.1%\"}",
    "title_pt": "Maior Número",
    "description_pt": "<p>Dada uma lista de inteiros não negativos <code>nums</code>, organize-os de forma que formem o maior número possível e retorne-o.</p>\n\n<p>Como o resultado pode ser muito grande, você precisa retornar uma string em vez de um inteiro.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [10,2]\n<strong>Saída:</strong> &quot;210&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,30,34,5,9]\n<strong>Saída:</strong> &quot;9534330&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "180",
    "paidOnly": false,
    "title": "Consecutive Numbers",
    "titleSlug": "consecutive-numbers",
    "url": "https://leetcode.com/problems/consecutive-numbers",
    "description_url": "https://leetcode.com/problems/consecutive-numbers/description/",
    "description": "<p>Table: <code>Logs</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| num         | varchar |\n+-------------+---------+\nIn SQL, id is the primary key for this table.\nid is an autoincrement column starting from 1.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Find all numbers that appear at least three times consecutively.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nLogs table:\n+----+-----+\n| id | num |\n+----+-----+\n| 1  | 1   |\n| 2  | 1   |\n| 3  | 1   |\n| 4  | 2   |\n| 5  | 1   |\n| 6  | 2   |\n| 7  | 2   |\n+----+-----+\n<strong>Output:</strong> \n+-----------------+\n| ConsecutiveNums |\n+-----------------+\n| 1               |\n+-----------------+\n<strong>Explanation:</strong> 1 is the only number that appears consecutively for at least three times.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/consecutive-numbers/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n### Approach: Using `DISTINCT` and `WHERE` clause [Accepted]\n\n**Algorithm**\n\nConsecutive appearing means the Id of the Num are next to each others. Since this problem asks for numbers appearing at least three times consecutively, we can use 3 aliases for this table **Logs**, and then check whether 3 consecutive numbers are all the same.\n\n```sql\nSELECT *\nFROM\n    Logs l1,\n    Logs l2,\n    Logs l3\nWHERE\n    l1.Id = l2.Id - 1\n    AND l2.Id = l3.Id - 1\n    AND l1.Num = l2.Num\n    AND l2.Num = l3.Num\n;\n```\n| Id | Num | Id | Num | Id | Num |\n|----|-----|----|-----|----|-----|\n| 1  | 1   | 2  | 1   | 3  | 1   |\n>Note: The first two columns are from l1, then the next two are from l2, and the last two are from l3.\n\nThen we can select any *Num* column from the above table to get the target data. However, we need to add a keyword `DISTINCT` because it will display a duplicated number if one number appears more than 3 times consecutively.\n\n**MySQL**\n\n```sql\nSELECT DISTINCT\n    l1.Num AS ConsecutiveNums\nFROM\n    Logs l1,\n    Logs l2,\n    Logs l3\nWHERE\n    l1.Id = l2.Id - 1\n    AND l2.Id = l3.Id - 1\n    AND l1.Num = l2.Num\n    AND l2.Num = l3.Num\n;\n```",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/180.html",
    "category": "Database",
    "acceptance_rate": 45.88833534102712,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2374,
    "dislikes": 341,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"547.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 547394, \"totalSubmissionRaw\": 1192891, \"acRate\": \"45.9%\"}",
    "title_pt": "Números Consecutivos",
    "description_pt": "<p>Tabela: <code>Logs</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| num         | varchar |\n+-------------+---------+\nEm SQL, id é a chave primária desta tabela.\nid é uma coluna autoincrementada começando em 1.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Encontre todos os números que aparecem pelo menos três vezes consecutivas.</p>\n\n<p>Retorne a tabela de resultados em <strong>qualquer ordem</strong>.</p>\n\n<p>O&nbsp;formato do resultado é o do exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Logs:\n+----+-----+\n| id | num |\n+----+-----+\n| 1  | 1   |\n| 2  | 1   |\n| 3  | 1   |\n| 4  | 2   |\n| 5  | 1   |\n| 6  | 2   |\n| 7  | 2   |\n+----+-----+\n<strong>Saída:</strong> \n+-----------------+\n| ConsecutiveNums |\n+-----------------+\n| 1               |\n+-----------------+\n<strong>Explicação:</strong> 1 é o único número que aparece consecutivamente por pelo menos três vezes.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "181",
    "paidOnly": false,
    "title": "Employees Earning More Than Their Managers",
    "titleSlug": "employees-earning-more-than-their-managers",
    "url": "https://leetcode.com/problems/employees-earning-more-than-their-managers",
    "description_url": "https://leetcode.com/problems/employees-earning-more-than-their-managers/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| salary      | int     |\n| managerId   | int     |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution&nbsp;to find the employees who earn more than their managers.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+-------+--------+-----------+\n| id | name  | salary | managerId |\n+----+-------+--------+-----------+\n| 1  | Joe   | 70000  | 3         |\n| 2  | Henry | 80000  | 4         |\n| 3  | Sam   | 60000  | Null      |\n| 4  | Max   | 90000  | Null      |\n+----+-------+--------+-----------+\n<strong>Output:</strong> \n+----------+\n| Employee |\n+----------+\n| Joe      |\n+----------+\n<strong>Explanation:</strong> Joe is the only employee who earns more than his manager.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/employees-earning-more-than-their-managers/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/181.html",
    "category": "Database",
    "acceptance_rate": 71.38412336374455,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2773,
    "dislikes": 274,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"806.2K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 806206, \"totalSubmissionRaw\": 1129396, \"acRate\": \"71.4%\"}",
    "title_pt": "Funcionários que Ganham Mais do que Seus Gerentes",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| salary      | int     |\n| managerId   | int     |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução&nbsp;para encontrar os funcionários que ganham mais do que seus gerentes.</p>\n\n<p>Retorne a tabela de შედეგo em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+-------+--------+-----------+\n| id | name  | salary | managerId |\n+----+-------+--------+-----------+\n| 1  | Joe   | 70000  | 3         |\n| 2  | Henry | 80000  | 4         |\n| 3  | Sam   | 60000  | Null      |\n| 4  | Max   | 90000  | Null      |\n+----+-------+--------+-----------+\n<strong>Saída:</strong> \n+----------+\n| Employee |\n+----------+\n| Joe      |\n+----------+\n<strong>Explicação:</strong> Joe é o único funcionário que ganha mais do que seu gerente.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "182",
    "paidOnly": false,
    "title": "Duplicate Emails",
    "titleSlug": "duplicate-emails",
    "url": "https://leetcode.com/problems/duplicate-emails",
    "description_url": "https://leetcode.com/problems/duplicate-emails/description/",
    "description": "<p>Table: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| email       | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains an email. The emails will not contain uppercase letters.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to report all the duplicate emails. Note that it&#39;s guaranteed that the email&nbsp;field is not NULL.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nPerson table:\n+----+---------+\n| id | email   |\n+----+---------+\n| 1  | a@b.com |\n| 2  | c@d.com |\n| 3  | a@b.com |\n+----+---------+\n<strong>Output:</strong> \n+---------+\n| Email   |\n+---------+\n| a@b.com |\n+---------+\n<strong>Explanation:</strong> a@b.com is repeated two times.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/duplicate-emails/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/182.html",
    "category": "Database",
    "acceptance_rate": 72.33058743021044,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2211,
    "dislikes": 76,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"839.2K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 839231, \"totalSubmissionRaw\": 1160270, \"acRate\": \"72.3%\"}",
    "title_pt": "Emails Duplicados",
    "description_pt": "<p>Tabela: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Tipo    |\n+-------------+---------+\n| id          | int     |\n| email       | varchar |\n+-------------+---------+\nid é a chave primária (coluna com valores únicos) desta tabela.\nCada linha desta tabela contém um email. Os emails não conterão letras maiúsculas.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para relatar todos os emails duplicados. Observe que é garantido que o campo&nbsp;email não é NULL.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Person:\n+----+---------+\n| id | email   |\n+----+---------+\n| 1  | a@b.com |\n| 2  | c@d.com |\n| 3  | a@b.com |\n+----+---------+\n<strong>Saída:</strong> \n+---------+\n| Email   |\n+---------+\n| a@b.com |\n+---------+\n<strong>Explicação:</strong> a@b.com é repetido duas vezes.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "183",
    "paidOnly": false,
    "title": "Customers Who Never Order",
    "titleSlug": "customers-who-never-order",
    "url": "https://leetcode.com/problems/customers-who-never-order",
    "description_url": "https://leetcode.com/problems/customers-who-never-order/description/",
    "description": "<p>Table: <code>Customers</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID and name of a customer.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Orders</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| customerId  | int  |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\ncustomerId is a foreign key (reference columns) of the ID from the Customers table.\nEach row of this table indicates the ID of an order and the ID of the customer who ordered it.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find all customers who never order anything.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nCustomers table:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | Joe   |\n| 2  | Henry |\n| 3  | Sam   |\n| 4  | Max   |\n+----+-------+\nOrders table:\n+----+------------+\n| id | customerId |\n+----+------------+\n| 1  | 3          |\n| 2  | 1          |\n+----+------------+\n<strong>Output:</strong> \n+-----------+\n| Customers |\n+-----------+\n| Henry     |\n| Max       |\n+-----------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/customers-who-never-order/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/183.html",
    "category": "Database",
    "acceptance_rate": 70.5646723008105,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2782,
    "dislikes": 143,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"994.8K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 994767, \"totalSubmissionRaw\": 1409720, \"acRate\": \"70.6%\"}",
    "title_pt": "Clientes que Nunca Fazem Pedidos",
    "description_pt": "<p>Tabela: <code>Customers</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID and name of a customer.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Orders</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| customerId  | int  |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\ncustomerId is a foreign key (reference columns) of the ID from the Customers table.\nEach row of this table indicates the ID of an order and the ID of the customer who ordered it.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar todos os clientes que nunca fazem nenhum pedido.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nCustomers table:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | Joe   |\n| 2  | Henry |\n| 3  | Sam   |\n| 4  | Max   |\n+----+-------+\nOrders table:\n+----+------------+\n| id | customerId |\n+----+------------+\n| 1  | 3          |\n| 2  | 1          |\n+----+------------+\n<strong>Saída:</strong> \n+-----------+\n| Customers |\n+-----------+\n| Henry     |\n| Max       |\n+-----------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "184",
    "paidOnly": false,
    "title": "Department Highest Salary",
    "titleSlug": "department-highest-salary",
    "url": "https://leetcode.com/problems/department-highest-salary",
    "description_url": "https://leetcode.com/problems/department-highest-salary/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+--------------+---------+\n| Column Name  | Type    |\n+--------------+---------+\n| id           | int     |\n| name         | varchar |\n| salary       | int     |\n| departmentId | int     |\n+--------------+---------+\nid is the primary key (column with unique values) for this table.\ndepartmentId is a foreign key (reference columns) of the ID from the <code>Department </code>table.\nEach row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Department</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table. It is guaranteed that department name is not <code>NULL.</code>\nEach row of this table indicates the ID of a department and its name.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find employees who have the highest salary in each of the departments.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+-------+--------+--------------+\n| id | name  | salary | departmentId |\n+----+-------+--------+--------------+\n| 1  | Joe   | 70000  | 1            |\n| 2  | Jim   | 90000  | 1            |\n| 3  | Henry | 80000  | 2            |\n| 4  | Sam   | 60000  | 2            |\n| 5  | Max   | 90000  | 1            |\n+----+-------+--------+--------------+\nDepartment table:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | IT    |\n| 2  | Sales |\n+----+-------+\n<strong>Output:</strong> \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT         | Jim      | 90000  |\n| Sales      | Henry    | 80000  |\n| IT         | Max      | 90000  |\n+------------+----------+--------+\n<strong>Explanation:</strong> Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/department-highest-salary/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/184.html",
    "category": "Database",
    "acceptance_rate": 54.480053497873,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2170,
    "dislikes": 195,
    "similar_questions": "[{\"title\": \"Highest Grade For Each Student\", \"titleSlug\": \"highest-grade-for-each-student\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"484.7K\", \"totalSubmission\": \"889.8K\", \"totalAcceptedRaw\": 484734, \"totalSubmissionRaw\": 889750, \"acRate\": \"54.5%\"}",
    "title_pt": "Maior Salário por Departamento",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+--------------+---------+\n| Nome da Coluna  | Tipo    |\n+--------------+---------+\n| id           | int     |\n| name         | varchar |\n| salary       | int     |\n| departmentId | int     |\n+--------------+---------+\nid é a chave primária (coluna com valores únicos) para esta tabela.\ndepartmentId é uma chave estrangeira (colunas de referência) do ID da tabela <code>Department </code>.\nCada linha desta tabela indica o ID, nome e salário de um empregado. Ela também contém o ID de seu departamento.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Department</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Tipo    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid é a chave primária (coluna com valores únicos) para esta tabela. É garantido que o nome do departamento não é <code>NULL.</code>\nCada linha desta tabela indica o ID de um departamento e seu nome.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar os empregados que possuem o maior salário em cada um dos departamentos.</p>\n\n<p>Retorne a tabela de შედეგados em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Employee:\n+----+-------+--------+--------------+\n| id | name  | salary | departmentId |\n+----+-------+--------+--------------+\n| 1  | Joe   | 70000  | 1            |\n| 2  | Jim   | 90000  | 1            |\n| 3  | Henry | 80000  | 2            |\n| 4  | Sam   | 60000  | 2            |\n| 5  | Max   | 90000  | 1            |\n+----+-------+--------+--------------+\nTabela Department:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | IT    |\n| 2  | Sales |\n+----+-------+\n<strong>Saída:</strong> \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT         | Jim      | 90000  |\n| Sales      | Henry    | 80000  |\n| IT         | Max      | 90000  |\n+------------+----------+--------+\n<strong>Explicação:</strong> Max e Jim ambos têm o maior salário no departamento de IT e Henry tem o maior salário no departamento de Sales.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "185",
    "paidOnly": false,
    "title": "Department Top Three Salaries",
    "titleSlug": "department-top-three-salaries",
    "url": "https://leetcode.com/problems/department-top-three-salaries",
    "description_url": "https://leetcode.com/problems/department-top-three-salaries/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+--------------+---------+\n| Column Name  | Type    |\n+--------------+---------+\n| id           | int     |\n| name         | varchar |\n| salary       | int     |\n| departmentId | int     |\n+--------------+---------+\nid is the primary key (column with unique values) for this table.\ndepartmentId is a foreign key (reference column) of the ID from the <code>Department </code>table.\nEach row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Department</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of a department and its name.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>A company&#39;s executives are interested in seeing who earns the most money in each of the company&#39;s departments. A <strong>high earner</strong> in a department is an employee who has a salary in the <strong>top three unique</strong> salaries for that department.</p>\n\n<p>Write a solution to find the employees who are <strong>high earners</strong> in each of the departments.</p>\n\n<p>Return the result table <strong>in any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+----+-------+--------+--------------+\n| id | name  | salary | departmentId |\n+----+-------+--------+--------------+\n| 1  | Joe   | 85000  | 1            |\n| 2  | Henry | 80000  | 2            |\n| 3  | Sam   | 60000  | 2            |\n| 4  | Max   | 90000  | 1            |\n| 5  | Janet | 69000  | 1            |\n| 6  | Randy | 85000  | 1            |\n| 7  | Will  | 70000  | 1            |\n+----+-------+--------+--------------+\nDepartment table:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | IT    |\n| 2  | Sales |\n+----+-------+\n<strong>Output:</strong> \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT         | Max      | 90000  |\n| IT         | Joe      | 85000  |\n| IT         | Randy    | 85000  |\n| IT         | Will     | 70000  |\n| Sales      | Henry    | 80000  |\n| Sales      | Sam      | 60000  |\n+------------+----------+--------+\n<strong>Explanation:</strong> \nIn the IT department:\n- Max earns the highest unique salary\n- Both Randy and Joe earn the second-highest unique salary\n- Will earns the third-highest unique salary\n\nIn the Sales department:\n- Henry earns the highest salary\n- Sam earns the second-highest salary\n- There is no third-highest salary as there are only two employees\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>There are no employees with the <strong>exact</strong> same name, salary <em>and</em> department.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/department-top-three-salaries/solutions/",
    "solution": "​\n<!-- Don't delete this -->\n[TOC]\n​\n# Solution\n​\n---\n​\n## pandas\n\n<!-- h3 for approaches -->\n### Approach 1: Return the First n Rows Using nlargest()\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nFor this problem, we can either identify the top earners first using DataFrame `employee` and then join the DataFrame `department` to get the department name, or join the DataFrame `department` first to get the department name before identifying the top earners. In this approach, we use the latter logic. \n\nIn this step, we can also update the column name in the DataFrame `department` from `name` to `Department` as requested by the final output.\n\n```python\nEmployee_Department = employee.merge(department, left_on='departmentId', right_on='id').rename(columns = {'name_y': 'Department'})\n```\n\nNow we have the employee and department information stored in the same DataFrame: \n\n| id_x | name_x | salary | departmentId | id_y | Department |\n| ---- | ------ | ------ | ------------ | ---- | ---------- |\n| 1    | Joe    | 85000  | 1            | 1    | IT         |\n| 4    | Max    | 90000  | 1            | 1    | IT         |\n| 5    | Janet  | 69000  | 1            | 1    | IT         |\n| 6    | Randy  | 85000  | 1            | 1    | IT         |\n| 7    | Will   | 70000  | 1            | 1    | IT         |\n| 2    | Henry  | 80000  | 2            | 2    | Sales      |\n| 3    | Sam    | 60000  | 2            | 2    | Sales      |\n\nSince the definition of a **high earner** is an employee who has a salary in the top three **unique** salaries for the department, we want to make sure the salary is unique at the department level for later calculation. To do this, we select only the department and salary from the DataFrame created in the last step and drop any duplicated records if existed. \n\n```python\nEmployee_Department = Employee_Department[['Department', 'departmentId', 'salary']].drop_duplicates()\n```\n\nHere's the output after this step:\n\n| Department | departmentId | salary |\n| ---------- | ------------ | ------ |\n| IT         | 1            | 85000  |\n| IT         | 1            | 90000  |\n| IT         | 1            | 69000  |\n| IT         | 1            | 70000  |\n| Sales      | 2            | 80000  |\n| Sales      | 2            | 60000  |\n\nNow we can identify the top 3 unique salaries for each department. We use the function [`nlargest()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.nlargest.html) to get this value. The parameter '3' is passed to the function as it defines the number of rows to return. \n\n```python\ntop_salary = Employee_Department.groupby(['Department', 'departmentId']).salary.nlargest(3).reset_index()\n```\n\n| Department | departmentId | level_2 | salary |\n| ---------- | ------------ | ------- | ------ |\n| IT         | 1            | 1       | 90000  |\n| IT         | 1            | 0       | 85000  |\n| IT         | 1            | 4       | 70000  |\n| Sales      | 2            | 5       | 80000  |\n| Sales      | 2            | 6       | 60000  |\n\n\nNow we only need to identify the employees are in these departments and making the same amount of salary. To do this, we can merge the DataFrame `top_salary`, which contains the top three unique salary for each department, to the DataFrame `employee` on `departmentId` and `salary`, so only the employees that match both criteria will be retained. \n\n```python\ndf = top_salary.merge(employee, on=['departmentId', 'salary'])\n```\n\n| Department | departmentId | level_2 | salary | id | name  |\n| ---------- | ------------ | ------- | ------ | -- | ----- |\n| IT         | 1            | 1       | 90000  | 4  | Max   |\n| IT         | 1            | 0       | 85000  | 1  | Joe   |\n| IT         | 1            | 0       | 85000  | 6  | Randy |\n| IT         | 1            | 4       | 70000  | 7  | Will  |\n| Sales      | 2            | 5       | 80000  | 2  | Henry |\n| Sales      | 2            | 6       | 60000  | 3  | Sam   |\n\nLastly, we clean the DataFrame as per requested by the final output. We keep only the columns needed and rename the columns accordingly.\n\n```python\ndf[['Department', 'name', 'salary']].rename(columns = {'name': 'Employee', 'salary': 'Salary'})\n```\n\n<!-- h4 for sections -->\n#### Implementation\n​<iframe src=\"https://leetcode.com/playground/5nLUgFZZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"276\" name=\"5nLUgFZZ\"></iframe>\n<!-- an empty line to separate approaches -->\n\n\n<!-- h3 for approaches -->\n### Approach 2: Return the First n Rows Using rank()\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nFor this approach, we first identify the top earners from the DataFrame `employee` and then join the DataFrame `department` to get the department name. \n\nTo identify the high earners for each department, we use the function [`rank()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html) to apply dense rank on the column `salary` so we can get the top three **unique** salaries. The parameter `ascending=False` is passed so the salary is sorted from the maximum to the minimum. Within the same step, we can also add the filter to keep only the records with a rank smaller than or equal to 3. \n\n```python\ntop_salary = employee[employee.groupby('departmentId').salary.rank(method='dense', ascending=False) <= 3]\n```\n\nOnly employees who are `high earners` retained in the new DataFrame:\n\n| id | name  | salary | departmentId |\n| -- | ----- | ------ | ------------ |\n| 1  | Joe   | 85000  | 1            |\n| 2  | Henry | 80000  | 2            |\n| 3  | Sam   | 60000  | 2            |\n| 4  | Max   | 90000  | 1            |\n| 6  | Randy | 85000  | 1            |\n| 7  | Will  | 70000  | 1            |\n\nNow we want to `merge` to the DataFrame `department` to get the `name` of the department. In the same step, we can also select only the columns needed for the final output. \n\n```python\nemployee_department = top_salary.merge(department, left_on='departmentId', right_on='id')[['name_y', 'name_x', 'salary']]\n```\n| name_y | name_x | salary |\n| ------ | ------ | ------ |\n| IT     | Joe    | 85000  |\n| IT     | Max    | 90000  |\n| IT     | Randy  | 85000  |\n| IT     | Will   | 70000  |\n| Sales  | Henry  | 80000  |\n| Sales  | Sam    | 60000  |\n\n\nWe are almost there! To get the final output, we need to update the column name as per requested.\n\n```python\nreturn employee_department.rename(columns = {'name_y': 'Department', 'name_x': 'Employee', 'salary': 'Salary'})\n```\n\n<!-- h4 for sections -->\n#### Implementation\n<iframe src=\"https://leetcode.com/playground/WbvUZqck/shared\" frameBorder=\"0\" width=\"100%\" height=\"208\" name=\"WbvUZqck\"></iframe>\n---\n\n## Database\n\n### Approach 1: Return the First n Rows Using Correlated Subquery\n\n<!-- h4 for sections -->\n#### Algorithm\n​<!-- Describe your approach to solving the problem. -->\nWe can build a [correlated subquery](https://dev.mysql.com/doc/refman/8.0/en/correlated-subqueries.html) to identify the top N records from more than one category. Since the correlated subquery is dependent on the main query, the idea behind this approach is to compare the values between the main query and the subquery, so that in the subquery, at most N-1 salaries can be greater than each selected salary from the main query.\n\nTo do this, we first build the main query. In the main query, we can also join the table `Employee` to the table `Department` on `departmentId` to get the `name` of the departments and rename the columns as requested by the final output. \n\n```sql\nSELECT d.name AS 'Department', \n       e1.name AS 'Employee', \n       e1.salary AS 'Salary' \nFROM Employee e1\nJOIN Department d\nON e1.departmentId = d.id \n```\n\nIn the correlated subquery, we select the number of salaries from the same table `Employee`. To compare the salaries between the main query and the subquery, we make sure the department is the same from both queries, but the salary from the subquery is always bigger than the salary from the main query. \n\n```sql\n(\n    SELECT COUNT(DISTINCT e2.salary)\n    FROM Employee e2\n    WHERE e2.salary > e1.salary AND e1.departmentId = e2.departmentId\n)\n```\n\nSince we need to identify the top three high earners in the main query, and the subquery always has larger salaries than the salaries from the main query, the maximum count of the larger salaries in the subquery is two. We add this criteria as a filter to the main query.\n\n<!-- h4 for sections -->\n#### Implementation\n\n```sql\nSELECT d.name AS 'Department', \n       e1.name AS 'Employee', \n       e1.salary AS 'Salary' \nFROM Employee e1\nJOIN Department d\nON e1.departmentId = d.id \nWHERE\n    3 > (SELECT COUNT(DISTINCT e2.salary)\n        FROM Employee e2\n        WHERE e2.salary > e1.salary AND e1.departmentId = e2.departmentId);\n```\n​\n<!-- an empty line to separate approaches -->\n\n<!-- h3 for approaches -->\n### Approach 2: Return the First n Rows Using DENSE_RANK()\n\n<!-- h4 for sections -->\n#### Algorithm\n​<!-- Describe your approach to solving the problem. -->\nUnlike the previous approach that utilized a correlated subquery, in this approach, we sorted the salaries in descending order, ranked employees based on their salaries within the department, and selected only the first 3 employees for the final output.\n\nWe first create a subquery or CTE to rank the employees. Since the definition of a high earner is the employee who has a salary in the top three **unique** salaries for the department, we can use the function `DENSE_RANK()` to avoid the scenario that employees from the same department make the same amount of salary. In this step, we can also join the table `Department` on `departmentId` to get the `name` of the departments and rename the columns for the final output. \n\n```sql\nWITH employee_department AS\n    (\n    SELECT d.id, \n        d.name AS Department, \n        salary AS Salary, \n        e.name AS Employee, \n        DENSE_RANK()OVER(PARTITION BY d.id ORDER BY salary DESC) AS rnk\n    FROM Department d\n    JOIN Employee e\n    ON d.id = e.departmentId\n    )\n```\n\nNow, each employee has a rank based on the `salary` in a descending order for each department. \n\n| id | Department | Salary | Employee | rnk |\n| -- | ---------- | ------ | -------- | --- |\n| 1  | IT         | 90000  | Max      | 1   |\n| 1  | IT         | 85000  | Joe      | 2   |\n| 1  | IT         | 85000  | Randy    | 2   |\n| 1  | IT         | 70000  | Will     | 3   |\n| 1  | IT         | 69000  | Janet    | 4   |\n| 2  | Sales      | 80000  | Henry    | 1   |\n| 2  | Sales      | 60000  | Sam      | 2   |\n\nWith the rank, we can select the high earners. We can add the filter to select employees that have a rank smaller than or equal to 3 in the main query. \n\n```sql\nSELECT Department, Employee, Salary\nFROM employee_department\nWHERE rnk <= 3\n```\n<!-- h4 for sections -->\n#### Implementation\n\n```mysql []\nWITH employee_department AS\n    (\n    SELECT d.id, \n        d.name AS Department, \n        salary AS Salary, \n        e.name AS Employee, \n        DENSE_RANK()OVER(PARTITION BY d.id ORDER BY salary DESC) AS rnk\n    FROM Department d\n    JOIN Employee e\n    ON d.id = e.departmentId\n    )\nSELECT Department, Employee, Salary\nFROM employee_department\nWHERE rnk <= 3\n```\n​\n----\n<!-- an empty line to separate approaches -->",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/185.html",
    "category": "Database",
    "acceptance_rate": 57.4620629721238,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 2308,
    "dislikes": 259,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"481.4K\", \"totalSubmission\": \"837.7K\", \"totalAcceptedRaw\": 481357, \"totalSubmissionRaw\": 837699, \"acRate\": \"57.5%\"}",
    "title_pt": "Os Três Maiores Salários por Departamento",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+--------------+---------+\n| Column Name  | Type    |\n+--------------+---------+\n| id           | int     |\n| name         | varchar |\n| salary       | int     |\n| departmentId | int     |\n+--------------+---------+\nid is the primary key (column with unique values) for this table.\ndepartmentId is a foreign key (reference column) of the ID from the <code>Department </code>table.\nEach row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Department</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of a department and its name.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Os executivos de uma empresa estão interessados em ver quem ganha mais dinheiro em cada um dos departamentos da empresa. Um <strong>alto ganhador</strong> em um departamento é um funcionário que possui um salário entre os <strong>três maiores salários distintos</strong> daquele departamento.</p>\n\n<p>Escreva uma solução para encontrar os funcionários que são <strong>altos ganhadores</strong> em cada um dos departamentos.</p>\n\n<p>Retorne a tabela de resultado <strong>em qualquer ordem</strong>.</p>\n\n<p>O&nbsp;formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+----+-------+--------+--------------+\n| id | name  | salary | departmentId |\n+----+-------+--------+--------------+\n| 1  | Joe   | 85000  | 1            |\n| 2  | Henry | 80000  | 2            |\n| 3  | Sam   | 60000  | 2            |\n| 4  | Max   | 90000  | 1            |\n| 5  | Janet | 69000  | 1            |\n| 6  | Randy | 85000  | 1            |\n| 7  | Will  | 70000  | 1            |\n+----+-------+--------+--------------+\nDepartment table:\n+----+-------+\n| id | name  |\n+----+-------+\n| 1  | IT    |\n| 2  | Sales |\n+----+-------+\n<strong>Saída:</strong> \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT         | Max      | 90000  |\n| IT         | Joe      | 85000  |\n| IT         | Randy    | 85000  |\n| IT         | Will     | 70000  |\n| Sales      | Henry    | 80000  |\n| Sales      | Sam      | 60000  |\n+------------+----------+--------+\n<strong>Explicação:</strong> \nNo departamento de TI:\n- Max ganha o salário distinto mais alto\n- Tanto Randy quanto Joe ganham o segundo maior salário distinto\n- Will ganha o terceiro maior salário distinto\n\nNo departamento de Vendas:\n- Henry ganha o salário mais alto\n- Sam ganha o segundo maior salário\n- Não existe terceiro maior salário, pois há apenas dois funcionários\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>Não há funcionários com exatamente o mesmo nome, salário <em>e</em> departamento.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "187",
    "paidOnly": false,
    "title": "Repeated DNA Sequences",
    "titleSlug": "repeated-dna-sequences",
    "url": "https://leetcode.com/problems/repeated-dna-sequences",
    "description_url": "https://leetcode.com/problems/repeated-dna-sequences/description/",
    "description": "<p>The <strong>DNA sequence</strong> is composed of a series of nucleotides abbreviated as <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p>\n\n<ul>\n\t<li>For example, <code>&quot;ACGAATTCCG&quot;</code> is a <strong>DNA sequence</strong>.</li>\n</ul>\n\n<p>When studying <strong>DNA</strong>, it is useful to identify repeated sequences within the DNA.</p>\n\n<p>Given a string <code>s</code> that represents a <strong>DNA sequence</strong>, return all the <strong><code>10</code>-letter-long</strong> sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n<strong>Output:</strong> [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"AAAAAAAAAAAAA\"\n<strong>Output:</strong> [\"AAAAAAAAAA\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, or <code>&#39;T&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/repeated-dna-sequences/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findRepeatedDnaSequences(self, s: str) -> List[str]:\n    ans = set()\n    seen = set()\n\n    for i in range(len(s) - 9):\n      seq = s[i:i + 10]\n      if seq in seen:\n        ans.add(seq)\n      seen.add(seq)\n\n    return list(ans)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> findRepeatedDnaSequences(String s) {\n    Set<String> ans = new HashSet<>();\n    Set<String> seen = new HashSet<>();\n\n    for (int i = 0; i + 10 <= s.length(); ++i) {\n      final String seq = s.substring(i, i + 10);\n      if (seen.contains(seq))\n        ans.add(seq);\n      seen.add(seq);\n    }\n\n    return new ArrayList<>(ans);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findRepeatedDnaSequences(string s) {\n    unordered_set<string> ans;\n    unordered_set<string_view> seen;\n    const string_view sv(s);\n\n    for (int i = 0; i + 10 <= s.length(); ++i) {\n      if (seen.count(sv.substr(i, 10)))\n        ans.insert(s.substr(i, 10));\n      seen.insert(sv.substr(i, 10));\n    }\n\n    return {begin(ans), end(ans)};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/187.html",
    "category": "Algorithms",
    "acceptance_rate": 51.117029584894816,
    "topics": [
      "Hash Table",
      "String",
      "Bit Manipulation",
      "Sliding Window",
      "Rolling Hash",
      "Hash Function"
    ],
    "hints": [],
    "likes": 3470,
    "dislikes": 553,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"448.3K\", \"totalSubmission\": \"877.1K\", \"totalAcceptedRaw\": 448348, \"totalSubmissionRaw\": 877102, \"acRate\": \"51.1%\"}",
    "title_pt": "Sequências de DNA Repetidas",
    "description_pt": "<p>A <strong>sequência de DNA</strong> é composta por uma série de nucleotídeos abreviados como <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code> e <code>&#39;T&#39;</code>.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;ACGAATTCCG&quot;</code> é uma <strong>sequência de DNA</strong>.</li>\n</ul>\n\n<p>Ao estudar <strong>DNA</strong>, é útil identificar sequências repetidas dentro do DNA.</p>\n\n<p>Dada uma string <code>s</code> que representa uma <strong>sequência de DNA</strong>, retorne todas as sequências <strong>com <code>10</code> letras de comprimento</strong> (substrings) que ocorrem mais de uma vez em uma molécula de DNA. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n<strong>Saída:</strong> [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"AAAAAAAAAAAAA\"\n<strong>Saída:</strong> [\"AAAAAAAAAA\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> é igual a <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code> ou <code>&#39;T&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "188",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock IV",
    "titleSlug": "best-time-to-buy-and-sell-stock-iv",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/",
    "description": "<p>You are given an integer array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>k</code>.</p>\n\n<p>Find the maximum profit you can achieve. You may complete at most <code>k</code> transactions: i.e. you may buy at most <code>k</code> times and sell at most <code>k</code> times.</p>\n\n<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 2, prices = [2,4,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 2, prices = [3,2,6,5,0,3]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 100</code></li>\n\t<li><code>1 &lt;= prices.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, k: int, prices: List[int]) -> int:\n    if k >= len(prices) // 2:\n      sell = 0\n      hold = -math.inf\n\n      for price in prices:\n        sell = max(sell, hold + price)\n        hold = max(hold, sell - price)\n\n      return sell\n\n    sell = [0] * (k + 1)\n    hold = [-math.inf] * (k + 1)\n\n    for price in prices:\n      for i in range(k, 0, -1):\n        sell[i] = max(sell[i], hold[i] + price)\n        hold[i] = max(hold[i], sell[i - 1] - price)\n\n    return sell[k]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int k, int[] prices) {\n    if (k >= prices.length / 2) {\n      int sell = 0;\n      int hold = Integer.MIN_VALUE;\n\n      for (final int price : prices) {\n        sell = Math.max(sell, hold + price);\n        hold = Math.max(hold, sell - price);\n      }\n\n      return sell;\n    }\n\n    int[] sell = new int[k + 1];\n    int[] hold = new int[k + 1];\n    Arrays.fill(hold, Integer.MIN_VALUE);\n\n    for (final int price : prices)\n      for (int i = k; i > 0; --i) {\n        sell[i] = Math.max(sell[i], hold[i] + price);\n        hold[i] = Math.max(hold[i], sell[i - 1] - price);\n      }\n\n    return sell[k];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(int k, vector<int>& prices) {\n    if (k >= prices.size() / 2) {\n      int sell = 0;\n      int hold = INT_MIN;\n\n      for (const int price : prices) {\n        sell = max(sell, hold + price);\n        hold = max(hold, sell - price);\n      }\n\n      return sell;\n    }\n\n    vector<int> sell(k + 1);\n    vector<int> hold(k + 1, INT_MIN);\n\n    for (const int price : prices)\n      for (int i = k; i > 0; --i) {\n        sell[i] = max(sell[i], hold[i] + price);\n        hold[i] = max(hold[i], sell[i - 1] - price);\n      }\n\n    return sell[k];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/188.html",
    "category": "Algorithms",
    "acceptance_rate": 46.665578615452155,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 7710,
    "dislikes": 218,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock\", \"titleSlug\": \"best-time-to-buy-and-sell-stock\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock II\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock III\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Profit From Trading Stocks\", \"titleSlug\": \"maximum-profit-from-trading-stocks\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"580.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 580424, \"totalSubmissionRaw\": 1243796, \"acRate\": \"46.7%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ações IV",
    "description_pt": "<p>Você recebe um array de inteiros <code>prices</code> onde <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia, e um inteiro <code>k</code>.</p>\n\n<p>Encontre o lucro máximo que você pode obter. Você pode completar no máximo <code>k</code> transações: ou seja, você pode comprar no máximo <code>k</code> vezes e vender no máximo <code>k</code> vezes.</p>\n\n<p><strong>Nota:</strong> Você não pode participar de múltiplas transações simultaneamente (isto é, você deve vender a ação antes de comprá-la novamente).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 2, prices = [2,4,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Compre no dia 1 (price = 2) e venda no dia 2 (price = 4), lucro = 4-2 = 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 2, prices = [3,2,6,5,0,3]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Compre no dia 2 (price = 2) e venda no dia 3 (price = 6), lucro = 6-2 = 4. Então compre no dia 5 (price = 0) e venda no dia 6 (price = 3), lucro = 3-0 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 100</code></li>\n\t<li><code>1 &lt;= prices.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "189",
    "paidOnly": false,
    "title": "Rotate Array",
    "titleSlug": "rotate-array",
    "url": "https://leetcode.com/problems/rotate-array",
    "description_url": "https://leetcode.com/problems/rotate-array/description/",
    "description": "<p>Given an integer array <code>nums</code>, rotate the array to the right by <code>k</code> steps, where <code>k</code> is non-negative.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,5,6,7], k = 3\n<strong>Output:</strong> [5,6,7,1,2,3,4]\n<strong>Explanation:</strong>\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,-100,3,99], k = 2\n<strong>Output:</strong> [3,99,-1,-100]\n<strong>Explanation:</strong> \nrotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Try to come up with as many solutions as you can. There are at least <strong>three</strong> different ways to solve this problem.</li>\n\t<li>Could you do it in-place with <code>O(1)</code> extra space?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/rotate-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rotate(self, nums: List[int], k: int) -> None:\n    k %= len(nums)\n    self.reverse(nums, 0, len(nums) - 1)\n    self.reverse(nums, 0, k - 1)\n    self.reverse(nums, k, len(nums) - 1)\n\n  def reverse(self, nums: List[int], l: int, r: int) -> None:\n    while l < r:\n      nums[l], nums[r] = nums[r], nums[l]\n      l += 1\n      r -= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void rotate(int[] nums, int k) {\n    k %= nums.length;\n    reverse(nums, 0, nums.length - 1);\n    reverse(nums, 0, k - 1);\n    reverse(nums, k, nums.length - 1);\n  }\n\n  private void reverse(int[] nums, int l, int r) {\n    while (l < r)\n      swap(nums, l++, r--);\n  }\n\n  private void swap(int[] nums, int l, int r) {\n    final int temp = nums[l];\n    nums[l] = nums[r];\n    nums[r] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void rotate(vector<int>& nums, int k) {\n    k %= nums.size();\n    reverse(nums, 0, nums.size() - 1);\n    reverse(nums, 0, k - 1);\n    reverse(nums, k, nums.size() - 1);\n  }\n\n private:\n  void reverse(vector<int>& nums, int l, int r) {\n    while (l < r)\n      swap(nums[l++], nums[r--]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/189.html",
    "category": "Algorithms",
    "acceptance_rate": 42.826360703420605,
    "topics": [
      "Array",
      "Math",
      "Two Pointers"
    ],
    "hints": [
      "The easiest solution would use additional memory and that is perfectly fine.",
      "The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays.",
      "One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example.",
      "The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on <b>cyclic-dependencies</b> between elements."
    ],
    "likes": 19376,
    "dislikes": 2098,
    "similar_questions": "[{\"title\": \"Rotate List\", \"titleSlug\": \"rotate-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Reverse Words in a String II\", \"titleSlug\": \"reverse-words-in-a-string-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Make K-Subarray Sums Equal\", \"titleSlug\": \"make-k-subarray-sums-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Matching Indices After Right Shifts\", \"titleSlug\": \"maximum-number-of-matching-indices-after-right-shifts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.1M\", \"totalSubmission\": \"7.2M\", \"totalAcceptedRaw\": 3090793, \"totalSubmissionRaw\": 7217046, \"acRate\": \"42.8%\"}",
    "title_pt": "Rotacionar Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, rotacione o array para a direita por <code>k</code> passos, onde <code>k</code> é não negativo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,5,6,7], k = 3\n<strong>Saída:</strong> [5,6,7,1,2,3,4]\n<strong>Explicação:</strong>\nrotacionar 1 passo para a direita: [7,1,2,3,4,5,6]\nrotacionar 2 passos para a direita: [6,7,1,2,3,4,5]\nrotacionar 3 passos para a direita: [5,6,7,1,2,3,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,-100,3,99], k = 2\n<strong>Saída:</strong> [3,99,-1,-100]\n<strong>Explicação:</strong> \nrotacionar 1 passo para a direita: [99,-1,-100,3]\nrotacionar 2 passos para a direita: [3,99,-1,-100]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Tente criar o maior número possível de soluções. Existem pelo menos <strong>três</strong> maneiras diferentes de resolver este problema.</li>\n\t<li>Você conseguiria fazer isso in-place com <code>O(1)</code> de espaço extra?</li>\n</ul>",
    "hints_pt": [
      "Dica 1: A solução mais সহজ? O ideal seria usar memória adicional, e isso é perfeitamente aceitável.",
      "Dica 2: O verdadeiro truque surge quando tentamos resolver este problema sem usar memória adicional. Isso significa que você precisa usar o array original de alguma forma para mover os elementos. Agora, poderíamos colocar cada elemento em sua posição original e deslocar todos os elementos ao redor para ajustá-lo, mas isso seria caro demais e muito provavelmente causaria time out em arrays de entrada maiores.",
      "Dica 3: Uma linha de raciocínio se baseia em inverter o array (ou partes dele) para obter o resultado desejado. Pense em como a inversão poderia potencialmente nos ajudar usando um exemplo.",
      "Dica 4: A outra linha de raciocínio é um pouco mais complicada, mas essencialmente se baseia na ideia de colocar cada elemento em sua posição original enquanto acompanhamos o elemento originalmente presente nessa posição. Basicamente, a cada passo, colocamos um elemento em seu lugar correto e mantemos o controle do elemento que já estava lá ou daquele que está sendo sobrescrito em uma variável adicional. Não podemos fazer isso em uma única passagem linear, e a ideia aqui se baseia em <b>dependências cíclicas</b> entre elementos."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "190",
    "paidOnly": false,
    "title": "Reverse Bits",
    "titleSlug": "reverse-bits",
    "url": "https://leetcode.com/problems/reverse-bits",
    "description_url": "https://leetcode.com/problems/reverse-bits/description/",
    "description": "<p>Reverse bits of a given 32 bits unsigned integer.</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer&#39;s internal binary representation is the same, whether it is signed or unsigned.</li>\n\t<li>In Java, the compiler represents the signed integers using <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" target=\"_blank\">2&#39;s complement notation</a>. Therefore, in <strong class=\"example\">Example 2</strong> above, the input represents the signed integer <code>-3</code> and the output represents the signed integer <code>-1073741825</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 00000010100101000001111010011100\n<strong>Output:</strong>    964176192 (00111001011110000010100101000000)\n<strong>Explanation: </strong>The input binary string <strong>00000010100101000001111010011100</strong> represents the unsigned integer 43261596, so return 964176192 which its binary representation is <strong>00111001011110000010100101000000</strong>.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 11111111111111111111111111111101\n<strong>Output:</strong>   3221225471 (10111111111111111111111111111111)\n<strong>Explanation: </strong>The input binary string <strong>11111111111111111111111111111101</strong> represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is <strong>10111111111111111111111111111111</strong>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The input must be a <strong>binary string</strong> of length <code>32</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> If this function is called many times, how would you optimize it?</p>\n",
    "solution_url": "https://leetcode.com/problems/reverse-bits/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseBits(self, n: int) -> int:\n    ans = 0\n\n    for i in range(32):\n      if n >> i & 1:\n        ans |= 1 << 31 - i\n\n    return ans",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  // You need treat n as an unsigned value\n  public int reverseBits(int n) {\n    int ans = 0;\n\n    for (int i = 0; i < 32; ++i)\n      if ((n >> i & 1) == 1)\n        ans |= 1 << 31 - i;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  uint32_t reverseBits(uint32_t n) {\n    uint32_t ans = 0;\n\n    for (int i = 0; i < 32; ++i)\n      if (n >> i & 1)\n        ans |= 1 << 31 - i;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/190.html",
    "category": "Algorithms",
    "acceptance_rate": 62.87848775407622,
    "topics": [
      "Divide and Conquer",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 5344,
    "dislikes": 1581,
    "similar_questions": "[{\"title\": \"Reverse Integer\", \"titleSlug\": \"reverse-integer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"A Number After a Double Reversal\", \"titleSlug\": \"a-number-after-a-double-reversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"992K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 991984, \"totalSubmissionRaw\": 1577623, \"acRate\": \"62.9%\"}",
    "title_pt": "Inverter Bits",
    "description_pt": "<p>Inverta os bits de um inteiro sem sinal de 32 bits fornecido.</p>\n\n<p><strong>Nota:</strong></p>\n\n<ul>\n\t<li>Observe que, em algumas linguagens, como Java, não existe tipo de inteiro sem sinal. Nesse caso, tanto a entrada quanto a saída serão fornecidas como um tipo de inteiro com sinal. Isso não deve afetar sua implementação, pois a representação binária interna do inteiro é a mesma, seja ele com sinal ou sem sinal.</li>\n\t<li>Em Java, o compilador representa os inteiros com sinal usando a <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" target=\"_blank\">notação de complemento de dois</a>. Portanto, no <strong class=\"example\">Exemplo 2</strong> acima, a entrada representa o inteiro com sinal <code>-3</code> e a saída representa o inteiro com sinal <code>-1073741825</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 00000010100101000001111010011100\n<strong>Saída:</strong>    964176192 (00111001011110000010100101000000)\n<strong>Explicação: </strong>A string binária de entrada <strong>00000010100101000001111010011100</strong> representa o inteiro sem sinal 43261596, então retorne 964176192 cuja representação binária é <strong>00111001011110000010100101000000</strong>.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 11111111111111111111111111111101\n<strong>Saída:</strong>   3221225471 (10111111111111111111111111111111)\n<strong>Explicação: </strong>A string binária de entrada <strong>11111111111111111111111111111101</strong> representa o inteiro sem sinal 4294967293, então retorne 3221225471 cuja representação binária é <strong>10111111111111111111111111111111</strong>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>A entrada deve ser uma <strong>string binária</strong> de comprimento <code>32</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Se esta função for chamada muitas vezes, como você a otimizaria?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "191",
    "paidOnly": false,
    "title": "Number of 1 Bits",
    "titleSlug": "number-of-1-bits",
    "url": "https://leetcode.com/problems/number-of-1-bits",
    "description_url": "https://leetcode.com/problems/number-of-1-bits/description/",
    "description": "<p>Given a positive integer <code>n</code>, write a function that returns the number of <span data-keyword=\"set-bit\">set bits</span> in its binary representation (also known as the <a href=\"http://en.wikipedia.org/wiki/Hamming_weight\" target=\"_blank\">Hamming weight</a>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">n = 11</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">3</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The input binary string <strong>1011</strong> has a total of three set bits.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">n = 128</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">1</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The input binary string <strong>10000000</strong> has a total of one set bit.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">n = 2147483645</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">30</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The input binary string <strong>1111111111111111111111111111101</strong> has a total of thirty set bits.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> If this function is called many times, how would you optimize it?",
    "solution_url": "https://leetcode.com/problems/number-of-1-bits/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def hammingWeight(self, n: int) -> int:\n    ans = 0\n\n    for i in range(32):\n      if (n >> i) & 1:\n        ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  // You need to treat n as an unsigned value\n  public int hammingWeight(int n) {\n    int ans = 0;\n\n    for (int i = 0; i < 32; ++i)\n      if (((n >> i) & 1) == 1)\n        ++ans;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int hammingWeight(uint32_t n) {\n    int ans = 0;\n\n    for (int i = 0; i < 32; ++i)\n      if ((n >> i) & 1)\n        ++ans;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/191.html",
    "category": "Algorithms",
    "acceptance_rate": 74.25910231449187,
    "topics": [
      "Divide and Conquer",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 6814,
    "dislikes": 1347,
    "similar_questions": "[{\"title\": \"Reverse Bits\", \"titleSlug\": \"reverse-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Counting Bits\", \"titleSlug\": \"counting-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Watch\", \"titleSlug\": \"binary-watch\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Hamming Distance\", \"titleSlug\": \"hamming-distance\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Number with Alternating Bits\", \"titleSlug\": \"binary-number-with-alternating-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Prime Number of Set Bits in Binary Representation\", \"titleSlug\": \"prime-number-of-set-bits-in-binary-representation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Convert Date to Binary\", \"titleSlug\": \"convert-date-to-binary\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1783084, \"totalSubmissionRaw\": 2401168, \"acRate\": \"74.3%\"}",
    "title_pt": "Número de Bits 1",
    "description_pt": "<p>Dado um inteiro positivo <code>n</code>, escreva uma função que retorne o número de <span data-keyword=\"set-bit\">bits definidos</span> em sua representação binária (também conhecido como o <a href=\"http://en.wikipedia.org/wiki/Hamming_weight\" target=\"_blank\">peso de Hamming</a>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">n = 11</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">3</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A string binária de entrada <strong>1011</strong> possui um total de três bits definidos.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">n = 128</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">1</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A string binária de entrada <strong>10000000</strong> possui um total de um bit definido.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">n = 2147483645</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">30</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A string binária de entrada <strong>1111111111111111111111111111101</strong> possui um total de trinta bits definidos.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Se esta função for chamada muitas vezes, como você a otimizaria?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "192",
    "paidOnly": false,
    "title": "Word Frequency",
    "titleSlug": "word-frequency",
    "url": "https://leetcode.com/problems/word-frequency",
    "description_url": "https://leetcode.com/problems/word-frequency/description/",
    "description": "<p>Write a bash script to calculate the <span data-keyword=\"frequency-textfile\">frequency</span> of each word in a text file <code>words.txt</code>.</p>\n\n<p>For simplicity sake, you may assume:</p>\n\n<ul>\n\t<li><code>words.txt</code> contains only lowercase characters and space <code>&#39; &#39;</code> characters.</li>\n\t<li>Each word must consist of lowercase characters only.</li>\n\t<li>Words are separated by one or more whitespace characters.</li>\n</ul>\n\n<p><strong class=\"example\">Example:</strong></p>\n\n<p>Assume that <code>words.txt</code> has the following content:</p>\n\n<pre>\nthe day is sunny the the\nthe sunny is is\n</pre>\n\n<p>Your script should output the following, sorted by descending frequency:</p>\n\n<pre>\nthe 4\nis 3\nsunny 2\nday 1\n</pre>\n\n<p><b>Note:</b></p>\n\n<ul>\n\t<li>Don&#39;t worry about handling ties, it is guaranteed that each word&#39;s frequency count is unique.</li>\n\t<li>Could you write it in one-line using <a href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html\">Unix pipes</a>?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-frequency/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/192.html",
    "category": "Shell",
    "acceptance_rate": 27.112954617970114,
    "topics": [
      "Shell"
    ],
    "hints": [],
    "likes": 558,
    "dislikes": 309,
    "similar_questions": "[{\"title\": \"Top K Frequent Elements\", \"titleSlug\": \"top-k-frequent-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"62K\", \"totalSubmission\": \"228.8K\", \"totalAcceptedRaw\": 62032, \"totalSubmissionRaw\": 228791, \"acRate\": \"27.1%\"}",
    "title_pt": "Frequência de Palavras",
    "description_pt": "<p>Escreva um script bash para calcular a <span data-keyword=\"frequency-textfile\">frequência</span> de cada palavra em um arquivo de texto <code>words.txt</code>.</p>\n\n<p>Para simplificar, você pode assumir:</p>\n\n<ul>\n\t<li><code>words.txt</code> contém apenas caracteres minúsculos e caracteres de espaço <code>&#39; &#39;</code>.</li>\n\t<li>Cada palavra deve consistir apenas de caracteres minúsculos.</li>\n\t<li>As palavras são separadas por um ou mais caracteres de espaço em branco.</li>\n</ul>\n\n<p><strong class=\"example\">Exemplo:</strong></p>\n\n<p>Suponha que <code>words.txt</code> tenha o seguinte conteúdo:</p>\n\n<pre>\nthe day is sunny the the\nthe sunny is is\n</pre>\n\n<p>Seu script deve produzir o seguinte, ordenado por frequência decrescente:</p>\n\n<pre>\nthe 4\nis 3\nsunny 2\nday 1\n</pre>\n\n<p><b>Nota:</b></p>\n\n<ul>\n\t<li>Não se preocupe com o tratamento de empates, é garantido que a contagem de frequência de cada palavra é única.</li>\n\t<li>Você conseguiria escrevê-lo em uma única linha usando <a href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-4.html\">pipes Unix</a>?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "193",
    "paidOnly": false,
    "title": "Valid Phone Numbers",
    "titleSlug": "valid-phone-numbers",
    "url": "https://leetcode.com/problems/valid-phone-numbers",
    "description_url": "https://leetcode.com/problems/valid-phone-numbers/description/",
    "description": "<p>Given a text file <code>file.txt</code> that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.</p>\n\n<p>You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)</p>\n\n<p>You may also assume each line in the text file must not contain leading or trailing white spaces.</p>\n\n<p><strong class=\"example\">Example:</strong></p>\n\n<p>Assume that <code>file.txt</code> has the following content:</p>\n\n<pre>\n987-123-4567\n123 456 7890\n(123) 456-7890\n</pre>\n\n<p>Your script should output the following valid phone numbers:</p>\n\n<pre>\n987-123-4567\n(123) 456-7890\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/valid-phone-numbers/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/193.html",
    "category": "Shell",
    "acceptance_rate": 27.302842345659645,
    "topics": [
      "Shell"
    ],
    "hints": [],
    "likes": 453,
    "dislikes": 974,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"102.7K\", \"totalSubmission\": \"376.1K\", \"totalAcceptedRaw\": 102695, \"totalSubmissionRaw\": 376133, \"acRate\": \"27.3%\"}",
    "title_pt": "Números de Telefone Válidos",
    "description_pt": "<p>Dado um arquivo de texto <code>file.txt</code> que contém uma lista de números de telefone (um por linha), escreva um script bash de uma única linha para imprimir todos os números de telefone válidos.</p>\n\n<p>Você pode assumir que um número de telefone válido deve aparecer em um dos dois formatos a seguir: (xxx) xxx-xxxx ou xxx-xxx-xxxx. (x significa um dígito)</p>\n\n<p>Você também pode assumir que cada linha no arquivo de texto não deve conter espaços em branco à esquerda ou à direita.</p>\n\n<p><strong class=\"example\">Exemplo:</strong></p>\n\n<p>Suponha que <code>file.txt</code> tenha o seguinte conteúdo:</p>\n\n<pre>\n987-123-4567\n123 456 7890\n(123) 456-7890\n</pre>\n\n<p>Seu script deve produzir os seguintes números de telefone válidos:</p>\n\n<pre>\n987-123-4567\n(123) 456-7890\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "194",
    "paidOnly": false,
    "title": "Transpose File",
    "titleSlug": "transpose-file",
    "url": "https://leetcode.com/problems/transpose-file",
    "description_url": "https://leetcode.com/problems/transpose-file/description/",
    "description": "<p>Given a text file <code>file.txt</code>, transpose its content.</p>\n\n<p>You may assume that each row has the same number of columns, and each field is separated by the <code>&#39; &#39;</code> character.</p>\n\n<p><strong class=\"example\">Example:</strong></p>\n\n<p>If <code>file.txt</code> has the following content:</p>\n\n<pre>\nname age\nalice 21\nryan 30\n</pre>\n\n<p>Output the following:</p>\n\n<pre>\nname alice ryan\nage 21 30\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/transpose-file/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/194.html",
    "category": "Shell",
    "acceptance_rate": 28.315976321012915,
    "topics": [
      "Shell"
    ],
    "hints": [],
    "likes": 155,
    "dislikes": 288,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"32.4K\", \"totalSubmission\": \"114.4K\", \"totalAcceptedRaw\": 32383, \"totalSubmissionRaw\": 114363, \"acRate\": \"28.3%\"}",
    "title_pt": "Transpor Arquivo",
    "description_pt": "<p>Dado um arquivo de texto <code>file.txt</code>, transpose seu conteúdo.</p>\n\n<p>Você pode assumir que cada linha tem o mesmo número de colunas, e que cada campo é separado pelo caractere <code>&#39; &#39;</code>.</p>\n\n<p><strong class=\"example\">Exemplo:</strong></p>\n\n<p>Se <code>file.txt</code> tiver o seguinte conteúdo:</p>\n\n<pre>\nname age\nalice 21\nryan 30\n</pre>\n\n<p>Produza a seguinte saída:</p>\n\n<pre>\nname alice ryan\nage 21 30\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "195",
    "paidOnly": false,
    "title": "Tenth Line",
    "titleSlug": "tenth-line",
    "url": "https://leetcode.com/problems/tenth-line",
    "description_url": "https://leetcode.com/problems/tenth-line/description/",
    "description": "<p>Given a text file&nbsp;<code>file.txt</code>, print&nbsp;just the 10th line of the&nbsp;file.</p>\r\n\r\n<p><strong class=\"example\">Example:</strong></p>\r\n\r\n<p>Assume that <code>file.txt</code> has the following content:</p>\r\n\r\n<pre>\r\nLine 1\r\nLine 2\r\nLine 3\r\nLine 4\r\nLine 5\r\nLine 6\r\nLine 7\r\nLine 8\r\nLine 9\r\nLine 10\r\n</pre>\r\n\r\n<p>Your script should output the tenth line, which is:</p>\r\n\r\n<pre>\r\nLine 10\r\n</pre>\r\n\r\n<div class=\"spoilers\"><b>Note:</b><br />\r\n1. If the file contains less than 10 lines, what should you output?<br />\r\n2. There&#39;s at least three different solutions. Try to explore all possibilities.</div>\r\n",
    "solution_url": "https://leetcode.com/problems/tenth-line/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/195.html",
    "category": "Shell",
    "acceptance_rate": 34.43131533380363,
    "topics": [
      "Shell"
    ],
    "hints": [],
    "likes": 407,
    "dislikes": 477,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"128.9K\", \"totalSubmission\": \"374.2K\", \"totalAcceptedRaw\": 128853, \"totalSubmissionRaw\": 374232, \"acRate\": \"34.4%\"}",
    "title_pt": "Décima Linha",
    "description_pt": "<p>Dado um arquivo de texto&nbsp;<code>file.txt</code>, imprima&nbsp;apenas a 10ª linha do&nbsp;arquivo.</p>\n\n<p><strong class=\"example\">Exemplo:</strong></p>\n\n<p>Suponha que <code>file.txt</code> tenha o seguinte conteúdo:</p>\n\n<pre>\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10\n</pre>\n\n<p>Seu script deve produzir a décima linha, que é:</p>\n\n<pre>\nLine 10\n</pre>\n\n<div class=\"spoilers\"><b>Nota:</b><br />\n1. Se o arquivo contiver menos de 10 linhas, o que você deve produzir?<br />\n2. Há pelo menos três soluções diferentes. Tente explorar todas as possibilidades.</div>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "196",
    "paidOnly": false,
    "title": "Delete Duplicate Emails",
    "titleSlug": "delete-duplicate-emails",
    "url": "https://leetcode.com/problems/delete-duplicate-emails",
    "description_url": "https://leetcode.com/problems/delete-duplicate-emails/description/",
    "description": "<p>Table: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| email       | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains an email. The emails will not contain uppercase letters.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to<strong> delete</strong> all duplicate emails, keeping only one unique email with the smallest <code>id</code>.</p>\n\n<p>For SQL users, please note that you are supposed to write a <code>DELETE</code> statement and not a <code>SELECT</code> one.</p>\n\n<p>For Pandas users, please note that you are supposed to modify <code>Person</code> in place.</p>\n\n<p>After running your script, the answer shown is the <code>Person</code> table. The driver will first compile and run your piece of code and then show the <code>Person</code> table. The final order of the <code>Person</code> table <strong>does not matter</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nPerson table:\n+----+------------------+\n| id | email            |\n+----+------------------+\n| 1  | john@example.com |\n| 2  | bob@example.com  |\n| 3  | john@example.com |\n+----+------------------+\n<strong>Output:</strong> \n+----+------------------+\n| id | email            |\n+----+------------------+\n| 1  | john@example.com |\n| 2  | bob@example.com  |\n+----+------------------+\n<strong>Explanation:</strong> john@example.com is repeated two times. We keep the row with the smallest Id = 1.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/delete-duplicate-emails/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/196.html",
    "category": "Database",
    "acceptance_rate": 64.15613928708304,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1809,
    "dislikes": 372,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"713.1K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 713114, \"totalSubmissionRaw\": 1111530, \"acRate\": \"64.2%\"}",
    "title_pt": "Excluir E-mails Duplicados",
    "description_pt": "<p>Tabela: <code>Person</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| email       | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains an email. The emails will not contain uppercase letters.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para <strong>excluir</strong> todos os e-mails duplicados, mantendo apenas um e-mail único com o menor <code>id</code>.</p>\n\n<p>Para usuários de SQL, observe que você deve escrever uma instrução <code>DELETE</code> e não uma de <code>SELECT</code>.</p>\n\n<p>Para usuários de Pandas, observe que você deve modificar <code>Person</code> no local.</p>\n\n<p>Após executar seu script, a resposta exibida é a tabela <code>Person</code>. O driver primeiro compilará e executará sua parte de código e então mostrará a tabela <code>Person</code>. A ordem final da tabela <code>Person</code> <strong>não importa</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nPerson table:\n+----+------------------+\n| id | email            |\n+----+------------------+\n| 1  | john@example.com |\n| 2  | bob@example.com  |\n| 3  | john@example.com |\n+----+------------------+\n<strong>Saída:</strong> \n+----+------------------+\n| id | email            |\n+----+------------------+\n| 1  | john@example.com |\n| 2  | bob@example.com  |\n+----+------------------+\n<strong>Explicação:</strong> john@example.com se repete duas vezes. Mantemos a linha com o menor Id = 1.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "197",
    "paidOnly": false,
    "title": "Rising Temperature",
    "titleSlug": "rising-temperature",
    "url": "https://leetcode.com/problems/rising-temperature",
    "description_url": "https://leetcode.com/problems/rising-temperature/description/",
    "description": "<p>Table: <code>Weather</code></p>\n\n<pre>\n+---------------+---------+\n| Column Name   | Type    |\n+---------------+---------+\n| id            | int     |\n| recordDate    | date    |\n| temperature   | int     |\n+---------------+---------+\nid is the column with unique values for this table.\nThere are no different rows with the same recordDate.\nThis table contains information about the temperature on a certain day.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find all dates&#39; <code>id</code> with higher temperatures compared to its previous dates (yesterday).</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nWeather table:\n+----+------------+-------------+\n| id | recordDate | temperature |\n+----+------------+-------------+\n| 1  | 2015-01-01 | 10          |\n| 2  | 2015-01-02 | 25          |\n| 3  | 2015-01-03 | 20          |\n| 4  | 2015-01-04 | 30          |\n+----+------------+-------------+\n<strong>Output:</strong> \n+----+\n| id |\n+----+\n| 2  |\n| 4  |\n+----+\n<strong>Explanation:</strong> \nIn 2015-01-02, the temperature was higher than the previous day (10 -&gt; 25).\nIn 2015-01-04, the temperature was higher than the previous day (20 -&gt; 30).\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/rising-temperature/solutions/",
    "solution": "[TOC]\n\n# Solution\n---\n\n### Overview\n\n**Problem Statement Reference**\n> Write a solution to find all dates' Id with higher temperatures compared to its previous dates (yesterday). Return the result table in any order.\n\nLet's further elaborate on the given example to deepen our understanding of the problem at hand.\n\nIf we conduct a time series analysis of the temperature data, we would notice distinct points where there is a rise in temperature compared to the previous day. This phenomenon is precisely what we are interested in identifying.\n\nBy analyzing the given data:\n\n<table>\n  <header>\n    <tr>\n      <th>id</th>\n      <th>recordDate</th>\n      <th>temperature</th>\n    </tr>\n  </header>\n  <tbody>\n    <tr>\n      <td>1</td>\n      <td>2015-01-01</td>\n      <td>10</td>\n    </tr>\n    <tr>\n      <td>2</td>\n      <td>2015-01-02</td>\n      <td>25</td>\n    </tr>\n    <tr>\n      <td>3</td>\n      <td>2015-01-03</td>\n      <td>20</td>\n    </tr>\n    <tr>\n      <td>4</td>\n      <td>2015-01-04</td>\n      <td>30</td>\n    </tr>\n  </tbody>\n</table>\n\nWe can graphically represent the temperature readings across the consecutive dates. When we plot these points on a graph, with the `recordDate` on the X-axis and the `temperature` on the Y-axis, we observe a graphical representation of the temperature variations over the specified period.\n\n![fig](../Figures/197/197-1.png)\n\nFrom this graphical analysis, we notice two instances where there is a rise in the temperature compared to the day before:\n\n1. **January 2, 2015 (id: 2)**: On this day, the temperature is recorded to be 25, which is higher than the 10 recorded on January 1st.\n   \n2. **January 4, 2015 (id: 4)**: Here, the temperature escalated to 30, surpassing the temperature of 20 noted on January 3rd.\n\nThus, based on our criteria of identifying days with a temperature rise compared to the immediate preceding day, we should return the ids for January 2nd and January 4th, which are 2 and 4 respectively.\n\n---\n\n## pandas\n\n### Approach 1: Shifted Dataframe Merge on Record Date\n\n#### Intuition\n\nWe are creating a new DataFrame that represents the data shifted by one day and merging it with the original DataFrame based on the `recordDate`. This way, for each record, we will have information on both the current day and the previous day in the same row, enabling easy comparison of temperatures across consecutive days.\n\nLet's break this down step by step:\n\n**Step 1: Converting `recordDate` to Datetime Type**\n\n```python\n# Ensure the 'recordDate' column is a datetime type\nweather['recordDate'] = pd.to_datetime(weather['recordDate'])\n```\n\n- Before working with date data, it is good practice to ensure that the date column is of the datetime data type to facilitate date-based operations correctly.\n  \n**Step 2: Creating a Shifted DataFrame**\n\n```python\n# Create a copy of the weather DataFrame with a 1 day shift \nweather_shifted = weather.copy()\nweather_shifted['recordDate'] = weather_shifted['recordDate'] + pd.to_timedelta(1, unit='D')\n```\n\n- A copy of the original DataFrame is created, where the `recordDate` for each entry is shifted forward by one day. This allows us to later merge this DataFrame with the original one to compare the temperatures of each day with the previous day.\n\n**Step 3: Merging the Original and Shifted DataFrames**\n\n```python\n# Merging the DataFrames on the 'recordDate' column to find consecutive dates\nmerged_df = pd.merge(weather, weather_shifted, on='recordDate', suffixes=('_today', '_yesterday'))\n```\n\n- The original and shifted DataFrames are merged based on the `recordDate` column, which now contains consecutive dates. This merge operation forms pairs of consecutive days so that we can directly compare the temperatures of each day with the previous day.\n\n**Step 4: Identifying Days with Higher Temperatures than the Previous Day**\n\n```python\n# Finding rows where the temperature is greater on the current day compared to the previous day\nresult = merged_df[merged_df['temperature_today'] > merged_df['temperature_yesterday']][['id_today']].rename(columns={'id_today': 'Id'})\n```\n\n- Within the merged DataFrame, we apply a condition to retain only those rows where the temperature of the current day (`temperature_today`) is greater than that of the previous day (`temperature_yesterday`). This effectively identifies all the days where the temperature was higher than the previous day.\n- We select only the ID column corresponding to the days that satisfy this condition, renaming it to `Id` to meet the output specification.\n\n**Step 5: Returning the Result**\n\n```python\nreturn result\n```\n\n- The final step is to return the DataFrame containing the IDs of the days where the temperature was higher than on the previous day.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/H8hou3Zo/shared\" frameBorder=\"0\" width=\"100%\" height=\"361\" name=\"H8hou3Zo\"></iframe>\n\n\n### Approach 2: Shift Function with Precise Date Match\n\n#### Intuition\n\nIn this approach, we sort the DataFrame by `recordDate` and then use the shift function to create new columns that hold the data for the previous day. After that, we filter the DataFrame to only include the rows where the temperature is greater than that of the previous day and the dates are precisely one day apart.\n\nLet's break this down step by step:\n\n**Step 1: Converting `recordDate` to Datetime Type**\n\n```python\nweather['recordDate'] = pd.to_datetime(weather['recordDate'])\n```\n- Before performing operations based on dates, we first ensure that the `recordDate` column is of datetime type. This allows us to easily perform date-specific operations later in the function.\n\n**Step 2: Sorting the DataFrame**\n\n```python\nweather.sort_values('recordDate', inplace=True)\n```\n- We sort the data based on the `recordDate` to maintain a chronological order. This step is crucial because the next steps involve operations that are dependent on the order of the dates.\n\n**Step 3: Creating Columns for Previous Day's Data**\n\n```python\nweather['PreviousTemperature'] = weather['temperature'].shift(1)\nweather['PreviousRecordDate'] = weather['recordDate'].shift(1)\n```\n- We create two new columns in the `weather` DataFrame:\n  - `PreviousTemperature`: This column is constructed by shifting the `temperature` column down by one row using `shift(1)`. This means that the value in each row of `PreviousTemperature` is the temperature value from the immediately preceding row in the DataFrame, not necessarily from the immediately preceding day in terms of time.\n  - `PreviousRecordDate`: Similarly, this column is formed by shifting the `recordDate` column down by one row. Hence, each value in `PreviousRecordDate` corresponds to the date from the immediately preceding row, not necessarily the day immediately before the current `recordDate`.\n\nBy having these new columns, we align each row with the temperature and record date of its preceding row in the DataFrame, allowing for comparisons between a day's temperature and that of the previous row. It’s crucial to note that these “previous” values come from the DataFrame's order and do not always represent the chronological day before, as there might be gaps in the dates within the data.\n\n**Step 4: Filtering for Days with Higher Temperature than the Previous Day**\n\n```python\nresult = weather[\n    (weather['temperature'] > weather['PreviousTemperature']) & \n    (weather['recordDate'] == weather['PreviousRecordDate'] + pd.Timedelta(days=1))\n][['id']].rename(columns={'id': 'Id'})\n```\n\n- We are filtering the DataFrame for rows where the temperature is higher than the previous day's temperature: `(weather['temperature'] > weather['PreviousTemperature'])`.\n- We also ensure that the record date is exactly one day more than the previous record date: `(weather['recordDate'] == weather['PreviousRecordDate'] + pd.Timedelta(days=1))`. This is done using `pd.Timedelta(days=1)` to add a day to the previous record date and checking if it equals the current record date.\n\n**Step 5: Returning the Result**\n\n```python\nreturn result\n```\n- Finally, we return the filtered DataFrame which contains only the `Id` column that satisfies both conditions specified in step 4. This DataFrame represents all the dates where the temperature was higher than the temperature of the previous day.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/gkesEsMj/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"gkesEsMj\"></iframe>\n\n\n---\n\n## Database\n\n### Approach 1: Using `JOIN` and `DATEDIFF()` \n\n#### Intuition\n\nBy doing a self-join on the `Weather` table, we create a Cartesian product of the table with itself, creating pairs of days. We then use the `DATEDIFF` function to restrict these pairs to only include consecutive days. Lastly, we filter these pairs of consecutive days further to only include pairs where the temperature is higher on the second day. The resulting ids represent the days where the temperature was higher than the previous day.\n\nLet's break this down step by step:\n\n**Step 1: Defining the Main Query Structure**\n\n```sql\nSELECT \n    w1.id\nFROM \n    Weather w1\nJOIN \n    Weather w2\n```\n\nHere, we are setting up a query to retrieve the `id` from the `Weather` table aliased as `w1`. To find the records where the temperature is greater than the previous day, we are performing a self-join on the `Weather` table, creating a second alias `w2`. This allows us to compare each record in `w1` with each record in `w2`.\n\n**Step 2: Join Condition**\n\n```sql\nON \n    DATEDIFF(w1.recordDate, w2.recordDate) = 1\n```\n\nIn the join condition, we are using the `DATEDIFF` function to find pairs of records where the `recordDate` differs by exactly one day. This condition ensures that we are comparing each day's temperature with the temperature of the previous day.\n\n**Step 3: Filter Records with Higher Temperature**\n\n```sql\nWHERE \n    w1.temperature > w2.temperature;\n```\n\nAfter finding pairs of days that are consecutive, we apply a filter in the `WHERE` clause to only get the records where the temperature on a day (represented by a record in `w1`) is greater than the temperature on the previous day (represented by a record in `w2`). This is the main condition to fulfill the requirement of finding the ids where the temperature is higher than the previous day.\n\n\n#### Implementation\n\n\n\n```mysql []\nSELECT \n    w1.id\nFROM \n    Weather w1\nJOIN \n    Weather w2\nON \n    DATEDIFF(w1.recordDate, w2.recordDate) = 1\nWHERE \n    w1.temperature > w2.temperature;\n\n```\n\n### Approach 2: Using `LAG()` Function\n\n#### Intuition\n\nLet's break this down step by step:\n\n**Step 1: Creating a Common Table Expression (CTE) with Lag Function**\n\n```sql\nWITH PreviousWeatherData AS\n(\n    SELECT \n        id,\n        recordDate,\n        temperature, \n        LAG(temperature, 1) OVER (ORDER BY recordDate) AS PreviousTemperature,\n        LAG(recordDate, 1) OVER (ORDER BY recordDate) AS PreviousRecordDate\n    FROM \n        Weather\n)\n```\n\nIn this step, we create a Common Table Expression (CTE) named `PreviousWeatherData` using a `WITH` clause. Inside this CTE, we are selecting all the rows from the \"Weather\" table along with two additional columns:\n\n1. `PreviousTemperature`: The temperature from the previous day, which is obtained using the `LAG()` function with an offset of 1, ordered by `recordDate`.\n2. `PreviousRecordDate`: The record date of the previous day, similarly obtained using the `LAG()` function with an offset of 1, ordered by `recordDate`.\n\nThis setup helps us associate each record with the respective details from the previous day in the same row.\n\n**Step 2: Selecting IDs with Conditions on Temperature and Date**\n\n```sql\nSELECT \n    id \nFROM \n    PreviousWeatherData\nWHERE \n    temperature > PreviousTemperature\nAND \n    recordDate = DATE_ADD(PreviousRecordDate, INTERVAL 1 DAY);\n```\n\nIn this step, we execute a query on the `PreviousWeatherData` CTE with two conditions in the WHERE clause to filter the required IDs:\n\n1. `temperature > PreviousTemperature`: This condition filters for the days where the temperature was higher than the previous day's temperature.\n2. `recordDate = DATE_ADD(PreviousRecordDate, INTERVAL 1 DAY)`: This condition ensures that we are comparing consecutive days. It uses the `DATE_ADD()` function to add an interval of 1 day to the `PreviousRecordDate` and checks if it equals the current `recordDate`.\n\nBy combining these two conditions with an `AND` clause, we ensure that we only select the IDs where both conditions are met, which are the days when the temperature is higher than the day before.\n\n\n#### Implementation\n\n\n```mysql []\nWITH PreviousWeatherData AS\n(\n    SELECT \n        id,\n        recordDate,\n        temperature, \n        LAG(temperature, 1) OVER (ORDER BY recordDate) AS PreviousTemperature,\n        LAG(recordDate, 1) OVER (ORDER BY recordDate) AS PreviousRecordDate\n    FROM \n        Weather\n)\nSELECT \n    id \nFROM \n    PreviousWeatherData\nWHERE \n    temperature > PreviousTemperature\nAND \n    recordDate = DATE_ADD(PreviousRecordDate, INTERVAL 1 DAY);\n\n```\n\n### Approach 3: Using Subquery\n\n#### Intuition\n\nLet's break this down step by step:\n\n**Step 1: Inner Subquery to Get the Previous Day’s Temperature**\n\n```sql\n        SELECT \n            w2.temperature\n        FROM \n            Weather w2\n        WHERE \n            w2.recordDate = DATE_SUB(w1.recordDate, INTERVAL 1 DAY)\n```\n\nThe inner query is responsible for retrieving the temperature of the day before the date currently under consideration in the outer query. \n\nIt utilizes the `DATE_SUB` function to find the date one day before the `recordDate` in the outer query (`w1.recordDate`) and then fetches the temperature recorded on that previous date from the same Weather table (alias `w2`).\n\n**Step 2: Outer Query to Find Days with Higher Temperature**\n\n```sql\nSELECT \n    w1.id\nFROM \n    Weather w1\nWHERE \n    w1.temperature > (\n        -- ... (inner subquery)\n    );\n```\n\nThe outer query iterates over each row (each day) in the Weather table (alias `w1`) and checks if the temperature on that day is greater than the temperature on the previous day, the latter being obtained from the inner subquery.\n\n**Step 3: Comparing Temperatures**\n\n```sql\n    w1.temperature > (\n        -- ... (inner subquery)\n    )\n```\n\nHere, we have the crucial comparison that serves our goal. For each day in the outer query, it checks whether the temperature is greater than the temperature fetched from the inner subquery (which is the temperature of the previous day).\n\n**Step 4: Selecting the ID**\n\n```sql\nSELECT \n    w1.id\n```\n\nIf the condition in the `WHERE` clause is satisfied (today’s temperature is greater than yesterday’s), we select the ID of the current day (from the outer query’s perspective). This ID indicates a day where the temperature was higher than the temperature on the previous day.\n\n#### Implementation\n\n\n\n```mysql []\nSELECT \n    w1.id\nFROM \n    Weather w1\nWHERE \n    w1.temperature > (\n        SELECT \n            w2.temperature\n        FROM \n            Weather w2\n        WHERE \n            w2.recordDate = DATE_SUB(w1.recordDate, INTERVAL 1 DAY)\n    );\n\n```\n\n### Approach 4: Using Cartesian Product and `WHERE` Clause\n\n#### Intuition\n\nLet's break this down step by step:\n\n**Step 1: Cartesian Product**\n```sql\nFROM \n    Weather w1, Weather w2\n```\n\nIn this step, we are performing a Cartesian product (or cross join) of the `Weather` table with itself. This means we create a new table where each row from `w1` (first instance of the Weather table) is paired with every row from `w2` (second instance of the Weather table), resulting in a table with n² rows (where n is the number of rows in the Weather table).\n\n**Step 2: Filtering Based on Date Difference**\n```sql\nWHERE \n    DATEDIFF(w2.recordDate, w1.recordDate) = 1 \n```\n\nNext, we use the `DATEDIFF` function to find pairs of rows where the difference between the 'recordDate' in w2 and w1 is exactly 1 day. This effectively filters down to pairs of rows representing consecutive days.\n\n**Step 3: Filtering Based on Temperature Difference**\n```sql\nAND \n    w2.temperature > w1.temperature;\n```\n\nIn this step, we are filtering the pairs further to retain only those where the temperature on the second day (`w2.temperature`) is greater than the temperature on the first day (`w1.temperature`). This finds the days where the temperature is rising compared to the previous day.\n\n**Step 4: Selecting the Result**\n```sql\nSELECT \n    w2.id\n```\n\nFinally, from all the pairs that satisfy the conditions set in the WHERE clause, we select the ID of the day from the w2 table (i.e., the ID of the day with the higher temperature).\n\n\n#### Implementation\n\n\n\n```mysql []\nSELECT \n    w2.id\nFROM \n    Weather w1, Weather w2\nWHERE \n    DATEDIFF(w2.recordDate, w1.recordDate) = 1 \nAND \n    w2.temperature > w1.temperature;\n\n```",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/197.html",
    "category": "Database",
    "acceptance_rate": 50.074242778956524,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 3603,
    "dislikes": 685,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1086565, \"totalSubmissionRaw\": 2169908, \"acRate\": \"50.1%\"}",
    "title_pt": "Temperatura em Elevação",
    "description_pt": "<p>Tabela: <code>Weather</code></p>\n\n<pre>\n+---------------+---------+\n| Column Name   | Type    |\n+---------------+---------+\n| id            | int     |\n| recordDate    | date    |\n| temperature   | int     |\n+---------------+---------+\nid is the column with unique values for this table.\nThere are no different rows with the same recordDate.\nThis table contains information about the temperature on a certain day.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar todos os <code>id</code> das datas com temperaturas mais altas em comparação com suas datas anteriores (ontem).</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no seguinte exemplo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nWeather table:\n+----+------------+-------------+\n| id | recordDate | temperature |\n+----+------------+-------------+\n| 1  | 2015-01-01 | 10          |\n| 2  | 2015-01-02 | 25          |\n| 3  | 2015-01-03 | 20          |\n| 4  | 2015-01-04 | 30          |\n+----+------------+-------------+\n<strong>Saída:</strong> \n+----+\n| id |\n+----+\n| 2  |\n| 4  |\n+----+\n<strong>Explicação:</strong> \nEm 2015-01-02, a temperatura foi maior do que no dia anterior (10 -&gt; 25).\nEm 2015-01-04, a temperatura foi maior do que no dia anterior (20 -&gt; 30).\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "198",
    "paidOnly": false,
    "title": "House Robber",
    "titleSlug": "house-robber",
    "url": "https://leetcode.com/problems/house-robber",
    "description_url": "https://leetcode.com/problems/house-robber/description/",
    "description": "<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p>\n\n<p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,7,9,3,1]\n<strong>Output:</strong> 12\n<strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 400</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/house-robber/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rob(self, nums: List[int]) -> int:\n    if not nums:\n      return 0\n    if len(nums) == 1:\n      return nums[0]\n\n    # dp[i]: = max money of robbing nums[0..i]\n    dp = [0] * len(nums)\n    dp[0] = nums[0]\n    dp[1] = max(nums[0], nums[1])\n\n    for i in range(2, len(nums)):\n      dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])\n\n    return dp[-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int rob(int[] nums) {\n    final int n = nums.length;\n    if (n == 0)\n      return 0;\n    if (n == 1)\n      return nums[0];\n\n    // dp[i] := max money of robbing nums[0..i]\n    int[] dp = new int[n];\n    dp[0] = nums[0];\n    dp[1] = Math.max(nums[0], nums[1]);\n\n    for (int i = 2; i < n; ++i)\n      dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);\n\n    return dp[n - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int rob(vector<int>& nums) {\n    if (nums.empty())\n      return 0;\n    if (nums.size() == 1)\n      return nums[0];\n\n    // dp[i] := max money of robbing nums[0..i]\n    vector<int> dp(nums.size());\n    dp[0] = nums[0];\n    dp[1] = max(nums[0], nums[1]);\n\n    for (int i = 2; i < nums.size(); ++i)\n      dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]);\n\n    return dp.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/198.html",
    "category": "Algorithms",
    "acceptance_rate": 52.19996471506505,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 22189,
    "dislikes": 471,
    "similar_questions": "[{\"title\": \"Maximum Product Subarray\", \"titleSlug\": \"maximum-product-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber II\", \"titleSlug\": \"house-robber-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint House\", \"titleSlug\": \"paint-house\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint Fence\", \"titleSlug\": \"paint-fence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber III\", \"titleSlug\": \"house-robber-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Non-negative Integers without Consecutive Ones\", \"titleSlug\": \"non-negative-integers-without-consecutive-ones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Coin Path\", \"titleSlug\": \"coin-path\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Delete and Earn\", \"titleSlug\": \"delete-and-earn\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Solving Questions With Brainpower\", \"titleSlug\": \"solving-questions-with-brainpower\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Number of Ways to Place Houses\", \"titleSlug\": \"count-number-of-ways-to-place-houses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber IV\", \"titleSlug\": \"house-robber-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Mice and Cheese\", \"titleSlug\": \"mice-and-cheese\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Largest Element in an Array after Merge Operations\", \"titleSlug\": \"largest-element-in-an-array-after-merge-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.9M\", \"totalSubmission\": \"5.5M\", \"totalAcceptedRaw\": 2867034, \"totalSubmissionRaw\": 5492410, \"acRate\": \"52.2%\"}",
    "title_pt": "Ladrão da Casa",
    "description_pt": "<p>Você é um ladrão profissional planejando roubar casas ao longo de uma rua. Cada casa tem uma certa quantia de dinheiro guardada; a única restrição que o impede de roubar cada uma delas é que casas adjacentes têm sistemas de segurança conectados e <b>ele automaticamente chamará a polícia se duas casas adjacentes forem invadidas na mesma noite</b>.</p>\n\n<p>Dado um array de inteiros <code>nums</code> representando a quantia de dinheiro de cada casa, retorne <em>a máxima quantia de dinheiro que você pode roubar esta noite <b>sem alertar a polícia</b></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Roube a casa 1 (dinheiro = 1) e então roube a casa 3 (dinheiro = 3).\nA quantia total que você pode roubar = 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,7,9,3,1]\n<strong>Saída:</strong> 12\n<strong>Explicação:</strong> Roube a casa 1 (dinheiro = 2), roube a casa 3 (dinheiro = 9) e roube a casa 5 (dinheiro = 1).\nA quantia total que você pode roubar = 2 + 9 + 1 = 12.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 400</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "199",
    "paidOnly": false,
    "title": "Binary Tree Right Side View",
    "titleSlug": "binary-tree-right-side-view",
    "url": "https://leetcode.com/problems/binary-tree-right-side-view",
    "description_url": "https://leetcode.com/problems/binary-tree-right-side-view/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,2,3,null,5,null,4]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,3,4]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/11/24/tmpd5jn43fs-1.png\" style=\"width: 400px; height: 207px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,2,3,4,null,null,null,5]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,3,4,5]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/11/24/tmpkpe40xeh-1.png\" style=\"width: 400px; height: 214px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = [1,null,3]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,3]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-right-side-view/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n    if not root:\n      return []\n\n    ans = []\n    q = deque([root])\n\n    while q:\n      size = len(q)\n      for i in range(size):\n        root = q.popleft()\n        if i == size - 1:\n          ans.append(root.val)\n        if root.left:\n          q.append(root.left)\n        if root.right:\n          q.append(root.right)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> rightSideView(TreeNode root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<Integer> ans = new ArrayList<>();\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      final int size = q.size();\n      for (int i = 0; i < size; ++i) {\n        TreeNode node = q.poll();\n        if (i == size - 1)\n          ans.add(node.val);\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> rightSideView(TreeNode* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<int> ans;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      const int size = q.size();\n      for (int i = 0; i < size; ++i) {\n        TreeNode* node = q.front();\n        q.pop();\n        if (i == size - 1)\n          ans.push_back(node->val);\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/199.html",
    "category": "Algorithms",
    "acceptance_rate": 66.61680552672932,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 12708,
    "dislikes": 1058,
    "similar_questions": "[{\"title\": \"Populating Next Right Pointers in Each Node\", \"titleSlug\": \"populating-next-right-pointers-in-each-node\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Boundary of Binary Tree\", \"titleSlug\": \"boundary-of-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1797425, \"totalSubmissionRaw\": 2698156, \"acRate\": \"66.6%\"}",
    "title_pt": "Vista Lateral Direita de uma Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, imagine-se parado no lado <strong>direito</strong> dela e retorne <em>os valores dos nós que você consegue ver, ordenados de cima para baixo</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,2,3,null,5,null,4]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,3,4]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/11/24/tmpd5jn43fs-1.png\" style=\"width: 400px; height: 207px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,2,3,4,null,null,null,5]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,3,4,5]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2024/11/24/tmpkpe40xeh-1.png\" style=\"width: 400px; height: 214px;\" /></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = [1,null,3]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,3]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 4:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">root = []</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "200",
    "paidOnly": false,
    "title": "Number of Islands",
    "titleSlug": "number-of-islands",
    "url": "https://leetcode.com/problems/number-of-islands",
    "description_url": "https://leetcode.com/problems/number-of-islands/description/",
    "description": "<p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>&#39;1&#39;</code>s (land) and <code>&#39;0&#39;</code>s (water), return <em>the number of islands</em>.</p>\n\n<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [\n  [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]\n]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;]\n]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 300</code></li>\n\t<li><code>grid[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-islands/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numIslands(self, grid: List[List[str]]) -> int:\n    m = len(grid)\n    n = len(grid[0])\n    dirs = [0, 1, 0, -1, 0]\n\n    def bfs(r, c):\n      q = deque([(r, c)])\n      grid[r][c] = '2'  # Mark '2' as visited\n      while q:\n        i, j = q.popleft()\n        for k in range(4):\n          x = i + dirs[k]\n          y = j + dirs[k + 1]\n          if x < 0 or x == m or y < 0 or y == n:\n            continue\n          if grid[x][y] != '1':\n            continue\n          q.append((x, y))\n          grid[x][y] = '2'  # Mark '2' as visited\n\n    ans = 0\n\n    for i in range(m):\n      for j in range(n):\n        if grid[i][j] == '1':\n          bfs(i, j)\n          ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numIslands(char[][] grid) {\n    int ans = 0;\n\n    for (int i = 0; i < grid.length; ++i)\n      for (int j = 0; j < grid[0].length; ++j)\n        if (grid[i][j] == '1') {\n          bfs(grid, i, j);\n          ++ans;\n        }\n\n    return ans;\n  }\n\n  private static final int[] dirs = {0, 1, 0, -1, 0};\n\n  private void bfs(char[][] grid, int r, int c) {\n    Queue<int[]> q = new ArrayDeque<>();\n    q.offer(new int[] {r, c});\n    grid[r][c] = '2'; // Mark '2' as visited\n    while (!q.isEmpty()) {\n      final int i = q.peek()[0];\n      final int j = q.poll()[1];\n      for (int k = 0; k < 4; ++k) {\n        final int x = i + dirs[k];\n        final int y = j + dirs[k + 1];\n        if (x < 0 || x == grid.length || y < 0 || y == grid[0].length)\n          continue;\n        if (grid[x][y] != '1')\n          continue;\n        q.offer(new int[] {x, y});\n        grid[x][y] = '2'; // Mark '2' as visited\n      }\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numIslands(vector<vector<char>>& grid) {\n    const int m = grid.size();\n    const int n = grid[0].size();\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    int ans = 0;\n\n    auto bfs = [&](int r, int c) {\n      queue<pair<int, int>> q{{{r, c}}};\n      grid[r][c] = '2';  // Mark '2' as visited\n      while (!q.empty()) {\n        const auto [i, j] = q.front();\n        q.pop();\n        for (int k = 0; k < 4; ++k) {\n          const int x = i + dirs[k];\n          const int y = j + dirs[k + 1];\n          if (x < 0 || x == m || y < 0 || y == n)\n            continue;\n          if (grid[x][y] != '1')\n            continue;\n          q.emplace(x, y);\n          grid[x][y] = '2';  // Mark '2' as visited\n        }\n      }\n    };\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (grid[i][j] == '1') {\n          bfs(i, j);\n          ++ans;\n        }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/200.html",
    "category": "Algorithms",
    "acceptance_rate": 62.09617867488178,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Matrix"
    ],
    "hints": [],
    "likes": 23763,
    "dislikes": 561,
    "similar_questions": "[{\"title\": \"Surrounded Regions\", \"titleSlug\": \"surrounded-regions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Walls and Gates\", \"titleSlug\": \"walls-and-gates\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Islands II\", \"titleSlug\": \"number-of-islands-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Connected Components in an Undirected Graph\", \"titleSlug\": \"number-of-connected-components-in-an-undirected-graph\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Battleships in a Board\", \"titleSlug\": \"battleships-in-a-board\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Distinct Islands\", \"titleSlug\": \"number-of-distinct-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Max Area of Island\", \"titleSlug\": \"max-area-of-island\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Sub Islands\", \"titleSlug\": \"count-sub-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All Groups of Farmland\", \"titleSlug\": \"find-all-groups-of-farmland\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Unreachable Pairs of Nodes in an Undirected Graph\", \"titleSlug\": \"count-unreachable-pairs-of-nodes-in-an-undirected-graph\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Fish in a Grid\", \"titleSlug\": \"maximum-number-of-fish-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.4M\", \"totalSubmission\": \"5.5M\", \"totalAcceptedRaw\": 3415751, \"totalSubmissionRaw\": 5500745, \"acRate\": \"62.1%\"}",
    "title_pt": "Número de Ilhas",
    "description_pt": "<p>Dado um <code>m x n</code> grid binário 2D <code>grid</code> que representa um mapa de <code>&#39;1&#39;</code>s (terra) e <code>&#39;0&#39;</code>s (água), retorne <em>o número de ilhas</em>.</p>\n\n<p>Uma <strong>ilha</strong> é cercada por água e é formada pela conexão de terras adjacentes horizontalmente ou verticalmente. Você pode assumir que todas as quatro bordas do grid são cercadas por água.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [\n  [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;]\n]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],\n  [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;]\n]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 300</code></li>\n\t<li><code>grid[i][j]</code> é <code>&#39;0&#39;</code> ou <code>&#39;1&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "201",
    "paidOnly": false,
    "title": "Bitwise AND of Numbers Range",
    "titleSlug": "bitwise-and-of-numbers-range",
    "url": "https://leetcode.com/problems/bitwise-and-of-numbers-range",
    "description_url": "https://leetcode.com/problems/bitwise-and-of-numbers-range/description/",
    "description": "<p>Given two integers <code>left</code> and <code>right</code> that represent the range <code>[left, right]</code>, return <em>the bitwise AND of all numbers in this range, inclusive</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> left = 5, right = 7\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> left = 0, right = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> left = 1, right = 2147483647\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= left &lt;= right &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/bitwise-and-of-numbers-range/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rangeBitwiseAnd(self, m: int, n: int) -> int:\n    return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1 if m < n else m",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int rangeBitwiseAnd(int m, int n) {\n    int shiftBits = 0;\n\n    while (m != n) {\n      m >>= 1;\n      n >>= 1;\n      ++shiftBits;\n    }\n\n    return m << shiftBits;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int rangeBitwiseAnd(int m, int n) {\n    int shiftBits = 0;\n\n    while (m != n) {\n      m >>= 1;\n      n >>= 1;\n      ++shiftBits;\n    }\n\n    return m << shiftBits;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/201.html",
    "category": "Algorithms",
    "acceptance_rate": 47.654351635821236,
    "topics": [
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 4143,
    "dislikes": 311,
    "similar_questions": "[{\"title\": \"Longest Nice Subarray\", \"titleSlug\": \"longest-nice-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"453K\", \"totalSubmission\": \"950.7K\", \"totalAcceptedRaw\": 453028, \"totalSubmissionRaw\": 950654, \"acRate\": \"47.7%\"}",
    "title_pt": "AND Bit a Bit de Números em um Intervalo",
    "description_pt": "<p>Dados dois inteiros <code>left</code> e <code>right</code> que representam o intervalo <code>[left, right]</code>, retorne <em>o AND bit a bit de todos os números neste intervalo, inclusive</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> left = 5, right = 7\n<strong>Saída:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> left = 0, right = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> left = 1, right = 2147483647\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= left &lt;= right &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "202",
    "paidOnly": false,
    "title": "Happy Number",
    "titleSlug": "happy-number",
    "url": "https://leetcode.com/problems/happy-number",
    "description_url": "https://leetcode.com/problems/happy-number/description/",
    "description": "<p>Write an algorithm to determine if a number <code>n</code> is happy.</p>\n\n<p>A <strong>happy number</strong> is a number defined by the following process:</p>\n\n<ul>\n\t<li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li>\n\t<li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li>\n\t<li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li>\n</ul>\n\n<p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 19\n<strong>Output:</strong> true\n<strong>Explanation:</strong>\n1<sup>2</sup> + 9<sup>2</sup> = 82\n8<sup>2</sup> + 2<sup>2</sup> = 68\n6<sup>2</sup> + 8<sup>2</sup> = 100\n1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/happy-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isHappy(self, n: int) -> bool:\n    def squaredSum(n: int) -> bool:\n      summ = 0\n      while n:\n        summ += pow(n % 10, 2)\n        n //= 10\n      return summ\n\n    slow = squaredSum(n)\n    fast = squaredSum(squaredSum(n))\n\n    while slow != fast:\n      slow = squaredSum(slow)\n      fast = squaredSum(squaredSum(fast))\n\n    return slow == 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isHappy(int n) {\n    int slow = squaredSum(n);\n    int fast = squaredSum(squaredSum(n));\n\n    while (slow != fast) {\n      slow = squaredSum(slow);\n      fast = squaredSum(squaredSum(fast));\n    }\n\n    return slow == 1;\n  }\n\n  private int squaredSum(int n) {\n    int sum = 0;\n    while (n > 0) {\n      sum += Math.pow(n % 10, 2);\n      n /= 10;\n    }\n    return sum;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isHappy(int n) {\n    int slow = squaredSum(n);\n    int fast = squaredSum(squaredSum(n));\n\n    while (slow != fast) {\n      slow = squaredSum(slow);\n      fast = squaredSum(squaredSum(fast));\n    }\n\n    return slow == 1;\n  }\n\n private:\n  int squaredSum(int n) {\n    int sum = 0;\n    while (n) {\n      sum += pow(n % 10, 2);\n      n /= 10;\n    }\n    return sum;\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/202.html",
    "category": "Algorithms",
    "acceptance_rate": 57.9078316335787,
    "topics": [
      "Hash Table",
      "Math",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 11088,
    "dislikes": 1558,
    "similar_questions": "[{\"title\": \"Linked List Cycle\", \"titleSlug\": \"linked-list-cycle\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Digits\", \"titleSlug\": \"add-digits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Ugly Number\", \"titleSlug\": \"ugly-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Digits of String After Convert\", \"titleSlug\": \"sum-of-digits-of-string-after-convert\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Addition to Make Integer Beautiful\", \"titleSlug\": \"minimum-addition-to-make-integer-beautiful\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Value After Replacing With Sum of Prime Factors\", \"titleSlug\": \"smallest-value-after-replacing-with-sum-of-prime-factors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Digits That Divide a Number\", \"titleSlug\": \"count-the-digits-that-divide-a-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 1851260, \"totalSubmissionRaw\": 3196910, \"acRate\": \"57.9%\"}",
    "title_pt": "Número Feliz",
    "description_pt": "<p>Escreva um algoritmo para determinar se um número <code>n</code> é feliz.</p>\n\n<p>Um <strong>número feliz</strong> é um número definido pelo seguinte processo:</p>\n\n<ul>\n\t<li>Começando com qualquer inteiro positivo, substitua o número pela soma dos quadrados de seus dígitos.</li>\n\t<li>Repita o processo até que o número seja igual a 1 (onde ele permanecerá), ou até que ele <strong>entre infinitamente em um ciclo</strong> que não inclua 1.</li>\n\t<li>Aqueles números para os quais esse processo <strong>termina em 1</strong> são felizes.</li>\n</ul>\n\n<p>Retorne <code>true</code> <em>se</em> <code>n</code> <em>for um número feliz, e</em> <code>false</code> <em>caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 19\n<strong>Saída:</strong> true\n<strong>Explicação:</strong>\n1<sup>2</sup> + 9<sup>2</sup> = 82\n8<sup>2</sup> + 2<sup>2</sup> = 68\n6<sup>2</sup> + 8<sup>2</sup> = 100\n1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "203",
    "paidOnly": false,
    "title": "Remove Linked List Elements",
    "titleSlug": "remove-linked-list-elements",
    "url": "https://leetcode.com/problems/remove-linked-list-elements",
    "description_url": "https://leetcode.com/problems/remove-linked-list-elements/description/",
    "description": "<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6\n<strong>Output:</strong> [1,2,3,4,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [], val = 1\n<strong>Output:</strong> []\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = [7,7,7,7], val = 7\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 50</code></li>\n\t<li><code>0 &lt;= val &lt;= 50</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-linked-list-elements/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeElements(self, head: ListNode, val: int) -> ListNode:\n    dummy = ListNode(0, head)\n    prev = dummy\n\n    while head:\n      if head.val != val:\n        prev.next = head\n        prev = prev.next\n      head = head.next\n    prev.next = None\n\n    return dummy.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode removeElements(ListNode head, int val) {\n    ListNode dummy = new ListNode(0, head);\n    ListNode prev = dummy;\n\n    for (; head != null; head = head.next)\n      if (head.val != val) {\n        prev.next = head;\n        prev = prev.next;\n      }\n    prev.next = null; // In case the last val == val\n\n    return dummy.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* removeElements(ListNode* head, int val) {\n    ListNode dummy(0, head);\n    ListNode* prev = &dummy;\n\n    for (; head; head = head->next)\n      if (head->val != val) {\n        prev->next = head;\n        prev = prev->next;\n      }\n    prev->next = nullptr;  // In case the last val == val\n\n    return dummy.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/203.html",
    "category": "Algorithms",
    "acceptance_rate": 51.673182501928025,
    "topics": [
      "Linked List",
      "Recursion"
    ],
    "hints": [],
    "likes": 8660,
    "dislikes": 267,
    "similar_questions": "[{\"title\": \"Remove Element\", \"titleSlug\": \"remove-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Delete Node in a Linked List\", \"titleSlug\": \"delete-node-in-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete the Middle Node of a Linked List\", \"titleSlug\": \"delete-the-middle-node-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete Nodes From Linked List Present in Array\", \"titleSlug\": \"delete-nodes-from-linked-list-present-in-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Convert Doubly Linked List to Array I\", \"titleSlug\": \"convert-doubly-linked-list-to-array-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Convert Doubly Linked List to Array II\", \"titleSlug\": \"convert-doubly-linked-list-to-array-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1353448, \"totalSubmissionRaw\": 2619253, \"acRate\": \"51.7%\"}",
    "title_pt": "Remover Elementos de uma Lista Encadeada",
    "description_pt": "<p>Dada a <code>head</code> de uma lista encadeada e um inteiro <code>val</code>, remova todos os nós da lista encadeada que têm <code>Node.val == val</code> e retorne <em>a nova head</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,6,3,4,5,6], val = 6\n<strong>Saída:</strong> [1,2,3,4,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [], val = 1\n<strong>Saída:</strong> []\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = [7,7,7,7], val = 7\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 50</code></li>\n\t<li><code>0 &lt;= val &lt;= 50</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "204",
    "paidOnly": false,
    "title": "Count Primes",
    "titleSlug": "count-primes",
    "url": "https://leetcode.com/problems/count-primes",
    "description_url": "https://leetcode.com/problems/count-primes/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 10\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-primes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countPrimes(self, n: int) -> int:\n    if n <= 2:\n      return 0\n\n    isPrime = [False] * 2 + [True] * (n - 2)\n\n    for i in range(2, int(n**0.5) + 1):\n      if isPrime[i]:\n        for j in range(i * i, n, i):\n          isPrime[j] = False\n\n    return sum(isPrime)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countPrimes(int n) {\n    if (n <= 2)\n      return 0;\n\n    int ans = 0;\n    boolean[] prime = new boolean[n];\n    Arrays.fill(prime, 2, n, true);\n\n    for (int i = 0; i < Math.sqrt(n); ++i)\n      if (prime[i])\n        for (int j = i * i; j < n; j += i)\n          prime[j] = false;\n\n    for (final boolean p : prime)\n      if (p)\n        ++ans;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countPrimes(int n) {\n    if (n <= 2)\n      return false;\n\n    vector<bool> prime(n, true);\n    prime[0] = false;\n    prime[1] = false;\n\n    for (int i = 0; i < sqrt(n); ++i)\n      if (prime[i])\n        for (int j = i * i; j < n; j += i)\n          prime[j] = false;\n\n    return count(begin(prime), end(prime), true);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/204.html",
    "category": "Algorithms",
    "acceptance_rate": 34.64775175975698,
    "topics": [
      "Array",
      "Math",
      "Enumeration",
      "Number Theory"
    ],
    "hints": [
      "Checking all the integers in the range [1, n - 1] is not efficient. Think about a better approach.",
      "Since most of the numbers are not primes, we need a fast approach to exclude the non-prime integers.",
      "Use Sieve of Eratosthenes."
    ],
    "likes": 8332,
    "dislikes": 1509,
    "similar_questions": "[{\"title\": \"Ugly Number\", \"titleSlug\": \"ugly-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Ugly Number II\", \"titleSlug\": \"ugly-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Perfect Squares\", \"titleSlug\": \"perfect-squares\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Common Factors\", \"titleSlug\": \"number-of-common-factors\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Prime Pairs With Target Sum\", \"titleSlug\": \"prime-pairs-with-target-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Count of Numbers Which Are Not Special\", \"titleSlug\": \"find-the-count-of-numbers-which-are-not-special\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"3M\", \"totalAcceptedRaw\": 1044627, \"totalSubmissionRaw\": 3015018, \"acRate\": \"34.6%\"}",
    "title_pt": "Contar Números Primos",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>a quantidade de números primos que são estritamente menores que</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 10\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Existem 4 números primos menores que 10, eles são 2, 3, 5, 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Verificar todos os inteiros no intervalo [1, n - 1] não é eficiente. Pense em uma abordagem melhor.",
      "Dica 2: Como a maioria dos números não é primo, precisamos de uma abordagem rápida para excluir os inteiros não primos.",
      "Dica 3: Use a Crivo de Eratóstenes."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "205",
    "paidOnly": false,
    "title": "Isomorphic Strings",
    "titleSlug": "isomorphic-strings",
    "url": "https://leetcode.com/problems/isomorphic-strings",
    "description_url": "https://leetcode.com/problems/isomorphic-strings/description/",
    "description": "<p>Given two strings <code>s</code> and <code>t</code>, <em>determine if they are isomorphic</em>.</p>\n\n<p>Two strings <code>s</code> and <code>t</code> are isomorphic if the characters in <code>s</code> can be replaced to get <code>t</code>.</p>\n\n<p>All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;egg&quot;, t = &quot;add&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The strings <code>s</code> and <code>t</code> can be made identical by:</p>\n\n<ul>\n\t<li>Mapping <code>&#39;e&#39;</code> to <code>&#39;a&#39;</code>.</li>\n\t<li>Mapping <code>&#39;g&#39;</code> to <code>&#39;d&#39;</code>.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The strings <code>s</code> and <code>t</code> can not be made identical as <code>&#39;o&#39;</code> needs to be mapped to both <code>&#39;a&#39;</code> and <code>&#39;r&#39;</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;paper&quot;, t = &quot;title&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>t.length == s.length</code></li>\n\t<li><code>s</code> and <code>t</code> consist of any valid ascii character.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/isomorphic-strings/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isIsomorphic(self, s: str, t: str) -> bool:\n    return [*map(s.index, s)] == [*map(t.index, t)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isIsomorphic(String s, String t) {\n    Map<Character, Integer> charToIndex_s = new HashMap<>();\n    Map<Character, Integer> charToIndex_t = new HashMap<>();\n\n    for (Integer i = 0; i < s.length(); ++i)\n      if (charToIndex_s.put(s.charAt(i), i) != charToIndex_t.put(t.charAt(i), i))\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isIsomorphic(string s, string t) {\n    vector<int> charToIndex_s(128);\n    vector<int> charToIndex_t(128);\n\n    for (int i = 0; i < s.length(); ++i) {\n      if (charToIndex_s[s[i]] != charToIndex_t[t[i]])\n        return false;\n      charToIndex_s[s[i]] = i + 1;\n      charToIndex_t[t[i]] = i + 1;\n    }\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/205.html",
    "category": "Algorithms",
    "acceptance_rate": 46.70215682253576,
    "topics": [
      "Hash Table",
      "String"
    ],
    "hints": [],
    "likes": 9689,
    "dislikes": 2199,
    "similar_questions": "[{\"title\": \"Word Pattern\", \"titleSlug\": \"word-pattern\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find and Replace Pattern\", \"titleSlug\": \"find-and-replace-pattern\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"3.8M\", \"totalAcceptedRaw\": 1758152, \"totalSubmissionRaw\": 3764609, \"acRate\": \"46.7%\"}",
    "title_pt": "Strings Isomórficas",
    "description_pt": "<p>Dadas duas strings <code>s</code> e <code>t</code>, <em>determine se elas são isomórficas</em>.</p>\n\n<p>Duas strings <code>s</code> e <code>t</code> são isomórficas se os caracteres em <code>s</code> puderem ser substituídos para obter <code>t</code>.</p>\n\n<p>Todas as ocorrências de um caractere devem ser substituídas por outro caractere, mantendo a ordem dos caracteres. Nenhum dois caracteres podem ser mapeados para o mesmo caractere, mas um caractere pode ser mapeado para ele mesmo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;egg&quot;, t = &quot;add&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>As strings <code>s</code> e <code>t</code> podem ser tornadas idênticas por meio de:</p>\n\n<ul>\n\t<li>Mapeando <code>&#39;e&#39;</code> para <code>&#39;a&#39;</code>.</li>\n\t<li>Mapeando <code>&#39;g&#39;</code> para <code>&#39;d&#39;</code>.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;foo&quot;, t = &quot;bar&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>As strings <code>s</code> e <code>t</code> não podem ser tornadas idênticas, pois <code>&#39;o&#39;</code> precisa ser mapeado para <code>&#39;a&#39;</code> e <code>&#39;r&#39;</code> ao mesmo tempo.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;paper&quot;, t = &quot;title&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>t.length == s.length</code></li>\n\t<li><code>s</code> e <code>t</code> consistem de qualquer caractere ASCII válido.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "206",
    "paidOnly": false,
    "title": "Reverse Linked List",
    "titleSlug": "reverse-linked-list",
    "url": "https://leetcode.com/problems/reverse-linked-list",
    "description_url": "https://leetcode.com/problems/reverse-linked-list/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [5,4,3,2,1]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg\" style=\"width: 182px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2]\n<strong>Output:</strong> [2,1]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li>\n\t<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>\n",
    "solution_url": "https://leetcode.com/problems/reverse-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n    if not head or not head.next:\n      return head\n\n    newHead = self.reverseList(head.next)\n    head.next.next = head\n    head.next = None\n    return newHead",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode reverseList(ListNode head) {\n    if (head == null || head.next == null)\n      return head;\n\n    ListNode newHead = reverseList(head.next);\n    head.next.next = head;\n    head.next = null;\n    return newHead;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* reverseList(ListNode* head) {\n    if (!head || !head->next)\n      return head;\n\n    ListNode* newHead = reverseList(head->next);\n    head->next->next = head;\n    head->next = nullptr;\n    return newHead;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/206.html",
    "category": "Algorithms",
    "acceptance_rate": 79.02436398675701,
    "topics": [
      "Linked List",
      "Recursion"
    ],
    "hints": [],
    "likes": 22874,
    "dislikes": 527,
    "similar_questions": "[{\"title\": \"Reverse Linked List II\", \"titleSlug\": \"reverse-linked-list-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Upside Down\", \"titleSlug\": \"binary-tree-upside-down\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Linked List\", \"titleSlug\": \"palindrome-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse Nodes in Even Length Groups\", \"titleSlug\": \"reverse-nodes-in-even-length-groups\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Twin Sum of a Linked List\", \"titleSlug\": \"maximum-twin-sum-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Remove Nodes From Linked List\", \"titleSlug\": \"remove-nodes-from-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insert Greatest Common Divisors in Linked List\", \"titleSlug\": \"insert-greatest-common-divisors-in-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"5.2M\", \"totalSubmission\": \"6.6M\", \"totalAcceptedRaw\": 5211790, \"totalSubmissionRaw\": 6595172, \"acRate\": \"79.0%\"}",
    "title_pt": "Inverter Lista Encadeada",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada simplesmente ligada, inverta a lista e retorne <em>a lista invertida</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg\" style=\"width: 542px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5]\n<strong>Saída:</strong> [5,4,3,2,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg\" style=\"width: 182px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2]\n<strong>Saída:</strong> [2,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 5000]</code>.</li>\n\t<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Uma lista encadeada pode ser invertida tanto iterativamente quanto recursivamente. Você conseguiria implementar ambos?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "207",
    "paidOnly": false,
    "title": "Course Schedule",
    "titleSlug": "course-schedule",
    "url": "https://leetcode.com/problems/course-schedule",
    "description_url": "https://leetcode.com/problems/course-schedule/description/",
    "description": "<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p>\n\n<ul>\n\t<li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li>\n</ul>\n\n<p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numCourses &lt;= 2000</code></li>\n\t<li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li>\n\t<li><code>prerequisites[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>\n\t<li>All the pairs prerequisites[i] are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/course-schedule/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nfrom enum import Enum\n\n\nclass State(Enum):\n  kInit = 0\n  kVisiting = 1\n  kVisited = 2\n\n\nclass Solution:\n  def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n    graph = [[] for _ in range(numCourses)]\n    state = [State.kInit] * numCourses\n\n    for a, b in prerequisites:\n      graph[b].append(a)\n\n    def hasCycle(u: int) -> bool:\n      if state[u] == State.kVisiting:\n        return True\n      if state[u] == State.kVisited:\n        return False\n\n      state[u] = State.kVisiting\n      if any(hasCycle(v) for v in graph[u]):\n        return True\n      state[u] = State.kVisited\n\n      return False\n\n    return not any(hasCycle(i) for i in range(numCourses))",
    "solution_code_java": "\t\t\t\n\nenum State { kInit, kVisiting, kVisited }\n\nclass Solution {\n  public boolean canFinish(int numCourses, int[][] prerequisites) {\n    List<Integer>[] graph = new List[numCourses];\n    State[] state = new State[numCourses];\n\n    for (int i = 0; i < numCourses; ++i)\n      graph[i] = new ArrayList<>();\n\n    for (int[] p : prerequisites)\n      graph[p[1]].add(p[0]);\n\n    for (int i = 0; i < numCourses; ++i)\n      if (hasCycle(graph, i, state))\n        return false;\n\n    return true;\n  }\n\n  private boolean hasCycle(List<Integer>[] graph, int u, State[] state) {\n    if (state[u] == State.kVisiting)\n      return true;\n    if (state[u] == State.kVisited)\n      return false;\n\n    state[u] = State.kVisiting;\n    for (final int v : graph[u])\n      if (hasCycle(graph, v, state))\n        return true;\n    state[u] = State.kVisited;\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nenum class State { kInit, kVisiting, kVisited };\n\nclass Solution {\n public:\n  bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {\n    vector<vector<int>> graph(numCourses);\n    vector<State> state(numCourses);\n\n    for (const vector<int>& p : prerequisites)\n      graph[p[1]].push_back(p[0]);\n\n    for (int i = 0; i < numCourses; ++i)\n      if (hasCycle(graph, i, state))\n        return false;\n\n    return true;\n  }\n\n private:\n  bool hasCycle(const vector<vector<int>>& graph, int u, vector<State>& state) {\n    if (state[u] == State::kVisiting)\n      return true;\n    if (state[u] == State::kVisited)\n      return false;\n\n    state[u] = State::kVisiting;\n    for (const int v : graph[u])\n      if (hasCycle(graph, v, state))\n        return true;\n    state[u] = State::kVisited;\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/207.html",
    "category": "Algorithms",
    "acceptance_rate": 48.970712263549,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Graph",
      "Topological Sort"
    ],
    "hints": [
      "This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.",
      "<a href=\"https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/03Graphs.pdf\" target=\"_blank\">Topological Sort via DFS</a> - A great tutorial explaining the basic concepts of Topological Sort.",
      "Topological sort could also be done via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>."
    ],
    "likes": 17044,
    "dislikes": 803,
    "similar_questions": "[{\"title\": \"Course Schedule II\", \"titleSlug\": \"course-schedule-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Graph Valid Tree\", \"titleSlug\": \"graph-valid-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Height Trees\", \"titleSlug\": \"minimum-height-trees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Course Schedule III\", \"titleSlug\": \"course-schedule-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Build a Matrix With Conditions\", \"titleSlug\": \"build-a-matrix-with-conditions\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2060679, \"totalSubmissionRaw\": 4207992, \"acRate\": \"49.0%\"}",
    "title_pt": "Cronograma de Cursos",
    "description_pt": "<p>Há um total de <code>numCourses</code> cursos que você precisa fazer, numerados de <code>0</code> a <code>numCourses - 1</code>. Você recebe um array <code>prerequisites</code> onde <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indica que você <strong>deve</strong> fazer o curso <code>b<sub>i</sub></code> primeiro se quiser fazer o curso <code>a<sub>i</sub></code>.</p>\n\n<ul>\n\t<li>Por exemplo, o par <code>[0, 1]</code> indica que, para fazer o curso <code>0</code>, você precisa primeiro fazer o curso <code>1</code>.</li>\n</ul>\n\n<p>Retorne <code>true</code> se você conseguir concluir todos os cursos. Caso contrário, retorne <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numCourses = 2, prerequisites = [[1,0]]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Há um total de 2 cursos para fazer. \nPara fazer o curso 1 você deveria ter concluído o curso 0. Portanto, é possível.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Há um total de 2 cursos para fazer. \nPara fazer o curso 1 você deveria ter concluído o curso 0, e para fazer o curso 0 você também deveria ter concluído o curso 1. Portanto, é impossível.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numCourses &lt;= 2000</code></li>\n\t<li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li>\n\t<li><code>prerequisites[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>\n\t<li>Todos os pares prerequisites[i] são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Este problema é equivalente a descobrir se existe um ciclo em um grafo direcionado. Se existir um ciclo, nenhuma ordenação topológica existe e, portanto, será impossível fazer todos os cursos.",
      "Dica 2: <a href=\"https://www.cs.princeton.edu/~wayne/kleinberg-tardos/pdf/03Graphs.pdf\" target=\"_blank\">Ordenação Topológica via DFS</a> - Um ótimo tutorial explicando os conceitos básicos de Ordenação Topológica.",
      "Dica 3: A ordenação topológica também pode ser feita via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "208",
    "paidOnly": false,
    "title": "Implement Trie (Prefix Tree)",
    "titleSlug": "implement-trie-prefix-tree",
    "url": "https://leetcode.com/problems/implement-trie-prefix-tree",
    "description_url": "https://leetcode.com/problems/implement-trie-prefix-tree/description/",
    "description": "<p>A <a href=\"https://en.wikipedia.org/wiki/Trie\" target=\"_blank\"><strong>trie</strong></a> (pronounced as &quot;try&quot;) or <strong>prefix tree</strong> is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.</p>\n\n<p>Implement the Trie class:</p>\n\n<ul>\n\t<li><code>Trie()</code> Initializes the trie object.</li>\n\t<li><code>void insert(String word)</code> Inserts the string <code>word</code> into the trie.</li>\n\t<li><code>boolean search(String word)</code> Returns <code>true</code> if the string <code>word</code> is in the trie (i.e., was inserted before), and <code>false</code> otherwise.</li>\n\t<li><code>boolean startsWith(String prefix)</code> Returns <code>true</code> if there is a previously inserted string <code>word</code> that has the prefix <code>prefix</code>, and <code>false</code> otherwise.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;]\n[[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]]\n<strong>Output</strong>\n[null, null, true, false, true, null, true]\n\n<strong>Explanation</strong>\nTrie trie = new Trie();\ntrie.insert(&quot;apple&quot;);\ntrie.search(&quot;apple&quot;);   // return True\ntrie.search(&quot;app&quot;);     // return False\ntrie.startsWith(&quot;app&quot;); // return True\ntrie.insert(&quot;app&quot;);\ntrie.search(&quot;app&quot;);     // return True\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li>\n\t<li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/implement-trie-prefix-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass TrieNode:\n  def __init__(self):\n    self.children: Dict[str, TrieNode] = defaultdict(TrieNode)\n    self.isWord = False\n\n\nclass Trie:\n  def __init__(self):\n    self.root = TrieNode()\n\n  def insert(self, word: str) -> None:\n    node: TrieNode = self.root\n    for c in word:\n      if c not in node.children:\n        node.children[c] = TrieNode()\n      node = node.children[c]\n    node.isWord = True\n\n  def search(self, word: str) -> bool:\n    node: TrieNode = self._find(word)\n    return node and node.isWord\n\n  def startsWith(self, prefix: str) -> bool:\n    return self._find(prefix)\n\n  def _find(self, prefix: str) -> Optional[TrieNode]:\n    node: TrieNode = self.root\n    for c in prefix:\n      if c not in node.children:\n        return None\n      node = node.children[c]\n    return node",
    "solution_code_java": "\t\t\t\n\nclass TrieNode {\n  public TrieNode[] children = new TrieNode[26];\n  public boolean isWord = false;\n}\n\nclass Trie {\n  public void insert(String word) {\n    TrieNode node = root;\n    for (final char c : word.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n    }\n    node.isWord = true;\n  }\n\n  public boolean search(String word) {\n    TrieNode node = find(word);\n    return node != null && node.isWord;\n  }\n\n  public boolean startsWith(String prefix) {\n    return find(prefix) != null;\n  }\n\n  private TrieNode root = new TrieNode();\n\n  private TrieNode find(String prefix) {\n    TrieNode node = root;\n    for (final char c : prefix.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        return null;\n      node = node.children[i];\n    }\n    return node;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  bool isWord = false;\n  TrieNode() : children(26) {}\n};\n\nclass Trie {\n public:\n  void insert(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n    }\n    node->isWord = true;\n  }\n\n  bool search(const string& word) {\n    shared_ptr<TrieNode> node = find(word);\n    return node && node->isWord;\n  }\n\n  bool startsWith(const string& prefix) {\n    return find(prefix) != nullptr;\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n\n  shared_ptr<TrieNode> find(const string& prefix) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : prefix) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        return nullptr;\n      node = node->children[i];\n    }\n    return node;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/208.html",
    "category": "Algorithms",
    "acceptance_rate": 67.72500606988775,
    "topics": [
      "Hash Table",
      "String",
      "Design",
      "Trie"
    ],
    "hints": [],
    "likes": 12009,
    "dislikes": 149,
    "similar_questions": "[{\"title\": \"Design Add and Search Words Data Structure\", \"titleSlug\": \"design-add-and-search-words-data-structure\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design Search Autocomplete System\", \"titleSlug\": \"design-search-autocomplete-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Replace Words\", \"titleSlug\": \"replace-words\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Implement Magic Dictionary\", \"titleSlug\": \"implement-magic-dictionary\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Encrypt and Decrypt Strings\", \"titleSlug\": \"encrypt-and-decrypt-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Implement Trie II (Prefix Tree)\", \"titleSlug\": \"implement-trie-ii-prefix-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Prefix and Suffix Pairs II\", \"titleSlug\": \"count-prefix-and-suffix-pairs-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Prefix and Suffix Pairs I\", \"titleSlug\": \"count-prefix-and-suffix-pairs-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1305422, \"totalSubmissionRaw\": 1927534, \"acRate\": \"67.7%\"}",
    "title_pt": "Implementar Trie (Árvore de Prefixos)",
    "description_pt": "<p>Uma <a href=\"https://en.wikipedia.org/wiki/Trie\" target=\"_blank\"><strong>trie</strong></a> (pronunciada como &quot;try&quot;) ou <strong>árvore de prefixos</strong> é uma estrutura de dados em árvore usada para armazenar e recuperar chaves de forma eficiente em um conjunto de strings. Há várias aplicações dessa estrutura de dados, como autocompletar e verificador ortográfico.</p>\n\n<p>Implemente a classe Trie:</p>\n\n<ul>\n\t<li><code>Trie()</code> Inicializa o objeto trie.</li>\n\t<li><code>void insert(String word)</code> Insere a string <code>word</code> na trie.</li>\n\t<li><code>boolean search(String word)</code> Retorna <code>true</code> se a string <code>word</code> estiver na trie (ou seja, foi inserida anteriormente), e <code>false</code> caso contrário.</li>\n\t<li><code>boolean startsWith(String prefix)</code> Retorna <code>true</code> se existir uma string <code>word</code> inserida anteriormente que tenha o prefixo <code>prefix</code>, e <code>false</code> caso contrário.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Trie&quot;, &quot;insert&quot;, &quot;search&quot;, &quot;search&quot;, &quot;startsWith&quot;, &quot;insert&quot;, &quot;search&quot;]\n[[], [&quot;apple&quot;], [&quot;apple&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;], [&quot;app&quot;]]\n<strong>Saída</strong>\n[null, null, true, false, true, null, true]\n\n<strong>Explicação</strong>\nTrie trie = new Trie();\ntrie.insert(&quot;apple&quot;);\ntrie.search(&quot;apple&quot;);   // return True\ntrie.search(&quot;app&quot;);     // return False\ntrie.startsWith(&quot;app&quot;); // return True\ntrie.insert(&quot;app&quot;);\ntrie.search(&quot;app&quot;);     // return True\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length, prefix.length &lt;= 2000</code></li>\n\t<li><code>word</code> and <code>prefix</code> consist only of lowercase English letters.</li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>search</code>, and <code>startsWith</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "209",
    "paidOnly": false,
    "title": "Minimum Size Subarray Sum",
    "titleSlug": "minimum-size-subarray-sum",
    "url": "https://leetcode.com/problems/minimum-size-subarray-sum",
    "description_url": "https://leetcode.com/problems/minimum-size-subarray-sum/description/",
    "description": "<p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return <em>the <strong>minimal length</strong> of a </em><span data-keyword=\"subarray-nonempty\"><em>subarray</em></span><em> whose sum is greater than or equal to</em> <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> target = 4, nums = [1,4,4]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.",
    "solution_url": "https://leetcode.com/problems/minimum-size-subarray-sum/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nGiven an array of positive integers `nums` and a positive integer `target`, our task is to return the minimal length of a subarray whose sum is greater than or equal to `target`. If there is no such subarray, we have to return `0`.\n\n---\n\n### Approach: Sliding Window\n\n#### Intuition\n\nAn intuitive technique is to go through all the subarrays one by one and check the sum of each one. If the total of the subarray under consideration is larger than or equal to `target`, we attempt to update our answer variable by using the minimum of the current answer and the length of this subarray. To get all the subarrays, we can run two loops: the outer loop selects a starting point and the inner loop selects an ending point. This solution, however, will take $O(n^2)$ time, resulting in a time limit exceeded (TLE).\n\nLet's think whether we really need to iterate over all the subarrays. \n\nGiven that we only have positive integers, there is no purpose in adding further elements to a subarray if its sum exceeds or equals `target`. Adding more elements to such a subarray will result in the construction of longer subarrays, which is useless because we have already found a smaller subarray that meets our requirements.\n\nOnly if the sum of the current subarray under consideration is smaller than `target`, we should append elements to the subarray. When the sum of the subarrays exceeds or equals `target`, we will attempt to update our answer with the length of the current subarray.\n\nWe now try to remove the elements from the start and see if we can form a smaller subarray that meets our requirements. We remove the first element from the subarray and check if we still have the total higher than or equal to `target`. If the total exceeds or equals `target`, we have a smaller subarray that meets our requirement. As a result, we again try to update our answer with the length of the current subarray and repeat the process of eliminating the first element from the current subarray until the sum no longer exceeds or equals `target`.\n\nNow after removing elements, if the sum of the subarray is less than `target`, we have to append more elements to it until the sum becomes larger than or equal to `target`. We append elements until the sum equals or exceeds `target`, then try to update our answer variable and repeat the process of eliminating the first element.\n\nThe above approach can be efficiently solved using the **sliding window approach**.\n\nIf you are not familiar with sliding window, please refer to our explore cards [Sliding Window Explore Card](https://leetcode.com/explore/featured/card/leetcodes-interview-crash-course-data-structures-and-algorithms/703/arraystrings/4502/).\n\nA sliding window is achieved by using two pointers `left` and `right`, which point to the starting and ending indices of the subarray. We set them to a value of `0`.\n\nTo \"add\" elements to the window, we loop over the array by incrementing `right`. In this problem, if the sum of the window exceeds or equals `target`, we try to update our answer and then \"remove\" elements from the window by incrementing `left` until the sum is less than `target` again.\n\nHere's a visual representation of how the approach works:\n\n!?!../Documents/209/209-slides.json:601,301!?!\n\n#### Algorithm\n\n1. Create three integer variables `left`, `right` and `sumOfCurrentWindow`. The variables `left` and `right` form a subarray by pointing to the starting and ending indices of the current subarray (or window), and `sumOfCurrentWindow` stores the sum of this window. Initialize all of them with `0`.\n2. Create another variable `res` to store the answer to the problem. We initialize it to a large integer value.\n3. We iterate over `nums` using `right` starting from `right = 0` till `nums.length - 1` incrementing `right` by `1` after each iteration. We perform the following inside this iteration: \n    - Add element at index `right` to the current window, incrementing `sumOfCurrentWindow` by `nums[right]`.\n    - We check if `sumOfCurrentWindow >= target`. If so, we have a subarray that satisfies our condition. As a result, we attempt to update our answer variable with the length of this subarray. We perform `res = min(res, right - left + 1)`. We then remove the first element from this window by reducing `sumOfCurrentWindow` by `nums[left]` and incrementing `left` by `1`. This step is repeated in an inner loop as long as `sumOfCurrentWindow >= target`.\n    - The current window's sum is now smaller than `target`. We need to add more elements to it. As a result, `right` is incremented by `1`.\n4. Return `res`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/AX72e7bN/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"AX72e7bN\"></iframe>\n\n#### Complexity Analysis\n\nHere $n$ is the length of `nums`.\n\n* Time complexity: $O(n)$.\n    - You may be thinking: there is an inner while loop inside another for loop, isn't the time complexity $O(n^2)$? The reason it is still $O(n)$ is because the right pointer `right` can move $n$ times and the left pointer `left` can move also $n$ times in total. The inner loop is not running $n$ times for each iteration of the outer loop. A sliding window guarantees a maximum of $2n$ window iterations. This is what is referred to as [amortized analysis](https://en.wikipedia.org/wiki/Amortized_analysis) - even though the worst case for an iteration inside the for loop is $O(n)$, it averages out to $O(1)$ when you consider the entire runtime of the algorithm.\n\n* Space complexity: $O(1)$.\n    - We are not using any extra space other than a few integer variables:`left`, `right`, `sumOfCurrentWindow`, and `res`, which takes up constant space each.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minSubArrayLen(self, s: int, nums: List[int]) -> int:\n    ans = math.inf\n    summ = 0\n    j = 0\n\n    for i, num in enumerate(nums):\n      summ += num\n      while summ >= s:\n        ans = min(ans, i - j + 1)\n        summ -= nums[j]\n        j += 1\n\n    return ans if ans != math.inf else 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minSubArrayLen(int s, int[] nums) {\n    int ans = Integer.MAX_VALUE;\n    int sum = 0;\n\n    for (int l = 0, r = 0; r < nums.length; ++r) {\n      sum += nums[r];\n      while (sum >= s) {\n        ans = Math.min(ans, r - l + 1);\n        sum -= nums[l++];\n      }\n    }\n\n    return ans != Integer.MAX_VALUE ? ans : 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minSubArrayLen(int s, vector<int>& nums) {\n    int ans = INT_MAX;\n    int sum = 0;\n\n    for (int l = 0, r = 0; r < nums.size(); ++r) {\n      sum += nums[r];\n      while (sum >= s) {\n        ans = min(ans, r - l + 1);\n        sum -= nums[l++];\n      }\n    }\n\n    return ans < INT_MAX ? ans : 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/209.html",
    "category": "Algorithms",
    "acceptance_rate": 49.17706234881324,
    "topics": [
      "Array",
      "Binary Search",
      "Sliding Window",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 13392,
    "dislikes": 494,
    "similar_questions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Size Subarray Sum Equals k\", \"titleSlug\": \"maximum-size-subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Length of Repeated Subarray\", \"titleSlug\": \"maximum-length-of-repeated-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Reduce X to Zero\", \"titleSlug\": \"minimum-operations-to-reduce-x-to-zero\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Radius Subarray Averages\", \"titleSlug\": \"k-radius-subarray-averages\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Product After K Increments\", \"titleSlug\": \"maximum-product-after-k-increments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Subarray With OR at Least K I\", \"titleSlug\": \"shortest-subarray-with-or-at-least-k-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Positive Sum Subarray \", \"titleSlug\": \"minimum-positive-sum-subarray\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.9M\", \"totalAcceptedRaw\": 1439535, \"totalSubmissionRaw\": 2927248, \"acRate\": \"49.2%\"}",
    "title_pt": "Subarray de Soma Mínima",
    "description_pt": "<p>Dado um array de inteiros positivos <code>nums</code> e um inteiro positivo <code>target</code>, retorne <em>o <strong>comprimento mínimo</strong> de uma </em><span data-keyword=\"subarray-nonempty\"><em>subarray</em></span><em> cuja soma seja maior ou igual a</em> <code>target</code>. Se não houver tal subarray, retorne <code>0</code> em vez disso.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> target = 7, nums = [2,3,1,2,4,3]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A subarray [4,3] tem o comprimento mínimo sob a restrição do problema.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> target = 4, nums = [1,4,4]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> target = 11, nums = [1,1,1,1,1,1,1,1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Se você encontrou a solução <code>O(n)</code>, tente codificar outra solução cuja complexidade de tempo seja <code>O(n log(n))</code>.",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "210",
    "paidOnly": false,
    "title": "Course Schedule II",
    "titleSlug": "course-schedule-ii",
    "url": "https://leetcode.com/problems/course-schedule-ii",
    "description_url": "https://leetcode.com/problems/course-schedule-ii/description/",
    "description": "<p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p>\n\n<ul>\n\t<li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li>\n</ul>\n\n<p>Return <em>the ordering of courses you should take to finish all courses</em>. If there are many valid answers, return <strong>any</strong> of them. If it is impossible to finish all courses, return <strong>an empty array</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]]\n<strong>Output:</strong> [0,1]\n<strong>Explanation:</strong> There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\n<strong>Output:</strong> [0,2,1,3]\n<strong>Explanation:</strong> There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> numCourses = 1, prerequisites = []\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numCourses &lt;= 2000</code></li>\n\t<li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li>\n\t<li><code>prerequisites[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>All the pairs <code>[a<sub>i</sub>, b<sub>i</sub>]</code> are <strong>distinct</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/course-schedule-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nfrom enum import Enum\n\n\nclass State(Enum):\n  kInit = 0\n  kVisiting = 1\n  kVisited = 2\n\n\nclass Solution:\n  def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n    ans = []\n    graph = [[] for _ in range(numCourses)]\n    state = [State.kInit] * numCourses\n\n    for v, u in prerequisites:\n      graph[u].append(v)\n\n    def hasCycle(u: int) -> bool:\n      if state[u] == State.kVisiting:\n        return True\n      if state[u] == State.kVisited:\n        return False\n\n      state[u] = State.kVisiting\n      if any(hasCycle(v) for v in graph[u]):\n        return True\n      state[u] = State.kVisited\n      ans.append(u)\n\n      return False\n\n    if any(hasCycle(i) for i in range(numCourses)):\n      return []\n\n    return ans[::-1]",
    "solution_code_java": "\t\t\t\n\nenum State { kInit, kVisiting, kVisited }\n\nclass Solution {\n  public int[] findOrder(int numCourses, int[][] prerequisites) {\n    Deque<Integer> ans = new ArrayDeque<>();\n    List<Integer>[] graph = new List[numCourses];\n    State[] state = new State[numCourses];\n\n    for (int i = 0; i < numCourses; ++i)\n      graph[i] = new ArrayList<>();\n\n    for (int[] p : prerequisites)\n      graph[p[1]].add(p[0]);\n\n    for (int i = 0; i < numCourses; ++i)\n      if (hasCycle(graph, i, state, ans))\n        return new int[] {};\n\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n\n  private boolean hasCycle(List<Integer>[] graph, int u, State[] state, Deque<Integer> ans) {\n    if (state[u] == State.kVisiting)\n      return true;\n    if (state[u] == State.kVisited)\n      return false;\n\n    state[u] = State.kVisiting;\n    for (final int v : graph[u])\n      if (hasCycle(graph, v, state, ans))\n        return true;\n    state[u] = State.kVisited;\n    ans.addFirst(u);\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nenum class State { kInit, kVisiting, kVisited };\n\nclass Solution {\n public:\n  vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {\n    vector<int> ans;\n    vector<vector<int>> graph(numCourses);\n    vector<State> state(numCourses);\n\n    for (const auto& p : prerequisites)\n      graph[p[1]].push_back(p[0]);\n\n    for (int i = 0; i < numCourses; ++i)\n      if (hasCycle(graph, i, state, ans))\n        return {};\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n\n private:\n  bool hasCycle(const vector<vector<int>>& graph, int u, vector<State>& state,\n                vector<int>& ans) {\n    if (state[u] == State::kVisiting)\n      return true;\n    if (state[u] == State::kVisited)\n      return false;\n\n    state[u] = State::kVisiting;\n    for (const int v : graph[u])\n      if (hasCycle(graph, v, state, ans))\n        return true;\n    state[u] = State::kVisited;\n    ans.push_back(u);\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/210.html",
    "category": "Algorithms",
    "acceptance_rate": 53.15596345369836,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Graph",
      "Topological Sort"
    ],
    "hints": [
      "This problem is equivalent to finding the topological order in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.",
      "<a href=\"https://www.youtube.com/watch?v=ozso3xxkVGU\" target=\"_blank\">Topological Sort via DFS</a> - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.",
      "Topological sort could also be done via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>."
    ],
    "likes": 11315,
    "dislikes": 364,
    "similar_questions": "[{\"title\": \"Course Schedule\", \"titleSlug\": \"course-schedule\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Alien Dictionary\", \"titleSlug\": \"alien-dictionary\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Height Trees\", \"titleSlug\": \"minimum-height-trees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sequence Reconstruction\", \"titleSlug\": \"sequence-reconstruction\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Course Schedule III\", \"titleSlug\": \"course-schedule-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Parallel Courses\", \"titleSlug\": \"parallel-courses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All Possible Recipes from Given Supplies\", \"titleSlug\": \"find-all-possible-recipes-from-given-supplies\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Build a Matrix With Conditions\", \"titleSlug\": \"build-a-matrix-with-conditions\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sort Array by Moving Items to Empty Space\", \"titleSlug\": \"sort-array-by-moving-items-to-empty-space\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1356914, \"totalSubmissionRaw\": 2552705, \"acRate\": \"53.2%\"}",
    "title_pt": "Curso de Programação II",
    "description_pt": "<p>Há um total de <code>numCourses</code> cursos que você precisa fazer, numerados de <code>0</code> a <code>numCourses - 1</code>. Você recebe um array <code>prerequisites</code> em que <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indica que você <strong>deve</strong> fazer o curso <code>b<sub>i</sub></code> primeiro se quiser fazer o curso <code>a<sub>i</sub></code>.</p>\n\n<ul>\n\t<li>Por exemplo, o par <code>[0, 1]</code> indica que, para fazer o curso <code>0</code>, você precisa קודם fazer o curso <code>1</code>.</li>\n</ul>\n\n<p>Retorne <em>a ordem dos cursos que você deve fazer para concluir todos os cursos</em>. Se houver muitas respostas válidas, retorne <strong>qualquer</strong> uma delas. Se for impossível concluir todos os cursos, retorne <strong>um array vazio</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numCourses = 2, prerequisites = [[1,0]]\n<strong>Saída:</strong> [0,1]\n<strong>Explicação:</strong> Há um total de 2 cursos a fazer. Para fazer o curso 1, você deve ter concluído o curso 0. Portanto, a ordem correta dos cursos é [0,1].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\n<strong>Saída:</strong> [0,2,1,3]\n<strong>Explicação:</strong> Há um total de 4 cursos a fazer. Para fazer o curso 3, você deve ter concluído os cursos 1 e 2. Tanto o curso 1 quanto o curso 2 devem ser feitos depois que você concluir o curso 0.\nPortanto, uma ordem correta dos cursos é [0,1,2,3]. Outra ordem correta é [0,2,1,3].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> numCourses = 1, prerequisites = []\n<strong>Saída:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= numCourses &lt;= 2000</code></li>\n\t<li><code>0 &lt;= prerequisites.length &lt;= numCourses * (numCourses - 1)</code></li>\n\t<li><code>prerequisites[i].length == 2</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>Todos os pares <code>[a<sub>i</sub>, b<sub>i</sub>]</code> são <strong>distintos</strong>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Este problema é equivalente a encontrar a ordem topológica em um grafo direcionado. Se existir um ciclo, nenhuma ordem topológica existe e, portanto, será impossível fazer todos os cursos.",
      "Dica 2: <a href=\"https://www.youtube.com/watch?v=ozso3xxkVGU\" target=\"_blank\">Ordenação Topológica via DFS</a> - Um ótimo tutorial em vídeo (21 minutos) na Coursera explicando os conceitos básicos de Ordenação Topológica.",
      "Dica 3: A ordenação topológica também pode ser feita via <a href=\"http://en.wikipedia.org/wiki/Topological_sorting#Algorithms\" target=\"_blank\">BFS</a>."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "211",
    "paidOnly": false,
    "title": "Design Add and Search Words Data Structure",
    "titleSlug": "design-add-and-search-words-data-structure",
    "url": "https://leetcode.com/problems/design-add-and-search-words-data-structure",
    "description_url": "https://leetcode.com/problems/design-add-and-search-words-data-structure/description/",
    "description": "<p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p>\n\n<p>Implement the <code>WordDictionary</code> class:</p>\n\n<ul>\n\t<li><code>WordDictionary()</code>&nbsp;Initializes the object.</li>\n\t<li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li>\n\t<li><code>bool search(word)</code>&nbsp;Returns <code>true</code> if there is any string in the data structure that matches <code>word</code>&nbsp;or <code>false</code> otherwise. <code>word</code> may contain dots <code>&#39;.&#39;</code> where dots can be matched with any letter.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;]\n[[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]]\n<strong>Output</strong>\n[null,null,null,null,false,true,true,true]\n\n<strong>Explanation</strong>\nWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(&quot;bad&quot;);\nwordDictionary.addWord(&quot;dad&quot;);\nwordDictionary.addWord(&quot;mad&quot;);\nwordDictionary.search(&quot;pad&quot;); // return False\nwordDictionary.search(&quot;bad&quot;); // return True\nwordDictionary.search(&quot;.ad&quot;); // return True\nwordDictionary.search(&quot;b..&quot;); // return True\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length &lt;= 25</code></li>\n\t<li><code>word</code> in <code>addWord</code> consists of lowercase English letters.</li>\n\t<li><code>word</code> in <code>search</code> consist of <code>&#39;.&#39;</code> or lowercase English letters.</li>\n\t<li>There will be at most <code>2</code> dots in <code>word</code> for <code>search</code> queries.</li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>addWord</code> and <code>search</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-add-and-search-words-data-structure/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass TrieNode:\n  def __init__(self):\n    self.children: Dict[str, TrieNode] = defaultdict(TrieNode)\n    self.isWord = False\n\n\nclass WordDictionary:\n  def __init__(self):\n    self.root = TrieNode()\n\n  def addWord(self, word: str) -> None:\n    node: TrieNode = self.root\n    for c in word:\n      if c not in node.children:\n        node.children[c] = TrieNode()\n      node = node.children[c]\n    node.isWord = True\n\n  def search(self, word: str) -> bool:\n    return self._dfs(word, 0, self.root)\n\n  def _dfs(self, word: str, s: int, node: TrieNode) -> bool:\n    if s == len(word):\n      return node.isWord\n    if word[s] != '.':\n      next: TrieNode = node.children[word[s]]\n      return self._dfs(word, s + 1, next) if next else False\n\n    for c in string.ascii_lowercase:\n      if c in node.children and self._dfs(word, s + 1, node.children[c]):\n        return True\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass TrieNode {\n  public TrieNode[] children = new TrieNode[26];\n  public boolean isWord = false;\n}\n\nclass WordDictionary {\n  public void addWord(String word) {\n    TrieNode node = root;\n    for (final char c : word.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n    }\n    node.isWord = true;\n  }\n\n  public boolean search(String word) {\n    return dfs(word, 0, root);\n  }\n\n  private TrieNode root = new TrieNode();\n\n  private boolean dfs(String word, int s, TrieNode node) {\n    if (s == word.length())\n      return node.isWord;\n    if (word.charAt(s) != '.') {\n      TrieNode next = node.children[word.charAt(s) - 'a'];\n      return next == null ? false : dfs(word, s + 1, next);\n    }\n\n    // Word.charAt(s) == '.' -> search all 26 children\n    for (int i = 0; i < 26; ++i)\n      if (node.children[i] != null && dfs(word, s + 1, node.children[i]))\n        return true;\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  bool isWord = false;\n  TrieNode() : children(26) {}\n};\n\nclass WordDictionary {\n public:\n  void addWord(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n    }\n    node->isWord = true;\n  }\n\n  bool search(const string& word) {\n    return dfs(word, 0, root);\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n\n  bool dfs(const string& word, int s, shared_ptr<TrieNode> node) {\n    if (s == word.length())\n      return node->isWord;\n    if (word[s] != '.') {\n      shared_ptr<TrieNode> next = node->children[word[s] - 'a'];\n      return next ? dfs(word, s + 1, next) : false;\n    }\n\n    // word[s] == '.' -> search all 26 children\n    for (int i = 0; i < 26; ++i)\n      if (node->children[i] && dfs(word, s + 1, node->children[i]))\n        return true;\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/211.html",
    "category": "Algorithms",
    "acceptance_rate": 46.89738354206017,
    "topics": [
      "String",
      "Depth-First Search",
      "Design",
      "Trie"
    ],
    "hints": [
      "You should be familiar with how a Trie works. If not, please work on this problem: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a> first."
    ],
    "likes": 7847,
    "dislikes": 478,
    "similar_questions": "[{\"title\": \"Implement Trie (Prefix Tree)\", \"titleSlug\": \"implement-trie-prefix-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Prefix and Suffix Search\", \"titleSlug\": \"prefix-and-suffix-search\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Match Substring After Replacement\", \"titleSlug\": \"match-substring-after-replacement\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sum of Prefix Scores of Strings\", \"titleSlug\": \"sum-of-prefix-scores-of-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Prefix and Suffix Pairs II\", \"titleSlug\": \"count-prefix-and-suffix-pairs-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Prefix and Suffix Pairs I\", \"titleSlug\": \"count-prefix-and-suffix-pairs-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"766K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 765974, \"totalSubmissionRaw\": 1633305, \"acRate\": \"46.9%\"}",
    "title_pt": "Projetar Estrutura de Dados para Adicionar e Pesquisar Palavras",
    "description_pt": "<p>Projete uma estrutura de dados que ofereça suporte à adição de novas palavras e à verificação de se uma string corresponde a alguma string adicionada anteriormente.</p>\n\n<p>Implemente a classe <code>WordDictionary</code>:</p>\n\n<ul>\n\t<li><code>WordDictionary()</code>&nbsp;Inicializa o objeto.</li>\n\t<li><code>void addWord(word)</code> Adiciona <code>word</code> à estrutura de dados; ela pode ser correspondida posteriormente.</li>\n\t<li><code>bool search(word)</code>&nbsp;Retorna <code>true</code> se houver qualquer string na estrutura de dados que corresponda a <code>word</code>&nbsp;ou <code>false</code> caso contrário. <code>word</code> pode conter pontos <code>&#39;.&#39;</code>, e os pontos podem corresponder a qualquer letra.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;]\n[[],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]]\n<strong>Saída</strong>\n[null,null,null,null,false,true,true,true]\n\n<strong>Explicação</strong>\nWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord(&quot;bad&quot;);\nwordDictionary.addWord(&quot;dad&quot;);\nwordDictionary.addWord(&quot;mad&quot;);\nwordDictionary.search(&quot;pad&quot;); // return False\nwordDictionary.search(&quot;bad&quot;); // return True\nwordDictionary.search(&quot;.ad&quot;); // return True\nwordDictionary.search(&quot;b..&quot;); // return True\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length &lt;= 25</code></li>\n\t<li><code>word</code> em <code>addWord</code> consiste em letras minúsculas do inglês.</li>\n\t<li><code>word</code> em <code>search</code> consiste em <code>&#39;.&#39;</code> ou letras minúsculas do inglês.</li>\n\t<li>Haverá no máximo <code>2</code> pontos em <code>word</code> para consultas de <code>search</code>.</li>\n\t<li>Serão feitas no máximo <code>10<sup>4</sup></code> chamadas a <code>addWord</code> e <code>search</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Você deve estar familiarizado com o funcionamento de uma Trie. Caso contrário, trabalhe primeiro neste problema: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a>."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "212",
    "paidOnly": false,
    "title": "Word Search II",
    "titleSlug": "word-search-ii",
    "url": "https://leetcode.com/problems/word-search-ii",
    "description_url": "https://leetcode.com/problems/word-search-ii/description/",
    "description": "<p>Given an <code>m x n</code> <code>board</code>&nbsp;of characters and a list of strings <code>words</code>, return <em>all words on the board</em>.</p>\n\n<p>Each word must be constructed from letters of sequentially adjacent cells, where <strong>adjacent cells</strong> are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search1.jpg\" style=\"width: 322px; height: 322px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;]\n<strong>Output:</strong> [&quot;eat&quot;,&quot;oath&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search2.jpg\" style=\"width: 162px; height: 162px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;]\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 12</code></li>\n\t<li><code>board[i][j]</code> is a lowercase English letter.</li>\n\t<li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n\t<li>All the strings of <code>words</code> are unique.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-search-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass TrieNode:\n  def __init__(self):\n    self.children: Dict[str, TrieNode] = defaultdict(TrieNode)\n    self.word: Optional[str] = None\n\n\nclass Solution:\n  def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n    m = len(board)\n    n = len(board[0])\n    ans = []\n    root = TrieNode()\n\n    def insert(word: str) -> None:\n      node = root\n      for c in word:\n        if c not in node.children:\n          node.children[c] = TrieNode()\n        node = node.children[c]\n      node.word = word\n\n    for word in words:\n      insert(word)\n\n    def dfs(i: int, j: int, node: TrieNode) -> None:\n      if i < 0 or i == m or j < 0 or j == n:\n        return\n      if board[i][j] == '*':\n        return\n\n      c = board[i][j]\n      if c not in node.children:\n        return\n\n      child = node.children[c]\n      if child.word:\n        ans.append(child.word)\n        child.word = None\n\n      board[i][j] = '*'\n      dfs(i + 1, j, child)\n      dfs(i - 1, j, child)\n      dfs(i, j + 1, child)\n      dfs(i, j - 1, child)\n      board[i][j] = c\n\n    for i in range(m):\n      for j in range(n):\n        dfs(i, j, root)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass TrieNode {\n  public TrieNode[] children = new TrieNode[26];\n  public String word;\n}\n\nclass Solution {\n  public List<String> findWords(char[][] board, String[] words) {\n    for (final String word : words)\n      insert(word);\n\n    List<String> ans = new ArrayList<>();\n\n    for (int i = 0; i < board.length; ++i)\n      for (int j = 0; j < board[0].length; ++j)\n        dfs(board, i, j, root, ans);\n\n    return ans;\n  }\n\n  private TrieNode root = new TrieNode();\n\n  private void insert(final String word) {\n    TrieNode node = root;\n    for (final char c : word.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n    }\n    node.word = word;\n  }\n\n  private void dfs(char[][] board, int i, int j, TrieNode node, List<String> ans) {\n    if (i < 0 || i == board.length || j < 0 || j == board[0].length)\n      return;\n    if (board[i][j] == '*')\n      return;\n\n    final char c = board[i][j];\n    TrieNode child = node.children[c - 'a'];\n    if (child == null)\n      return;\n    if (child.word != null) {\n      ans.add(child.word);\n      child.word = null;\n    }\n\n    board[i][j] = '*';\n    dfs(board, i + 1, j, child, ans);\n    dfs(board, i - 1, j, child, ans);\n    dfs(board, i, j + 1, child, ans);\n    dfs(board, i, j - 1, child, ans);\n    board[i][j] = c;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  const string* word = nullptr;\n  TrieNode() : children(26) {}\n};\n\nclass Solution {\n public:\n  vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {\n    vector<string> ans;\n\n    for (const string& word : words)\n      insert(word);\n\n    for (int i = 0; i < board.size(); ++i)\n      for (int j = 0; j < board[0].size(); ++j)\n        dfs(board, i, j, root, ans);\n\n    return ans;\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n\n  void insert(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n    }\n    node->word = &word;\n  }\n\n  void dfs(vector<vector<char>>& board, int i, int j, shared_ptr<TrieNode> node,\n           vector<string>& ans) {\n    if (i < 0 || i == board.size() || j < 0 || j == board[0].size())\n      return;\n    if (board[i][j] == '*')\n      return;\n\n    const char c = board[i][j];\n    shared_ptr<TrieNode> child = node->children[c - 'a'];\n    if (child == nullptr)\n      return;\n    if (child->word != nullptr) {\n      ans.push_back(*child->word);\n      child->word = nullptr;\n    }\n\n    board[i][j] = '*';\n    dfs(board, i + 1, j, child, ans);\n    dfs(board, i - 1, j, child, ans);\n    dfs(board, i, j + 1, child, ans);\n    dfs(board, i, j - 1, child, ans);\n    board[i][j] = c;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/212.html",
    "category": "Algorithms",
    "acceptance_rate": 37.216717935318364,
    "topics": [
      "Array",
      "String",
      "Backtracking",
      "Trie",
      "Matrix"
    ],
    "hints": [
      "You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier?",
      "If the current candidate does not exist in all words&#39; prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a> first."
    ],
    "likes": 9787,
    "dislikes": 490,
    "similar_questions": "[{\"title\": \"Word Search\", \"titleSlug\": \"word-search\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Unique Paths III\", \"titleSlug\": \"unique-paths-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Encrypt and Decrypt Strings\", \"titleSlug\": \"encrypt-and-decrypt-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"783.4K\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 783383, \"totalSubmissionRaw\": 2104917, \"acRate\": \"37.2%\"}",
    "title_pt": "Busca de Palavras II",
    "description_pt": "<p>Dado um <code>board</code>&nbsp;de caracteres de <code>m x n</code> e uma lista de strings <code>words</code>, retorne <em>todas as palavras no tabuleiro</em>.</p>\n\n<p>Cada palavra deve ser construída a partir de letras de células adjacentes sequencialmente, onde <strong>células adjacentes</strong> são vizinhas horizontalmente ou verticalmente. A mesma célula de letra não pode ser usada mais de uma vez em uma palavra.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search1.jpg\" style=\"width: 322px; height: 322px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;o&quot;,&quot;a&quot;,&quot;a&quot;,&quot;n&quot;],[&quot;e&quot;,&quot;t&quot;,&quot;a&quot;,&quot;e&quot;],[&quot;i&quot;,&quot;h&quot;,&quot;k&quot;,&quot;r&quot;],[&quot;i&quot;,&quot;f&quot;,&quot;l&quot;,&quot;v&quot;]], words = [&quot;oath&quot;,&quot;pea&quot;,&quot;eat&quot;,&quot;rain&quot;]\n<strong>Saída:</strong> [&quot;eat&quot;,&quot;oath&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/07/search2.jpg\" style=\"width: 162px; height: 162px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;a&quot;,&quot;b&quot;],[&quot;c&quot;,&quot;d&quot;]], words = [&quot;abcb&quot;]\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 12</code></li>\n\t<li><code>board[i][j]</code> é uma letra minúscula do alfabeto inglês.</li>\n\t<li><code>1 &lt;= words.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consiste em letras minúsculas do alfabeto inglês.</li>\n\t<li>Todas as strings de <code>words</code> são únicas.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Você precisaria otimizar seu backtracking para passar no teste maior. Você conseguiria interromper o backtracking mais cedo?",
      "Dica 2: Se o candidato atual não existir no prefixo de todas as palavras, você poderia interromper o backtracking imediatamente. Que tipo de estrutura de dados poderia responder a essa consulta de forma eficiente? Uma tabela hash funciona? Por quê ou por que não? E uma Trie? Se você quiser aprender como implementar uma trie básica, trabalhe neste problema: <a href=\"https://leetcode.com/problems/implement-trie-prefix-tree/\">Implement Trie (Prefix Tree)</a> primeiro."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "213",
    "paidOnly": false,
    "title": "House Robber II",
    "titleSlug": "house-robber-ii",
    "url": "https://leetcode.com/problems/house-robber-ii",
    "description_url": "https://leetcode.com/problems/house-robber-ii/description/",
    "description": "<p>You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are <strong>arranged in a circle.</strong> That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and&nbsp;<b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p>\n\n<p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <strong>without alerting the police</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/house-robber-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rob(self, nums: List[int]) -> int:\n    if not nums:\n      return 0\n    if len(nums) < 2:\n      return nums[0]\n\n    def rob(l: int, r: int) -> int:\n      dp1 = 0\n      dp2 = 0\n\n      for i in range(l, r + 1):\n        temp = dp1\n        dp1 = max(dp1, dp2 + nums[i])\n        dp2 = temp\n\n      return dp1\n\n    return max(rob(0, len(nums) - 2),\n               rob(1, len(nums) - 1))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int rob(int[] nums) {\n    if (nums.length == 0)\n      return 0;\n    if (nums.length == 1)\n      return nums[0];\n    return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));\n  }\n\n  private int rob(int[] nums, int l, int r) {\n    int prev1 = 0; // dp[i - 1]\n    int prev2 = 0; // dp[i - 2]\n\n    for (int i = l; i <= r; ++i) {\n      final int dp = Math.max(prev1, prev2 + nums[i]);\n      prev2 = prev1;\n      prev1 = dp;\n    }\n\n    return prev1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int rob(vector<int>& nums) {\n    if (nums.empty())\n      return 0;\n    if (nums.size() == 1)\n      return nums[0];\n\n    auto rob = [&](int l, int r) {\n      int prev1 = 0;  // dp[i - 1]\n      int prev2 = 0;  // dp[i - 2]\n\n      for (int i = l; i <= r; ++i) {\n        const int dp = max(prev1, prev2 + nums[i]);\n        prev2 = prev1;\n        prev1 = dp;\n      }\n\n      return prev1;\n    };\n\n    return max(rob(0, nums.size() - 2), rob(1, nums.size() - 1));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/213.html",
    "category": "Algorithms",
    "acceptance_rate": 43.416192164939375,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [
      "Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the <a href =\"https://leetcode.com/problems/house-robber/description/\">House Robber</a>, which is already been solved."
    ],
    "likes": 10432,
    "dislikes": 170,
    "similar_questions": "[{\"title\": \"House Robber\", \"titleSlug\": \"house-robber\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint House\", \"titleSlug\": \"paint-house\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint Fence\", \"titleSlug\": \"paint-fence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber III\", \"titleSlug\": \"house-robber-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Non-negative Integers without Consecutive Ones\", \"titleSlug\": \"non-negative-integers-without-consecutive-ones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Coin Path\", \"titleSlug\": \"coin-path\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"985.5K\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 985498, \"totalSubmissionRaw\": 2269895, \"acRate\": \"43.4%\"}",
    "title_pt": "Ladrão de Casas II",
    "description_pt": "<p>Você é um ladrão profissional planejando roubar casas ao longo de uma rua. Cada casa tem uma certa quantia de dinheiro guardada. Todas as casas neste local estão <strong>dispostas em um círculo.</strong> Isso significa que a primeira casa é vizinha da última. Enquanto isso, casas adjacentes têm um sistema de segurança conectado, e&nbsp;<b>ele entrará automaticamente em contato com a polícia se duas casas adjacentes forem invadidas na mesma noite</b>.</p>\n\n<p>Dado um array de inteiros <code>nums</code> representando a quantia de dinheiro de cada casa, retorne <em>a quantidade máxima de dinheiro que você pode roubar esta noite <strong>sem alertar a polícia</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,2]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Você não pode roubar a casa 1 (dinheiro = 2) e depois roubar a casa 3 (dinheiro = 2), porque elas são casas adjacentes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Roube a casa 1 (dinheiro = 1) e depois roube a casa 3 (dinheiro = 3).\nQuantidade total que você pode roubar = 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Como House[1] e House[n] são adjacentes, elas não podem ser roubadas juntas. Portanto, o problema se torna roubar ou House[1]-House[n-1] ou House[2]-House[n], dependendo de qual escolha oferece mais dinheiro. Agora o problema se reduziu ao <a href =\"https://leetcode.com/problems/house-robber/description/\">House Robber</a>, que já foi resolvido."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "214",
    "paidOnly": false,
    "title": "Shortest Palindrome",
    "titleSlug": "shortest-palindrome",
    "url": "https://leetcode.com/problems/shortest-palindrome",
    "description_url": "https://leetcode.com/problems/shortest-palindrome/description/",
    "description": "<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword=\"palindrome-string\">palindrome</span> by adding characters in front of it.</p>\n\n<p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"aacecaaa\"\n<strong>Output:</strong> \"aaacecaaa\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"abcd\"\n<strong>Output:</strong> \"dcbabcd\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters only.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/shortest-palindrome/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a string `s`. Our task is to build the smallest palindrome by adding characters to the beginning of `s`.\n\nTo solve this, we can reframe the problem as finding the longest palindromic substring that starts from the index `0`. Once we know the length of this substring, we can create the shortest palindrome by appending the reverse of the remaining part of the string to the original string to make `s` a complete palindrome.\n\nFor instance, consider the string `s = \"aacecaaa\"`. Here, the longest palindromic prefix is `\"aacecaa\"`(starts at index `0`). The remaining part of the string is just the last `\"a\"`. To create the smallest palindrome, we reverse this remaining part and add it to the front of the original string, resulting in `\"aaacecaaa\"`, which is a palindrome. \n\nAnother example is `s = \"abcd\"`, where the longest palindromic prefix is just the first character `\"a\"`. The remaining part, `\"bcd\"`, is not a palindrome. By reversing `\"bcd\"` and adding it to the start, we get `\"dcbabcd\"`, which is the smallest palindrome that can be formed from the original string. This way, we can find the shortest palindrome by adding only the necessary characters to the front of the string.\n\n### Approach 1: Brute Force\n\n#### Intuition\n\nAs we know, a palindrome reads the same forwards and backwards. Therefore, the challenge is to identify the longest prefix of the original string that can be extended to a full palindrome by only adding characters at the start.\n\nFirst, we need to find out which part of the string is already a palindrome. So, we check the original string and see how much of it matches the end of its reversed version. This helps us figure out the longest palindromic prefix.\n\nTo do this, we look at different prefixes of the original string and compare them to suffixes of the reversed string. If a prefix matches a suffix of the reversed string, it’s part of a palindrome.\n\nOnce we find the longest palindromic prefix, we need to reverse the rest of the string (the part not included in the prefix) and add this reversed part to the start of the original string. This gives us the shortest possible palindrome.\n\nFor example: Let’s take the string `\"abcbabcab\"`. We reverse the string to get `\"bacbabcba\"`. By comparing prefixes of `\"abcbabcab\"` with suffixes of `\"bacbabcba\"`, we find that the longest prefix `\"abcba\"` matches with the suffix `\"abcba\"` in the reversed string. This is a palindrome.\n\nTo form the shortest palindrome, we then need to reverse the remaining part of the original string that doesn’t overlap with this prefix. In our example, the remaining part is `\"bcab\"`. Reversing `\"bcab\"` gives us `\"bacb\"`. Adding this to the start of the original string results in `\"bacbabcbabcab\"`.\n\n#### Algorithm\n\n- Initialize `length` with the length of the string `s`.\n- Reverse the string `s` to get `reversedString`.\n\n- Iterate through the string from `0` to `length - 1`:\n  - For each index `i`, check if the substring `s.substring(0, length - i)` (i.e., the prefix of `s` up to `length - i`) is equal to the substring `reversedString.substring(i)` (i.e., the suffix of `reversedString` starting from `i`).\n  - If they are equal, it means the prefix of `s` is a palindrome:\n    - Return the concatenation of `reversedString.substring(0, i)` (i.e., the characters in `reversedString` before `i`) and the original string `s`.\n\n- If no valid prefix is found that satisfies the condition, return an empty string `\"\"`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/HTCP8cwb/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"HTCP8cwb\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string $s$.\n\n- Time complexity: $O(n^2)$\n\n    The reversal of the string `s` involves traversing the string once, which has a time complexity of $O(n)$.\n    \n    In the loop, for each iteration, we check if the substring of length $n - i$ of `s` matches the substring of length $n - i$ of the reversed string. Each check involves string operations that are linear in the length of the substring being compared. Thus, for each iteration $i$, the comparison is $O(n - i)$. Since $i$ ranges from 0 to $n - 1$, the total time complexity of the palindrome check part can be expressed as the sum of comparisons of decreasing lengths. This sum is roughly $O(n^2)$.\n    \n    Combining these operations, the overall time complexity is $O(n^2)$.\n\n- Space complexity: $O(n)$\n\n    Creating the reversed string involves additional space proportional to the length of the input string, i.e., $O(n)$.\n    \n    The substring operations in the `for` loop do not require additional space proportional to the length of the string but do create new string objects temporarily, which is still $O(n)$ space for each substring.\n    \n    Therefore, the overall space complexity is $O(n)$.\n\n---\n\n### Approach 2: Two Pointer\n\n#### Intuition\n\nIn the brute force approach, we observe that we need to identify the longest palindromic prefix of a string. To do this, we can now use a method involving two pointers. This method is a bit more efficient compared to checking every possible substring, which would take longer.\n\nLet's consider an example string: `\"abcbabcaba\"`. We use two pointers, `left` and `right`. We start by setting `left` to `0`. Then, we move the `right` pointer from the end of the string to the beginning. Each time the characters at `left` and `right` match, we increment `left`.\n\nBy following this process, we narrow our search to the substring from the beginning of the string up to `left`. This substring will always include the longest palindromic prefix.\n\n- If the entire string were a perfect palindrome, the `left` pointer would move through the entire length of the string, reaching the end (`n` times).\n- If the string isn’t a perfect palindrome, the `left` pointer will still move forward by the length of the palindromic part at the beginning.\n\nTherefore, while the substring $[0, \\text{left})$ may not always be the tightest fit, it will always contain the longest palindromic prefix.\n\nThe best-case scenario for this algorithm is when the entire string is a palindrome. In this case, the `left` pointer will reach the end of the string quickly. The worst-case scenario is when the string is something like `\"aababababababa\"`. Here, `left` initially becomes `12`, meaning we need to recheck the substring $[0, 12)$. As we continue, `left` might decrease to `10`, and so on. In this worst-case scenario, the substring is reduced by only a few elements at each step, making the total number of steps proportional to the length of the string, or $O(n)$.\n\n#### Algorithm\n\n- If the string `s` is empty, return `s` immediately.\n\n- Find the longest palindromic prefix:\n  - Initialize `left` to 0.\n  - Iterate `right` from the end of the string (`length - 1`) to the start (0):\n    - If the character at `right` matches the character at `left`:\n      - Increment `left`.\n\n- If `left` equals the length of the string, `s` is already a palindrome, so return `s`.\n\n- Extract the suffix that is not part of the palindromic prefix:\n  - Create `nonPalindromeSuffix` as the substring from `left` to the end of `s`.\n  - Reverse `nonPalindromeSuffix` to create `reverseSuffix`.\n\n- Form the shortest palindrome:\n  - Recursively call `shortestPalindrome` on the substring from the start to `left` (i.e., `s.substring(0, left)`).\n  - Concatenate `reverseSuffix`, the result of the recursive call, and `nonPalindromeSuffix`.\n\n- Return the concatenated result as the shortest palindrome.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/X6dVgEa4/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"X6dVgEa4\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n- Time Complexity: $O(n^2)$\n\n    Each iteration of the `shortestPalindrome` function operates on a substring of size `n`. In the worst-case scenario, where the string is not a palindrome and we must continually reduce its size, the function might need to be called up to `n/2` times.\n\n    The time complexity $T(n)$ represents the total time taken by the algorithm. At each step, the algorithm processes a substring and then works with a smaller substring by removing two characters. This can be expressed as $T(n) = T(n-2) + O(n)$, where $O(n)$ is the time taken to process the substring of size `n`.\n\n    Summing up all the steps, we get:\n    $T(n) = O(n) + O(n-2) + O(n-4) + \\ldots + O(1)$\n  \n    This sum of terms approximates to $O(n^2)$ because it is an arithmetic series where the number of terms grows linearly with `n`.\n\n- Space Complexity: $O(n)$\n\n    The space complexity is linear, $O(n)$, due to the space needed to store the reversed suffix and other temporary variables.\n\n---\n\n### Approach 3: KMP (Knuth-Morris-Pratt) Algorithm\n\n#### Intuition\n\nThe KMP algorithm is used for pattern matching within strings. The KMP algorithm computes prefix functions to identify substrings that match specific patterns. In our case, we use this efficiency to compute the longest palindromic prefix. We construct a combined string of the original string, a special delimiter, and the reversed original string. By applying KMP, we can determine the longest prefix of the original string that matches a suffix of the reversed string.\n\nFirst, we construct a new string by concatenating the original string, a delimiter (such as `\"#\"`), and the reversed original string. This combined string looks like `\"original#reversed\"`. The delimiter `\"#\"` is crucial because it ensures that we are only comparing the original string with its reversed version, and not inadvertently matching parts of the reversed string with itself.\n\nTo proceed, we calculate the prefix function for this combined string. The prefix function or partial match table is an array where each element at index `i` indicates the length of the longest prefix of the substring ending at `i` which is also a suffix. This helps us identify the longest segment where the prefix of the original string matches a suffix in the reversed string. The purpose is to identify how much of the original string matches a suffix of the reversed string.\n\n</br>\n\nFor example: We construct a combined string using the original string `s`, a delimiter `\"#\"`, and the reversed version of `s`. This combined string helps us find the longest palindromic prefix by applying the KMP algorithm. For the string `\"aacecaaa\"`, the reversed string is `\"aaacecaa\"`. Thus, the combined string becomes `\"aacecaaa#aaacecaa\"`.\n\nThe prefix function helps us determine the length of the longest prefix of the original string that can be matched by a suffix of the reversed string. For the combined string `\"aacecaaa#aaacecaa\"`, the prefix function will reveal that the longest palindromic prefix of `\"aacecaaa\"` is `\"aacecaa\"`.\n\nTo create the shortest palindrome, we need to prepend characters to the original string. Specifically, we reverse the portion of the original string that extends beyond the longest palindromic prefix and prepend it. In this case, the part of the original string that extends beyond `\"aacecaa\"` is `\"a\"`. Reversing `\"a\"` gives `\"a\"`, so we prepend `\"a\"` to `\"aacecaaa\"` and the result is `\"aaacecaaa\"`.\n\n</br>\n\n</br>\n\nThe algorithm to generate the prefix table is described below:\n\n```java\nprefixTable[0] = 0;\nfor (int i = 1; i < n; i++) {\n    int length = prefixTable[i - 1];\n    while (length > 0 && s.charAt(i) != s.charAt(length)) {\n        length = prefixTable[length - 1];\n    }\n    if (s.charAt(i) == s.charAt(length)) {\n        length++;\n    }\n    prefixTable[i] = length;\n}\n```\n\n* Begin by setting `prefixTable[0] = 0` since there is no proper prefix for the first character.\n* Next, iterate over `i` from 1 to `n - 1`:\n    * Set `length = prefixTable[i - 1]`, which represents the longest prefix length for the substring up to the previous character.\n    * While `length > 0` and the character at position `i` doesn't match the character at position `length`, set `length = prefixTable[length - 1]`. This step is essential when we encounter a mismatch, and we attempt to match a shorter prefix, which is the value of `prefixTable[length - 1]`, until either we find a match or `length` becomes 0.\n    * If `s.charAt(i) == s.charAt(length)`, we increment `length` by 1 (extend the matching prefix).\n    * Finally, set `prefixTable[i] = length`.\n\nThe lookup table generation is as illustrated below:\n\n![KMP](../Figures/214/shortest_palindrome_KMP.png)\n\n\n#### Algorithm\n\n- `shortestPalindrome` function:\n  - Create `reversedString` by reversing the input string `s`.\n  - Concatenate `s`, a separator `#`, and `reversedString` to form `combinedString`.\n  - Call `buildPrefixTable(combinedString)` to compute the prefix table for `combinedString`.\n  - Extract the length of the longest palindromic prefix from the last value in the prefix table (`prefixTable[combinedString.length() - 1]`).\n  - Compute `suffix` by taking the substring of `s` starting from the length of the longest palindromic prefix.\n  - Reverse `suffix` and prepend it to `s` to form and return the shortest palindrome.\n\n- `buildPrefixTable` function:\n  - Initialize `prefixTable` with the same length as the input string `s` and set `length` to `0`.\n  - Iterate over `s` from index `1` to the end:\n    - While `length` is greater than `0` and the current character does not match the character at the current length, update `length` to the value at `prefixTable[length - 1]`.\n    - If the current character matches the character at `length`, increment `length`.\n    - Set `prefixTable[i]` to the current `length`.\n  - Return the `prefixTable`.\n\n- The result is the shortest palindrome string formed by appending the reversed suffix of `s` to `s`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/N4VVxjKz/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"N4VVxjKz\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n- Time complexity: $O(n)$\n\n    Creating the reversed string requires a pass through the original string, which takes $O(n)$ time.\n\n    Concatenating `s`, `#`, and `reversedString` takes $O(n)$ time, as concatenating strings of length $n$ is linear in the length of the strings.\n\n    Constructing the prefix table involves iterating over the combined string of length $2n + 1$. The `buildPrefixTable` method runs in $O(m)$ time, where $m$ is the length of the combined string. In this case, $m = 2n + 1$, so the time complexity is $O(n)$.\n\n    Extracting the suffix and reversing it are both $O(n)$ operations.\n\n    Combining these, the overall time complexity is $O(n)$.\n\n- Space complexity: $O(n)$\n    \n    The `reversedString` and `combinedString` each use $O(n)$ space.\n    \n    The `prefixTable` array has a size of $2n + 1$, which is $O(n)$. Other variables used (such as `length` and indices) use $O(1)$ space.\n\n    Combining these, the overall space complexity is $O(n)$.\n\n---\n\n### Approach 4: Rolling Hash Based Algorithm\n\n#### Intuition\n\nThe rolling hash approach uses hash functions to efficiently compare different substrings of the original string with those of the reversed string. Hashing helps determine if a substring matches another by comparing hash values rather than individual characters.\n\nRolling hashes were designed to handle substring matching and comparison problems by allowing incremental updates to hash values as we slide through the string. This reduces the number of comparisons needed by comparing hash values instead of actual substrings.\n\nTo start, we compute hash values for all prefixes of the original string and all suffixes of the reversed string using a rolling hash function. The rolling hash function allows us to update the hash values incrementally, which speeds up the computation compared to recalculating hashes from scratch.\n\nNext, we compare the hash values of the prefixes from the original string with the hash values of the suffixes from the reversed string. When the hash values match, it indicates that the corresponding substrings are identical. This helps us find the longest palindromic prefix.\n\nFor example: Suppose our string is `\"aacecaaa\"`. We calculate hash values for the prefixes of `\"aacecaaa\"` and the suffixes of its reverse, `\"aaacecaa\"`. The hash comparisons reveal that the longest palindromic prefix is `\"aacecaaa\"`. We then reverse the remaining part of the string (`\"a\"`), yielding `\"a\"`. Prepending this reversed part to the original string gives `\"aaacecaaa\"`.\n\n<br/>\n\n##### Hash Calculation Details:\n\nTo give you a clearer idea of how the hashing is calculated, let's see this:\n\nWe initialize two hash values: one for the original string and one for its reversed version. Let’s use base `29` and a large prime modulus $10^9 + 7$ for hashing. We also initialize a variable to keep track of powers of the base.\n\nWe iterate through each character of the original string and compute its hash. Suppose we start with the hash value `0` and process characters one by one:\n\n<br/>\n\n$$\\text{Character } 'a':$$\n\n$$\\text{Update hash:}$$\n\n$$\\text{hash} = (\\text{hash} \\times \\text{base} + \\text{character\\_value}) \\% \\text{mod}$$\n\n$$\\text{Suppose } \\text{character\\_value} \\text{ for } 'a' \\text{ is } 1.$$\n\n$$\\text{hash} = (0 \\times 29 + 1) \\%  1000000007 = 1$$\n\n<br/>\n\n$$\\text{Character } 'a':$$\n\n$$\\text{Update hash:}$$\n\n$$\\text{hash} = (1 \\times 29 + 1) \\% 1000000007 = 30$$\n\n<br/>\n\nContinue this for all characters. After processing `\"aacecaaa\"`, let’s assume the final hash is `23456789` for this substring.\n\nWe do a similar hash calculation for the reversed string `\"aaacecaa\"`. We compute the hash values for each prefix of the reversed string. Let’s assume the final hash of the reversed string is `34567890`.\n\nTo compare substrings, we use a rolling hash. As we move the window of comparison along the combined string, we update the hash values based on the new and old characters entering and exiting the window. If the hash of a prefix of the original string matches the hash of a suffix of the reversed string, that prefix is palindromic. Now the comparison shows that the longest prefix of `\"aacecaaa\"` that matches a suffix of `\"aaacecaa\"` is `\"aacecaa\"`. This tells us that `\"aacecaa\"` is a palindromic segment. Now we identify the remaining part of the original string that extends beyond the palindromic prefix. For `\"aacecaaa\"`, the remaining part is `\"a\"`.\n\nSo we reverse the remaining part (`\"a\"`) to get `\"a\"`, and prepend this reversed part to the original string.\n\nThus the shortest palindrome is `\"aaacecaaa\"`.\n\n#### Algorithm\n\n- Initialize hash parameters:\n  - Set `hashBase` to 29 and `modValue` to $10^9 + 7$.\n  - Initialize `forwardHash` and `reverseHash` to 0.\n  - Initialize `powerValue` to 1.\n  - Initialize `palindromeEndIndex` to -1.\n\n- Iterate over each character `currentChar` in the string `s`:\n  - Update `forwardHash` to include the current character:\n    - Compute `forwardHash` as `(forwardHash * hashBase + (currentChar - 'a' + 1)) % modValue`.\n  - Update `reverseHash` to include the current character:\n    - Compute `reverseHash` as `(reverseHash + (currentChar - 'a' + 1) * powerValue) % modValue`.\n  - Update `powerValue` for the next character:\n    - Compute `powerValue` as `(powerValue * hashBase) % modValue`.\n  - If `forwardHash` matches `reverseHash`, update `palindromeEndIndex` to the current index `i`.\n\n- After the loop, find the suffix that follows the longest palindromic prefix:\n  - Extract the suffix from the string `s` starting from `palindromeEndIndex + 1` to the end.\n  - Reverse the suffix to prepare for prepending.\n\n- Concatenate the reversed suffix to the original string `s` and return the result:\n  - Return `reversedSuffix + s`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ZJD8AXfF/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ZJD8AXfF\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n- Time complexity: $O(n)$\n\n    The algorithm performs a single pass over the input string to compute rolling hashes and determine the longest palindromic prefix, resulting in $O(n)$ time complexity. This pass involves constant-time operations for each character, including hash updates and power calculations. After this, we perform an additional pass to reverse the suffix, which is also $O(n)$. The total time complexity remains $O(n)$.\n\n- Space complexity: $O(n)$\n\n    The space complexity is determined by the space used for the reversed suffix and the additional string manipulations. The space required for the forward and reverse hash values, power value, and palindrome end index is constant and does not scale with input size. However, storing the reversed suffix and the final result string both require $O(n)$ space. Thus, the space complexity is $O(n)$.\n\n---\n\n### Approach 5: Manacher's Algorithm\n\n#### Intuition\n\n> Note: This algorithm goes beyond what's typically expected in coding interviews. It's more for those who are curious and eager to explore advanced algorithms, simply out of personal interest or a desire to deepen their understanding of data structures and algorithms. If you're someone who loves learning new concepts beyond interview prep, this approach might be for you! Sometimes this is the only algorithm that can give you an $O(n)$ runtime.\n\n</br>\n\nDeveloped to address the problem of finding palindromic substrings efficiently, Manacher’s algorithm preprocesses the string to handle both even and odd-length palindromes uniformly. By inserting special characters between each character of the original string, it computes the radius of the longest palindromic substring centered at each position.\n\nTo handle palindromes of both even and odd lengths uniformly, the algorithm transforms the original string by inserting special characters (e.g., `\"#\"`) between every character and at the boundaries. This way, every palindrome can be treated as if it’s surrounded by characters, making it easier to apply the same expansion logic for all cases.\n\nFor example, the string `\"aacecaaa\"` is transformed into `\"^#a#a#c#e#c#a#a#a#$\"`. Here, `^` and `$` are boundary markers that help avoid out-of-bound errors. `#` helps to treat the string uniformly, making every palindrome appear with a single center.\n\nManacher’s algorithm maintains an array `P` where `P[i]` denotes the radius of the longest palindromic substring centered at the position `i` in the transformed string.\n\n</br>\n\nWe divide Manacher's algorithm into three steps to achieve linear time complexity:\n\n1. Center and Right Boundary: We track the center `C` and right boundary `R` of the rightmost palindrome found so far. For each position `i`, we check if it falls within the current right boundary. If it does, we use previously computed information to estimate the length of the palindrome centered at `i`.\n\n2. Mirror Property: If a position `i` is within the right boundary of a known palindrome, we can infer the length of the palindrome centered at `i` from its mirrored position relative to the current center `C`. This way we reduce the need for direct expansion by leveraging previously computed palindromes to quickly estimate lengths.\n\n3. Expand Around Center: For positions where the estimated palindrome length based on the mirror property is not accurate, we perform direct expansion to find the exact length of the palindrome centered at `i`. We update the center and right boundary if the newly found palindrome extends beyond the current right boundary.\n\n</br>\n\nAfter computing the array `P`, we can determine the longest palindromic prefix of the original string. The longest palindromic substring in the transformed string that corresponds to a prefix of the original string gives us the longest palindromic prefix.\n\nTo form the shortest palindrome, identify the part of the original string that does not contribute to this longest palindromic prefix. Reverse this non-matching segment and prepend it to the original string.\n\nWith the string `\"aacecaaa\"`, after preprocessing to `\"#a#a#c#e#c#a#a#a#\"`, Manacher’s algorithm identifies `\"aacecaaa\"` as the longest palindromic prefix. Reversing the remaining part (`\"a\"`) and prepending it results in `\"aaacecaaa\"`.\n\nWe highly recommend solving the [longest palindromic substring problem using Manacher’s algorithm](https://leetcode.com/problems/longest-palindromic-substring/editorial/). It is extremely efficient and ideal for solving palindrome-related problems.\n\nThis algorithm is complex, so review various sources to gain a better understanding. It's normal if you don’t grasp it right away, so give yourself time.\n\n#### Algorithm\n\n- `shortestPalindrome` function:\n  - If the input string `s` is null or empty, return `s` immediately.\n  - Preprocess the string `s` by calling `preprocessString(s)` to handle edge cases and simplify palindrome detection.\n    - `preprocessString` function:\n      - Initialize a string with a starting character `^`.\n      - Append a `#` followed by each character in `s` to string.\n      - Append a trailing `#` and a dollar sign to complete the modified string.\n      - Return the modified string which includes special boundary characters.\n  - Initialize an integer array `palindromeRadiusArray` to store the radius of the palindrome centered at each character in the modified string.\n  - Initialize `center` and `rightBoundary` to track the center and right boundary of the current longest palindrome found.\n  - Initialize `maxPalindromeLength` to track the length of the longest palindrome that touches the start of the string.\n\n  - Iterate through each character `i` in the modified string (excluding the boundary characters):\n    - Calculate the `mirrorIndex` as `2 * center - i` to utilize previously computed palindromes.\n    - If `rightBoundary` is greater than `i`, update `palindromeRadiusArray[i]` to the minimum of the remaining length to the `rightBoundary` or the radius of the palindrome at `mirrorIndex`.\n    - Expand around the center `i` while the characters match and update `palindromeRadiusArray[i]` accordingly.\n    - If the expanded palindrome extends beyond `rightBoundary`, update `center` and `rightBoundary` to the new values.\n    - If the palindrome touches the start of the string (`i - palindromeRadiusArray[i] == 1`), update `maxPalindromeLength` with the maximum length found.\n\n  - Extract the suffix of the original string starting from `maxPalindromeLength` and reverse it.\n  - Concatenate the reversed suffix with the original string and return the result.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5kUQ24JZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5kUQ24JZ\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n- Time complexity: $O(n)$\n\n    The `preprocessString` method adds boundaries and separators to the input string. This takes linear time, $O(n)$, where $n$ is the length of the input string.\n\n    The core algorithm iterates through the characters of the modified string once. The expansion step and the updates of the center and right boundary each take constant time in the average case for each character. Thus, this step has a time complexity of $O(m)$, where $m$ is the length of the modified string.\n    \n    Since the length of the modified string is $2n + 1 \\, (\\text{for separators}) + 2 \\, (\\text{for boundaries}) = 2n + 3$ , the time complexity of Manacher's algorithm is $O(n)$.\n\n    Constructing the result involves reversing the suffix of the original string and concatenating it with the original string, both of which take linear time, $O(n)$.\n\n    Combining these steps, the total time complexity is $O(n)$.\n\n- Space complexity: $O(n)$\n\n    The space used to store the modified string is proportional to its length, which is $2n + 3$. Therefore, the space complexity for storing this string is $O(n)$.\n\n    The `palindromeRadiusArray` is used to store the radius of palindromes for each character in the modified string, which is $O(m)$. Since $m$ is $2n + 3$, the space complexity for this array is $O(n)$.\n\n    The additional space used for temporary variables, and other operations is constant, $O(1)$.\n\n    Combining these factors, the total space complexity is $O(n)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def shortestPalindrome(self, s: str) -> str:\n    t = s[::-1]\n\n    for i in range(len(t)):\n      if s.startswith(t[i:]):\n        return t[:i] + s\n\n    return t + s",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String shortestPalindrome(String s) {\n    final String t = new StringBuilder(s).reverse().toString();\n\n    for (int i = 0; i < t.length(); ++i)\n      if (s.startsWith(t.substring(i)))\n        return t.substring(0, i) + s;\n\n    return t + s;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string shortestPalindrome(string s) {\n    string t = s;\n    reverse(begin(t), end(t));\n\n    const string_view sv_s(s);\n    const string_view sv_t(t);\n\n    for (int i = 0; i < s.length(); ++i)\n      if (sv_s.substr(0, s.length() - i) == sv_t.substr(i))\n        return t.substr(0, i) + s;\n\n    return t + s;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/214.html",
    "category": "Algorithms",
    "acceptance_rate": 40.55487059545669,
    "topics": [
      "String",
      "Rolling Hash",
      "String Matching",
      "Hash Function"
    ],
    "hints": [],
    "likes": 4364,
    "dislikes": 277,
    "similar_questions": "[{\"title\": \"Longest Palindromic Substring\", \"titleSlug\": \"longest-palindromic-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Index of the First Occurrence in a String\", \"titleSlug\": \"find-the-index-of-the-first-occurrence-in-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Palindrome Pairs\", \"titleSlug\": \"palindrome-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Deletions on a String\", \"titleSlug\": \"maximum-deletions-on-a-string\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Smallest Palindromic Rearrangement I\", \"titleSlug\": \"smallest-palindromic-rearrangement-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"306.6K\", \"totalSubmission\": \"755.9K\", \"totalAcceptedRaw\": 306563, \"totalSubmissionRaw\": 755923, \"acRate\": \"40.6%\"}",
    "title_pt": "Menor Palíndromo",
    "description_pt": "<p>Você recebe uma string <code>s</code>. Você pode converter <code>s</code> em um <span data-keyword=\"palindrome-string\">palíndromo</span> adicionando caracteres na frente dela.</p>\n\n<p>Retorne <em>o menor palíndromo que você puder encontrar ao realizar essa transformação</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"aacecaaa\"\n<strong>Saída:</strong> \"aaacecaaa\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"abcd\"\n<strong>Saída:</strong> \"dcbabcd\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "215",
    "paidOnly": false,
    "title": "Kth Largest Element in an Array",
    "titleSlug": "kth-largest-element-in-an-array",
    "url": "https://leetcode.com/problems/kth-largest-element-in-an-array",
    "description_url": "https://leetcode.com/problems/kth-largest-element-in-an-array/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>largest element in the array</em>.</p>\n\n<p>Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p>\n\n<p>Can you solve it without sorting?</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [3,2,1,5,6,4], k = 2\n<strong>Output:</strong> 5\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4\n<strong>Output:</strong> 4\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/kth-largest-element-in-an-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findKthLargest(self, nums: List[int], k: int) -> int:\n    minHeap = []\n\n    for num in nums:\n      heapq.heappush(minHeap, num)\n      if len(minHeap) > k:\n        heapq.heappop(minHeap)\n\n    return minHeap[0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findKthLargest(int[] nums, int k) {\n    Queue<Integer> minHeap = new PriorityQueue<>((a, b) -> a - b);\n\n    for (final int num : nums) {\n      minHeap.offer(num);\n      while (minHeap.size() > k)\n        minHeap.poll();\n    }\n\n    return minHeap.peek();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findKthLargest(vector<int>& nums, int k) {\n    priority_queue<int, vector<int>, greater<>> minHeap;\n\n    for (const int num : nums) {\n      minHeap.push(num);\n      if (minHeap.size() > k)\n        minHeap.pop();\n    }\n\n    return minHeap.top();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/215.html",
    "category": "Algorithms",
    "acceptance_rate": 67.84758260152124,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Sorting",
      "Heap (Priority Queue)",
      "Quickselect"
    ],
    "hints": [],
    "likes": 17862,
    "dislikes": 934,
    "similar_questions": "[{\"title\": \"Wiggle Sort II\", \"titleSlug\": \"wiggle-sort-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Top K Frequent Elements\", \"titleSlug\": \"top-k-frequent-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Third Maximum Number\", \"titleSlug\": \"third-maximum-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Element in a Stream\", \"titleSlug\": \"kth-largest-element-in-a-stream\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"K Closest Points to Origin\", \"titleSlug\": \"k-closest-points-to-origin\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Kth Largest Integer in the Array\", \"titleSlug\": \"find-the-kth-largest-integer-in-the-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Subsequence of Length K With the Largest Sum\", \"titleSlug\": \"find-subsequence-of-length-k-with-the-largest-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"K Highest Ranked Items Within a Price Range\", \"titleSlug\": \"k-highest-ranked-items-within-a-price-range\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3M\", \"totalSubmission\": \"4.4M\", \"totalAcceptedRaw\": 2973568, \"totalSubmissionRaw\": 4382718, \"acRate\": \"67.8%\"}",
    "title_pt": "k-ésimo Maior Elemento em um Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>o</em> <code>k<sup>th</sup></code> <em>maior elemento no array</em>.</p>\n\n<p>Observe que ele é o <code>k<sup>th</sup></code> maior elemento na ordem ordenada, não o <code>k<sup>th</sup></code> elemento distinto.</p>\n\n<p>Você consegue resolvê-lo sem ordenar?</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [3,2,1,5,6,4], k = 2\n<strong>Saída:</strong> 5\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [3,2,3,1,2,4,5,5,6], k = 4\n<strong>Saída:</strong> 4\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "216",
    "paidOnly": false,
    "title": "Combination Sum III",
    "titleSlug": "combination-sum-iii",
    "url": "https://leetcode.com/problems/combination-sum-iii",
    "description_url": "https://leetcode.com/problems/combination-sum-iii/description/",
    "description": "<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p>\n\n<ul>\n\t<li>Only numbers <code>1</code> through <code>9</code> are used.</li>\n\t<li>Each number is used <strong>at most once</strong>.</li>\n</ul>\n\n<p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 3, n = 7\n<strong>Output:</strong> [[1,2,4]]\n<strong>Explanation:</strong>\n1 + 2 + 4 = 7\nThere are no other valid combinations.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 3, n = 9\n<strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]]\n<strong>Explanation:</strong>\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 4, n = 1\n<strong>Output:</strong> []\n<strong>Explanation:</strong> There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= k &lt;= 9</code></li>\n\t<li><code>1 &lt;= n &lt;= 60</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/combination-sum-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n    ans = []\n\n    def dfs(k: int, n: int, s: int, path: List[int]) -> None:\n      if k == 0 and n == 0:\n        ans.append(path)\n        return\n      if k == 0 or n < 0:\n        return\n\n      for i in range(s, 10):\n        dfs(k - 1, n - i, i + 1, path + [i])\n\n    dfs(k, n, 1, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> combinationSum3(int k, int n) {\n    List<List<Integer>> ans = new ArrayList<>();\n    dfs(k, n, 1, new ArrayList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int k, int n, int s, List<Integer> path, List<List<Integer>> ans) {\n    if (k == 0 && n == 0) {\n      ans.add(new ArrayList<>(path));\n      return;\n    }\n    if (k == 0 || n < 0)\n      return;\n\n    for (int i = s; i <= 9; ++i) {\n      path.add(i);\n      dfs(k - 1, n - i, i + 1, path, ans);\n      path.remove(path.size() - 1);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> combinationSum3(int k, int n) {\n    vector<vector<int>> ans;\n    dfs(k, n, 1, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(int k, int n, int s, vector<int>&& path, vector<vector<int>>& ans) {\n    if (k == 0 && n == 0) {\n      ans.push_back(path);\n      return;\n    }\n    if (k == 0 || n <= 0)\n      return;\n\n    for (int i = s; i <= 9; ++i) {\n      path.push_back(i);\n      dfs(k - 1, n - i, i + 1, move(path), ans);\n      path.pop_back();\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/216.html",
    "category": "Algorithms",
    "acceptance_rate": 71.69761128018742,
    "topics": [
      "Array",
      "Backtracking"
    ],
    "hints": [],
    "likes": 6321,
    "dislikes": 116,
    "similar_questions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"654.9K\", \"totalSubmission\": \"913.4K\", \"totalAcceptedRaw\": 654915, \"totalSubmissionRaw\": 913444, \"acRate\": \"71.7%\"}",
    "title_pt": "Combinação Soma III",
    "description_pt": "<p>Encontre todas as combinações válidas de <code>k</code> números que somem <code>n</code> de modo que as seguintes condições sejam verdadeiras:</p>\n\n<ul>\n\t<li>Apenas os números <code>1</code> através de <code>9</code> são usados.</li>\n\t<li>Cada número é usado <strong>no máximo uma vez</strong>.</li>\n</ul>\n\n<p>Retorne <em>uma lista de todas as combinações válidas possíveis</em>. A lista não deve conter a mesma combinação duas vezes, e as combinações podem ser retornadas em qualquer ordem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 3, n = 7\n<strong>Saída:</strong> [[1,2,4]]\n<strong>Explicação:</strong>\n1 + 2 + 4 = 7\nNão há outras combinações válidas.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 3, n = 9\n<strong>Saída:</strong> [[1,2,6],[1,3,5],[2,3,4]]\n<strong>Explicação:</strong>\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nNão há outras combinações válidas.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 4, n = 1\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> Não há combinações válidas.\nUsando 4 números diferentes no intervalo [1,9], a menor soma que podemos obter é 1+2+3+4 = 10 e, como 10 &gt; 1, não há combinação válida.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= k &lt;= 9</code></li>\n\t<li><code>1 &lt;= n &lt;= 60</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "217",
    "paidOnly": false,
    "title": "Contains Duplicate",
    "titleSlug": "contains-duplicate",
    "url": "https://leetcode.com/problems/contains-duplicate",
    "description_url": "https://leetcode.com/problems/contains-duplicate/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <code>true</code> if any value appears <strong>at least twice</strong> in the array, and return <code>false</code> if every element is distinct.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,2,3,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The element 1 occurs at the indices 0 and 3.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,2,3,4]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>All elements are distinct.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,1,1,3,3,4,3,2,4,2]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/contains-duplicate/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def containsDuplicate(self, nums: List[int]) -> bool:\n    return len(nums) != len(set(nums))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean containsDuplicate(int[] nums) {\n    Set<Integer> seen = new HashSet<>();\n\n    for (final int num : nums)\n      if (!seen.add(num))\n        return true;\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool containsDuplicate(vector<int>& nums) {\n    unordered_set<int> seen;\n\n    for (const int num : nums)\n      if (!seen.insert(num).second)\n        return true;\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/217.html",
    "category": "Algorithms",
    "acceptance_rate": 63.09846006911588,
    "topics": [
      "Array",
      "Hash Table",
      "Sorting"
    ],
    "hints": [],
    "likes": 12845,
    "dislikes": 1328,
    "similar_questions": "[{\"title\": \"Contains Duplicate II\", \"titleSlug\": \"contains-duplicate-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Contains Duplicate III\", \"titleSlug\": \"contains-duplicate-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Make Array Zero by Subtracting Equal Amounts\", \"titleSlug\": \"make-array-zero-by-subtracting-equal-amounts\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Valid Pair of Adjacent Digits in String\", \"titleSlug\": \"find-valid-pair-of-adjacent-digits-in-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"5.1M\", \"totalSubmission\": \"8.1M\", \"totalAcceptedRaw\": 5091057, \"totalSubmissionRaw\": 8068437, \"acRate\": \"63.1%\"}",
    "title_pt": "Contém Duplicados",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <code>true</code> se algum valor aparecer <strong>pelo menos duas vezes</strong> no array e retorne <code>false</code> se cada elemento for distinto.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,2,3,1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>O elemento 1 ocorre nos índices 0 e 3.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,2,3,4]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Todos os elementos são distintos.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,1,1,3,3,4,3,2,4,2]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "218",
    "paidOnly": false,
    "title": "The Skyline Problem",
    "titleSlug": "the-skyline-problem",
    "url": "https://leetcode.com/problems/the-skyline-problem",
    "description_url": "https://leetcode.com/problems/the-skyline-problem/description/",
    "description": "<p>A city&#39;s <strong>skyline</strong> is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return <em>the <strong>skyline</strong> formed by these buildings collectively</em>.</p>\n\n<p>The geometric information of each building is given in the array <code>buildings</code> where <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p>\n\n<ul>\n\t<li><code>left<sub>i</sub></code> is the x coordinate of the left edge of the <code>i<sup>th</sup></code> building.</li>\n\t<li><code>right<sub>i</sub></code> is the x coordinate of the right edge of the <code>i<sup>th</sup></code> building.</li>\n\t<li><code>height<sub>i</sub></code> is the height of the <code>i<sup>th</sup></code> building.</li>\n</ul>\n\n<p>You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height <code>0</code>.</p>\n\n<p>The <strong>skyline</strong> should be represented as a list of &quot;key points&quot; <strong>sorted by their x-coordinate</strong> in the form <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate <code>0</code> and is used to mark the skyline&#39;s termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline&#39;s contour.</p>\n\n<p><b>Note:</b> There must be no consecutive horizontal lines of equal height in the output skyline. For instance, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> is not acceptable; the three lines of height 5 should be merged into one in the final output as such: <code>[...,[2 3],[4 5],[12 7],...]</code></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/merged.jpg\" style=\"width: 800px; height: 331px;\" />\n<pre>\n<strong>Input:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n<strong>Output:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n<strong>Explanation:</strong>\nFigure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> buildings = [[0,2,3],[2,5,3]]\n<strong>Output:</strong> [[0,3],[5,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>buildings</code> is sorted by <code>left<sub>i</sub></code> in&nbsp;non-decreasing order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/the-skyline-problem/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n    n = len(buildings)\n    if n == 0:\n      return []\n    if n == 1:\n      left, right, height = buildings[0]\n      return [[left, height], [right, 0]]\n\n    left = self.getSkyline(buildings[:n // 2])\n    right = self.getSkyline(buildings[n // 2:])\n    return self._merge(left, right)\n\n  def _merge(self, left: List[List[int]], right: List[List[int]]) -> List[List[int]]:\n    ans = []\n    i = 0  # left's index\n    j = 0  # right's index\n    leftY = 0\n    rightY = 0\n\n    while i < len(left) and j < len(right):\n      # Choose the powith smaller x\n      if left[i][0] < right[j][0]:\n        leftY = left[i][1]  # Update the ongoing leftY\n        self._addPoint(ans, left[i][0], max(left[i][1], rightY))\n        i += 1\n      else:\n        rightY = right[j][1]  # Update the ongoing rightY\n        self._addPoint(ans, right[j][0], max(right[j][1], leftY))\n        j += 1\n\n    while i < len(left):\n      self._addPoint(ans, left[i][0], left[i][1])\n      i += 1\n\n    while j < len(right):\n      self._addPoint(ans, right[j][0], right[j][1])\n      j += 1\n\n    return ans\n\n  def _addPoint(self, ans: List[List[int]], x: int, y: int) -> None:\n    if ans and ans[-1][0] == x:\n      ans[-1][1] = y\n      return\n    if ans and ans[-1][1] == y:\n      return\n    ans.append([x, y])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> getSkyline(int[][] buildings) {\n    final int n = buildings.length;\n    if (n == 0)\n      return new ArrayList<>();\n    if (n == 1) {\n      final int left = buildings[0][0];\n      final int right = buildings[0][1];\n      final int height = buildings[0][2];\n      List<List<Integer>> ans = new ArrayList<>();\n      ans.add(new ArrayList<>(Arrays.asList(left, height)));\n      ans.add(new ArrayList<>(Arrays.asList(right, 0)));\n      return ans;\n    }\n\n    List<List<Integer>> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2));\n    List<List<Integer>> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n));\n    return merge(leftSkyline, rightSkyline);\n  }\n\n  private List<List<Integer>> merge(List<List<Integer>> left, List<List<Integer>> right) {\n    List<List<Integer>> ans = new ArrayList<>();\n    int i = 0; // left's index\n    int j = 0; // right's index\n    int leftY = 0;\n    int rightY = 0;\n\n    while (i < left.size() && j < right.size())\n      // Choose the point with smaller x\n      if (left.get(i).get(0) < right.get(j).get(0)) {\n        leftY = left.get(i).get(1); // Update the ongoing leftY\n        addPoint(ans, left.get(i).get(0), Math.max(left.get(i++).get(1), rightY));\n      } else {\n        rightY = right.get(j).get(1); // Update the ongoing rightY\n        addPoint(ans, right.get(j).get(0), Math.max(right.get(j++).get(1), leftY));\n      }\n\n    while (i < left.size())\n      addPoint(ans, left.get(i).get(0), left.get(i++).get(1));\n\n    while (j < right.size())\n      addPoint(ans, right.get(j).get(0), right.get(j++).get(1));\n\n    return ans;\n  }\n\n  private void addPoint(List<List<Integer>> ans, int x, int y) {\n    if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == x) {\n      ans.get(ans.size() - 1).set(1, y);\n      return;\n    }\n    if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == y)\n      return;\n    ans.add(new ArrayList<>(Arrays.asList(x, y)));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> getSkyline(const vector<vector<int>>& buildings) {\n    const int n = buildings.size();\n    if (n == 0)\n      return {};\n    if (n == 1) {\n      const int left = buildings[0][0];\n      const int right = buildings[0][1];\n      const int height = buildings[0][2];\n      return {{left, height}, {right, 0}};\n    }\n\n    const vector<vector<int>> left =\n        getSkyline({begin(buildings), begin(buildings) + n / 2});\n    const vector<vector<int>> right =\n        getSkyline({begin(buildings) + n / 2, end(buildings)});\n    return merge(left, right);\n  }\n\n private:\n  vector<vector<int>> merge(const vector<vector<int>>& left,\n                            const vector<vector<int>>& right) {\n    vector<vector<int>> ans;\n    int i = 0;  // left's index\n    int j = 0;  // right's index\n    int leftY = 0;\n    int rightY = 0;\n\n    while (i < left.size() && j < right.size())\n      // Choose the point with smaller x\n      if (left[i][0] < right[j][0]) {\n        leftY = left[i][1];  // Update the ongoing leftY\n        addPoint(ans, left[i][0], max(left[i++][1], rightY));\n      } else {\n        rightY = right[j][1];  // Update the ongoing rightY\n        addPoint(ans, right[j][0], max(right[j++][1], leftY));\n      }\n\n    while (i < left.size())\n      addPoint(ans, left[i][0], left[i++][1]);\n\n    while (j < right.size())\n      addPoint(ans, right[j][0], right[j++][1]);\n\n    return ans;\n  }\n\n  void addPoint(vector<vector<int>>& ans, int x, int y) {\n    if (!ans.empty() && ans.back()[0] == x) {\n      ans.back()[1] = y;\n      return;\n    }\n    if (!ans.empty() && ans.back()[1] == y)\n      return;\n    ans.push_back({x, y});\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/218.html",
    "category": "Algorithms",
    "acceptance_rate": 43.86048569732416,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Binary Indexed Tree",
      "Segment Tree",
      "Line Sweep",
      "Heap (Priority Queue)",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 6052,
    "dislikes": 276,
    "similar_questions": "[{\"title\": \"Falling Squares\", \"titleSlug\": \"falling-squares\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Shifting Letters II\", \"titleSlug\": \"shifting-letters-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"319.2K\", \"totalSubmission\": \"727.7K\", \"totalAcceptedRaw\": 319171, \"totalSubmissionRaw\": 727696, \"acRate\": \"43.9%\"}",
    "title_pt": "O Problema do Horizonte Urbano",
    "description_pt": "<p>O <strong>horizonte urbano</strong> de uma cidade é o contorno externo da silhueta formada por todos os edifícios nessa cidade quando vista de uma distância. Dadas as localizações e alturas de todos os edifícios, retorne <em>o <strong>horizonte urbano</strong> formado por esses edifícios coletivamente</em>.</p>\n\n<p>A informação geométrica de cada edifício é fornecida no array <code>buildings</code> onde <code>buildings[i] = [left<sub>i</sub>, right<sub>i</sub>, height<sub>i</sub>]</code>:</p>\n\n<ul>\n\t<li><code>left<sub>i</sub></code> é a coordenada x da borda esquerda do <code>i<sup>th</sup></code> edifício.</li>\n\t<li><code>right<sub>i</sub></code> é a coordenada x da borda direita do <code>i<sup>th</sup></code> edifício.</li>\n\t<li><code>height<sub>i</sub></code> é a altura do <code>i<sup>th</sup></code> edifício.</li>\n</ul>\n\n<p>Você pode assumir que todos os edifícios são retângulos perfeitos apoiados sobre uma superfície absolutamente plana na altura <code>0</code>.</p>\n\n<p>O <strong>horizonte urbano</strong> deve ser representado como uma lista de \"pontos-chave\" <strong>ordenados pela sua coordenada x</strong> na forma <code>[[x<sub>1</sub>,y<sub>1</sub>],[x<sub>2</sub>,y<sub>2</sub>],...]</code>. Cada ponto-chave é o ponto inicial esquerdo de algum segmento horizontal no horizonte urbano, exceto o último ponto da lista, que sempre tem uma coordenada y <code>0</code> e é usado para marcar a terminação do horizonte urbano onde termina o edifício mais à direita. Qualquer terreno entre os edifícios mais à esquerda e mais à direita deve fazer parte do contorno do horizonte urbano.</p>\n\n<p><b>Nota:</b> Não deve haver linhas horizontais consecutivas de altura igual na saída do horizonte urbano. Por exemplo, <code>[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]</code> não é aceitável; as três linhas de altura 5 devem ser mescladas em uma só na saída final, desta forma: <code>[...,[2 3],[4 5],[12 7],...]</code></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/01/merged.jpg\" style=\"width: 800px; height: 331px;\" />\n<pre>\n<strong>Entrada:</strong> buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n<strong>Saída:</strong> [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n<strong>Explicação:</strong>\nA figura A mostra os edifícios da entrada.\nA figura B mostra o horizonte urbano formado por esses edifícios. Os pontos vermelhos na figura B representam os pontos-chave na lista de saída.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> buildings = [[0,2,3],[2,5,3]]\n<strong>Saída:</strong> [[0,3],[5,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buildings.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= height<sub>i</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>buildings</code> está ordenado por <code>left<sub>i</sub></code> em&nbsp;ordem não decrescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "219",
    "paidOnly": false,
    "title": "Contains Duplicate II",
    "titleSlug": "contains-duplicate-ii",
    "url": "https://leetcode.com/problems/contains-duplicate-ii",
    "description_url": "https://leetcode.com/problems/contains-duplicate-ii/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1], k = 3\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,0,1,1], k = 1\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/contains-duplicate-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n    seen = set()\n\n    for i, num in enumerate(nums):\n      if i > k:\n        seen.remove(nums[i - k - 1])\n      if num in seen:\n        return True\n      seen.add(num)\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean containsNearbyDuplicate(int[] nums, int k) {\n    Set<Integer> seen = new HashSet<>();\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (!seen.add(nums[i]))\n        return true;\n      if (i >= k)\n        seen.remove(nums[i - k]);\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool containsNearbyDuplicate(vector<int>& nums, int k) {\n    unordered_set<int> seen;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (!seen.insert(nums[i]).second)\n        return true;\n      if (i >= k)\n        seen.erase(nums[i - k]);\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/219.html",
    "category": "Algorithms",
    "acceptance_rate": 48.79264816006937,
    "topics": [
      "Array",
      "Hash Table",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 6710,
    "dislikes": 3219,
    "similar_questions": "[{\"title\": \"Contains Duplicate\", \"titleSlug\": \"contains-duplicate\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Contains Duplicate III\", \"titleSlug\": \"contains-duplicate-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1337020, \"totalSubmissionRaw\": 2740209, \"acRate\": \"48.8%\"}",
    "title_pt": "Contém Duplicado II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <code>true</code> <em>se houver dois <strong>índices distintos</strong> </em><code>i</code><em> e </em><code>j</code><em> no array tais que </em><code>nums[i] == nums[j]</code><em> e </em><code>abs(i - j) &lt;= k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1], k = 3\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,0,1,1], k = 1\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1,2,3], k = 2\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "220",
    "paidOnly": false,
    "title": "Contains Duplicate III",
    "titleSlug": "contains-duplicate-iii",
    "url": "https://leetcode.com/problems/contains-duplicate-iii",
    "description_url": "https://leetcode.com/problems/contains-duplicate-iii/description/",
    "description": "<p>You are given an integer array <code>nums</code> and two integers <code>indexDiff</code> and <code>valueDiff</code>.</p>\n\n<p>Find a pair of indices <code>(i, j)</code> such that:</p>\n\n<ul>\n\t<li><code>i != j</code>,</li>\n\t<li><code>abs(i - j) &lt;= indexDiff</code>.</li>\n\t<li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, and</li>\n</ul>\n\n<p>Return <code>true</code><em> if such pair exists or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0\n<strong>Output:</strong> true\n<strong>Explanation:</strong> We can choose (i, j) = (0, 3).\nWe satisfy the three conditions:\ni != j --&gt; 0 != 3\nabs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3\nabs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3\n<strong>Output:</strong> false\n<strong>Explanation:</strong> After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= indexDiff &lt;= nums.length</code></li>\n\t<li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/contains-duplicate-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {\n    if (nums.empty() || k <= 0 || t < 0)\n      return false;\n\n    const long min = *min_element(begin(nums), end(nums));\n    const long diff = t + 1L;  // In case of t = 0\n    // Use long because corner case INT_MAX - (-1) will overflow\n    unordered_map<long, long> bucket;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const long num = nums[i];\n      const long key = getKey(num, min, diff);\n      if (bucket.count(key))  // Current bucket\n        return true;\n      if (bucket.count(key - 1) &&\n          num - bucket[key - 1] < diff)  // Left adjacent bucket\n        return true;\n      if (bucket.count(key + 1) &&\n          bucket[key + 1] - num < diff)  // Right adjacent bucket\n        return true;\n      bucket[key] = num;\n      if (i >= k)\n        bucket.erase(getKey(nums[i - k], min, diff));\n    }\n\n    return false;\n  }\n\n private:\n  int getKey(long num, long min, long diff) {\n    return (num - min) / diff;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {\n    TreeSet<Long> set = new TreeSet<>();\n\n    for (int i = 0; i < nums.length; ++i) {\n      final long num = (long) nums[i];\n      final Long ceiling = set.ceiling(num); // The smallest num >= nums[i]\n      if (ceiling != null && ceiling - num <= t)\n        return true;\n      final Long floor = set.floor(num); // The largest num <= nums[i]\n      if (floor != null && num - floor <= t)\n        return true;\n      set.add(num);\n      if (i >= k)\n        set.remove((long) nums[i - k]);\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {\n    set<long> window;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const auto it = window.lower_bound(static_cast<long>(nums[i]) - t);\n      if (it != cend(window) && *it - nums[i] <= t)\n        return true;\n      window.insert(nums[i]);\n      if (i >= k)\n        window.erase(nums[i - k]);\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/220.html",
    "category": "Algorithms",
    "acceptance_rate": 23.5582212085127,
    "topics": [
      "Array",
      "Sliding Window",
      "Sorting",
      "Bucket Sort",
      "Ordered Set"
    ],
    "hints": [
      "Time complexity O(n logk)  - This will give an indication that sorting is involved for k elements.",
      "Use already existing state to evaluate next state  -  Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again."
    ],
    "likes": 1145,
    "dislikes": 120,
    "similar_questions": "[{\"title\": \"Contains Duplicate\", \"titleSlug\": \"contains-duplicate\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Contains Duplicate II\", \"titleSlug\": \"contains-duplicate-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"280.5K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 280528, \"totalSubmissionRaw\": 1190784, \"acRate\": \"23.6%\"}",
    "title_pt": "Contém Duplicado III",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> e dois inteiros <code>indexDiff</code> e <code>valueDiff</code>.</p>\n\n<p>Encontre um par de índices <code>(i, j)</code> tal que:</p>\n\n<ul>\n\t<li><code>i != j</code>,</li>\n\t<li><code>abs(i - j) &lt;= indexDiff</code>.</li>\n\t<li><code>abs(nums[i] - nums[j]) &lt;= valueDiff</code>, e</li>\n</ul>\n\n<p>Retorne <code>true</code><em> se tal par existir ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,1], indexDiff = 3, valueDiff = 0\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Podemos escolher (i, j) = (0, 3).\nSatisfazemos as três condições:\ni != j --&gt; 0 != 3\nabs(i - j) &lt;= indexDiff --&gt; abs(0 - 3) &lt;= 3\nabs(nums[i] - nums[j]) &lt;= valueDiff --&gt; abs(1 - 1) &lt;= 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Depois de tentar todos os pares possíveis (i, j), não conseguimos satisfazer as três condições, então retornamos false.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>1 &lt;= indexDiff &lt;= nums.length</code></li>\n\t<li><code>0 &lt;= valueDiff &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Complexidade de tempo O(n logk)  - Isso dará uma indicação de que ordenação está envolvida para k elementos.",
      "Dica 2: Use o estado já existente para avaliar o próximo estado  -  Apenas um conjunto de k números ordenados precisa ser acompanhado. Quando estivermos processando o próximo número no array, então podemos utilizar o estado ordenado existente e não é necessário ordenar novamente o próximo conjunto sobreposto de k números."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "221",
    "paidOnly": false,
    "title": "Maximal Square",
    "titleSlug": "maximal-square",
    "url": "https://leetcode.com/problems/maximal-square",
    "description_url": "https://leetcode.com/problems/maximal-square/description/",
    "description": "<p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>&#39;s and <code>1</code>&#39;s, <em>find the largest square containing only</em> <code>1</code>&#39;s <em>and return its area</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg\" style=\"width: 400px; height: 319px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg\" style=\"width: 165px; height: 165px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[&quot;0&quot;]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 300</code></li>\n\t<li><code>matrix[i][j]</code> is <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximal-square/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maximalSquare(self, matrix: List[List[str]]) -> int:\n    m = len(matrix)\n    n = len(matrix[0])\n    dp = [[0] * n for _ in range(m)]\n    maxLength = 0\n\n    for i in range(m):\n      for j in range(n):\n        if i == 0 or j == 0 or matrix[i][j] == '0':\n          dp[i][j] = 1 if matrix[i][j] == '1' else 0\n        else:\n          dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1]\n                         [j], dp[i][j - 1]) + 1\n        maxLength = max(maxLength, dp[i][j])\n\n    return maxLength * maxLength",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maximalSquare(char[][] matrix) {\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    int[][] dp = new int[m][n];\n    int maxLength = 0;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        if (i == 0 || j == 0 || matrix[i][j] == '0')\n          dp[i][j] = matrix[i][j] == '1' ? 1 : 0;\n        else\n          dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;\n        maxLength = Math.max(maxLength, dp[i][j]);\n      }\n\n    return maxLength * maxLength;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maximalSquare(vector<vector<char>>& matrix) {\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    vector<vector<int>> dp(m, vector<int>(n));\n    int maxLength = 0;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        if (i == 0 || j == 0 || matrix[i][j] == '0')\n          dp[i][j] = matrix[i][j] == '1' ? 1 : 0;\n        else\n          dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;\n        maxLength = max(maxLength, dp[i][j]);\n      }\n\n    return maxLength * maxLength;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/221.html",
    "category": "Algorithms",
    "acceptance_rate": 48.57464580205053,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Matrix"
    ],
    "hints": [],
    "likes": 10573,
    "dislikes": 244,
    "similar_questions": "[{\"title\": \"Maximal Rectangle\", \"titleSlug\": \"maximal-rectangle\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Largest Plus Sign\", \"titleSlug\": \"largest-plus-sign\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Artifacts That Can Be Extracted\", \"titleSlug\": \"count-artifacts-that-can-be-extracted\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Stamping the Grid\", \"titleSlug\": \"stamping-the-grid\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximize Area of Square Hole in Grid\", \"titleSlug\": \"maximize-area-of-square-hole-in-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"808.4K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 808405, \"totalSubmissionRaw\": 1664251, \"acRate\": \"48.6%\"}",
    "title_pt": "Quadrado Máximo",
    "description_pt": "<p>Dada uma <code>m x n</code> <code>matrix</code> binária preenchida com <code>0</code>s e <code>1</code>s, <em>encontre o maior quadrado contendo apenas</em> <code>1</code>s <em>e retorne sua área</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg\" style=\"width: 400px; height: 319px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;]]\n<strong>Saída:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg\" style=\"width: 165px; height: 165px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;0&quot;,&quot;1&quot;],[&quot;1&quot;,&quot;0&quot;]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[&quot;0&quot;]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 300</code></li>\n\t<li><code>matrix[i][j]</code> é <code>&#39;0&#39;</code> ou <code>&#39;1&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "222",
    "paidOnly": false,
    "title": "Count Complete Tree Nodes",
    "titleSlug": "count-complete-tree-nodes",
    "url": "https://leetcode.com/problems/count-complete-tree-nodes",
    "description_url": "https://leetcode.com/problems/count-complete-tree-nodes/description/",
    "description": "<p>Given the <code>root</code> of a <strong>complete</strong> binary tree, return the number of the nodes in the tree.</p>\n\n<p>According to <strong><a href=\"http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\" target=\"_blank\">Wikipedia</a></strong>, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between <code>1</code> and <code>2<sup>h</sup></code> nodes inclusive at the last level <code>h</code>.</p>\n\n<p>Design an algorithm that runs in less than&nbsp;<code data-stringify-type=\"code\">O(n)</code>&nbsp;time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/complete.jpg\" style=\"width: 372px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,5,6]\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li>The tree is guaranteed to be <strong>complete</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-complete-tree-nodes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countNodes(self, root: Optional[TreeNode]) -> int:\n    if not root:\n      return 0\n    return 1 + self.countNodes(root.left) + self.countNodes(root.right)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countNodes(TreeNode root) {\n    if (root == null)\n      return 0;\n    return 1 + countNodes(root.left) + countNodes(root.right);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countNodes(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    return 1 + countNodes(root->left) + countNodes(root->right);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/222.html",
    "category": "Algorithms",
    "acceptance_rate": 69.60255038782994,
    "topics": [
      "Binary Search",
      "Bit Manipulation",
      "Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 9051,
    "dislikes": 568,
    "similar_questions": "[{\"title\": \"Closest Binary Search Tree Value\", \"titleSlug\": \"closest-binary-search-tree-value\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"949.3K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 949278, \"totalSubmissionRaw\": 1363860, \"acRate\": \"69.6%\"}",
    "title_pt": "Contar Nós de uma Árvore Completa",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária <strong>completa</strong>, retorne o número de nós na árvore.</p>\n\n<p>De acordo com a <strong><a href=\"http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees\" target=\"_blank\">Wikipedia</a></strong>, cada nível, exceto possivelmente o último, é completamente preenchido em uma árvore binária completa, e todos os nós no último nível estão o mais à esquerda possível. Ela pode ter entre <code>1</code> e <code>2<sup>h</sup></code> nós, inclusive, no último nível <code>h</code>.</p>\n\n<p>Projete um algoritmo que execute em menos de&nbsp;<code data-stringify-type=\"code\">O(n)</code>&nbsp;complexidade de tempo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/14/complete.jpg\" style=\"width: 372px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,5,6]\n<strong>Saída:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 5 * 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li>A árvore é гарантidamente <strong>completa</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "223",
    "paidOnly": false,
    "title": "Rectangle Area",
    "titleSlug": "rectangle-area",
    "url": "https://leetcode.com/problems/rectangle-area",
    "description_url": "https://leetcode.com/problems/rectangle-area/description/",
    "description": "<p>Given the coordinates of two <strong>rectilinear</strong> rectangles in a 2D plane, return <em>the total area covered by the two rectangles</em>.</p>\n\n<p>The first rectangle is defined by its <strong>bottom-left</strong> corner <code>(ax1, ay1)</code> and its <strong>top-right</strong> corner <code>(ax2, ay2)</code>.</p>\n\n<p>The second rectangle is defined by its <strong>bottom-left</strong> corner <code>(bx1, by1)</code> and its <strong>top-right</strong> corner <code>(bx2, by2)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"Rectangle Area\" src=\"https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png\" style=\"width: 700px; height: 365px;\" />\n<pre>\n<strong>Input:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\n<strong>Output:</strong> 45\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\n<strong>Output:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/rectangle-area/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:\n    x = min(C, G) - max(A, E) if max(A, E) < min(C, G) else 0\n    y = min(D, H) - max(B, F) if max(B, F) < min(D, H) else 0\n    return (C - A) * (D - B) + (G - E) * (H - F) - x * y",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int computeArea(long A, long B, long C, long D, long E, long F, long G, long H) {\n    final long x = Math.max(A, E) < Math.min(C, G) ? (Math.min(C, G) - Math.max(A, E)) : 0;\n    final long y = Math.max(B, F) < Math.min(D, H) ? (Math.min(D, H) - Math.max(B, F)) : 0;\n    return (int) ((C - A) * (D - B) + (G - E) * (H - F) - x * y);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int computeArea(long A, long B, long C, long D,\n                  long E, long F, long G, long H) {\n    const long x = max(A, E) < min(C, G) ? (min(C, G) - max(A, E)) : 0;\n    const long y = max(B, F) < min(D, H) ? (min(D, H) - max(B, F)) : 0;\n    return (C - A) * (D - B) + (G - E) * (H - F) - x * y;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/223.html",
    "category": "Algorithms",
    "acceptance_rate": 47.24415302212988,
    "topics": [
      "Math",
      "Geometry"
    ],
    "hints": [],
    "likes": 2055,
    "dislikes": 1655,
    "similar_questions": "[{\"title\": \"Rectangle Overlap\", \"titleSlug\": \"rectangle-overlap\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Number of Ways to Place People II\", \"titleSlug\": \"find-the-number-of-ways-to-place-people-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Number of Ways to Place People I\", \"titleSlug\": \"find-the-number-of-ways-to-place-people-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Largest Area of Square Inside Two Rectangles\", \"titleSlug\": \"find-the-largest-area-of-square-inside-two-rectangles\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"247.9K\", \"totalSubmission\": \"524.6K\", \"totalAcceptedRaw\": 247857, \"totalSubmissionRaw\": 524629, \"acRate\": \"47.2%\"}",
    "title_pt": "Área de Retângulo",
    "description_pt": "<p>Dadas as coordenadas de dois retângulos <strong>retilíneos</strong> em um plano 2D, retorne <em>a área total coberta pelos dois retângulos</em>.</p>\n\n<p>O primeiro retângulo é definido pelo seu vértice <strong>inferior esquerdo</strong> <code>(ax1, ay1)</code> e pelo seu vértice <strong>superior direito</strong> <code>(ax2, ay2)</code>.</p>\n\n<p>O segundo retângulo é definido pelo seu vértice <strong>inferior esquerdo</strong> <code>(bx1, by1)</code> e pelo seu vértice <strong>superior direito</strong> <code>(bx2, by2)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"Rectangle Area\" src=\"https://assets.leetcode.com/uploads/2021/05/08/rectangle-plane.png\" style=\"width: 700px; height: 365px;\" />\n<pre>\n<strong>Entrada:</strong> ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\n<strong>Saída:</strong> 45\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\n<strong>Saída:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>4</sup> &lt;= ax1 &lt;= ax2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= ay1 &lt;= ay2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= bx1 &lt;= bx2 &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= by1 &lt;= by2 &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "224",
    "paidOnly": false,
    "title": "Basic Calculator",
    "titleSlug": "basic-calculator",
    "url": "https://leetcode.com/problems/basic-calculator",
    "description_url": "https://leetcode.com/problems/basic-calculator/description/",
    "description": "<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>\n\n<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;1 + 1&quot;\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot; 2-1 + 2 &quot;\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot;\n<strong>Output:</strong> 23\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>\n\t<li><code>s</code> represents a valid expression.</li>\n\t<li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li>\n\t<li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li>\n\t<li>There will be no two consecutive operators in the input.</li>\n\t<li>Every number and running calculation will fit in a signed 32-bit integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/basic-calculator/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def calculate(self, s: str) -> int:\n    ans = 0\n    num = 0\n    sign = 1\n    stack = [sign]  # stack[-1]: current env's sign\n\n    for c in s:\n      if c.isdigit():\n        num = num * 10 + (ord(c) - ord('0'))\n      elif c == '(':\n        stack.append(sign)\n      elif c == ')':\n        stack.pop()\n      elif c == '+' or c == '-':\n        ans += sign * num\n        sign = (1 if c == '+' else -1) * stack[-1]\n        num = 0\n\n    return ans + sign * num",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int calculate(String s) {\n    int ans = 0;\n    int num = 0;\n    int sign = 1;\n    Deque<Integer> stack = new ArrayDeque<>(); // Stack.peek(): current env's sign\n    stack.push(sign);\n\n    for (final char c : s.toCharArray())\n      if (Character.isDigit(c))\n        num = num * 10 + (c - '0');\n      else if (c == '(')\n        stack.push(sign);\n      else if (c == ')')\n        stack.pop();\n      else if (c == '+' || c == '-') {\n        ans += sign * num;\n        sign = (c == '+' ? 1 : -1) * stack.peek();\n        num = 0;\n      }\n\n    return ans + sign * num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int calculate(string s) {\n    int ans = 0;\n    int num = 0;\n    int sign = 1;\n    stack<int> stack{{sign}};  // Stack.top(): current env's sign\n\n    for (const char c : s)\n      if (isdigit(c))\n        num = num * 10 + (c - '0');\n      else if (c == '(')\n        stack.push(sign);\n      else if (c == ')')\n        stack.pop();\n      else if (c == '+' || c == '-') {\n        ans += sign * num;\n        sign = (c == '+' ? 1 : -1) * stack.top();\n        num = 0;\n      }\n\n    return ans + sign * num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/224.html",
    "category": "Algorithms",
    "acceptance_rate": 45.37544738230404,
    "topics": [
      "Math",
      "String",
      "Stack",
      "Recursion"
    ],
    "hints": [],
    "likes": 6625,
    "dislikes": 536,
    "similar_questions": "[{\"title\": \"Evaluate Reverse Polish Notation\", \"titleSlug\": \"evaluate-reverse-polish-notation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator II\", \"titleSlug\": \"basic-calculator-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Different Ways to Add Parentheses\", \"titleSlug\": \"different-ways-to-add-parentheses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Expression Add Operators\", \"titleSlug\": \"expression-add-operators\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator III\", \"titleSlug\": \"basic-calculator-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"The Score of Students Solving Math Expression\", \"titleSlug\": \"the-score-of-students-solving-math-expression\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimize Result by Adding Parentheses to Expression\", \"titleSlug\": \"minimize-result-by-adding-parentheses-to-expression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"590K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 590025, \"totalSubmissionRaw\": 1300327, \"acRate\": \"45.4%\"}",
    "title_pt": "Calculadora Básica",
    "description_pt": "<p>Dada uma string <code>s</code> representando uma expressão válida, implemente uma calculadora básica para avaliá-la e retorne <em>o resultado da avaliação</em>.</p>\n\n<p><strong>Nota:</strong> Você <strong>não</strong> tem permissão para usar nenhuma função embutida que avalie strings como expressões matemáticas, como <code>eval()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;1 + 1&quot;\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot; 2-1 + 2 &quot;\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot;\n<strong>Saída:</strong> 23\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em dígitos, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> e <code>&#39; &#39;</code>.</li>\n\t<li><code>s</code> representa uma expressão válida.</li>\n\t<li><code>&#39;+&#39;</code> <strong>não</strong> é usado como uma operação unária (ou seja, <code>&quot;+1&quot;</code> e <code>&quot;+(2 + 3)&quot;</code> são inválidos).</li>\n\t<li><code>&#39;-&#39;</code> pode ser usado como uma operação unária (ou seja, <code>&quot;-1&quot;</code> e <code>&quot;-(2 + 3)&quot;</code> são válidos).</li>\n\t<li>Não haverá dois operadores consecutivos na entrada.</li>\n\t<li>Cada número e cálculo em andamento caberá em um inteiro com sinal de 32 bits.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "225",
    "paidOnly": false,
    "title": "Implement Stack using Queues",
    "titleSlug": "implement-stack-using-queues",
    "url": "https://leetcode.com/problems/implement-stack-using-queues",
    "description_url": "https://leetcode.com/problems/implement-stack-using-queues/description/",
    "description": "<p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p>\n\n<p>Implement the <code>MyStack</code> class:</p>\n\n<ul>\n\t<li><code>void push(int x)</code> Pushes element x to the top of the stack.</li>\n\t<li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li>\n\t<li><code>int top()</code> Returns the element on the top of the stack.</li>\n\t<li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li>\n</ul>\n\n<p><b>Notes:</b></p>\n\n<ul>\n\t<li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li>\n\t<li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue&#39;s standard operations.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;]\n[[], [1], [2], [], [], []]\n<strong>Output</strong>\n[null, null, null, 2, 2, false]\n\n<strong>Explanation</strong>\nMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x &lt;= 9</code></li>\n\t<li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li>\n\t<li>All the calls to <code>pop</code> and <code>top</code> are valid.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>\n",
    "solution_url": "https://leetcode.com/problems/implement-stack-using-queues/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass MyStack:\n  def __init__(self):\n    self.q = deque()\n\n  def push(self, x: int) -> None:\n    self.q.append(x)\n    for _ in range(len(self.q) - 1):\n      self.q.append(self.q.popleft())\n\n  def pop(self) -> int:\n    return self.q.popleft()\n\n  def top(self) -> int:\n    return self.q[0]\n\n  def empty(self) -> bool:\n    return not self.q",
    "solution_code_java": "\t\t\t\n\nclass MyStack {\n  public void push(int x) {\n    q.offer(x);\n    for (int i = 0; i < q.size() - 1; ++i)\n      q.offer(q.poll());\n  }\n\n  public int pop() {\n    return q.poll();\n  }\n\n  public int top() {\n    return q.peek();\n  }\n\n  public boolean empty() {\n    return q.isEmpty();\n  }\n\n  private Queue<Integer> q = new ArrayDeque<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyStack {\n public:\n  void push(int x) {\n    q.push(x);\n    for (int i = 0; i < q.size() - 1; ++i) {\n      q.push(q.front());\n      q.pop();\n    }\n  }\n\n  int pop() {\n    const int val = q.front();\n    q.pop();\n    return val;\n  }\n\n  int top() {\n    return q.front();\n  }\n\n  bool empty() {\n    return q.empty();\n  }\n\n private:\n  queue<int> q;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/225.html",
    "category": "Algorithms",
    "acceptance_rate": 67.02444070865124,
    "topics": [
      "Stack",
      "Design",
      "Queue"
    ],
    "hints": [],
    "likes": 6446,
    "dislikes": 1249,
    "similar_questions": "[{\"title\": \"Implement Queue using Stacks\", \"titleSlug\": \"implement-queue-using-stacks\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"891.5K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 891464, \"totalSubmissionRaw\": 1330062, \"acRate\": \"67.0%\"}",
    "title_pt": "Implementar Pilha usando Filas",
    "description_pt": "<p>Implemente uma pilha last-in-first-out (LIFO) usando apenas duas filas. A pilha implementada deve suportar todas as funções de uma pilha normal (<code>push</code>, <code>top</code>, <code>pop</code> e <code>empty</code>).</p>\n\n<p>Implemente a classe <code>MyStack</code>:</p>\n\n<ul>\n\t<li><code>void push(int x)</code> Insere o elemento x no topo da pilha.</li>\n\t<li><code>int pop()</code> Remove o elemento do topo da pilha e o retorna.</li>\n\t<li><code>int top()</code> Retorna o elemento do topo da pilha.</li>\n\t<li><code>boolean empty()</code> Retorna <code>true</code> se a pilha estiver vazia, <code>false</code> caso contrário.</li>\n</ul>\n\n<p><b>Notas:</b></p>\n\n<ul>\n\t<li>Você deve usar <strong>apenas</strong> operações padrão de uma fila, o que significa que somente as operações <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> e <code>is empty</code> são válidas.</li>\n\t<li>Dependendo da sua linguagem, a fila pode não ser suportada nativamente. Você pode simular uma fila usando uma lista ou deque (fila de duas extremidades) desde que use apenas as operações padrão de uma fila.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyStack&quot;, &quot;push&quot;, &quot;push&quot;, &quot;top&quot;, &quot;pop&quot;, &quot;empty&quot;]\n[[], [1], [2], [], [], []]\n<strong>Saída</strong>\n[null, null, null, 2, 2, false]\n\n<strong>Explicação</strong>\nMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x &lt;= 9</code></li>\n\t<li>No máximo <code>100</code> chamadas serão feitas para <code>push</code>, <code>pop</code>, <code>top</code> e <code>empty</code>.</li>\n\t<li>Todas as chamadas a <code>pop</code> e <code>top</code> são válidas.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue implementar a pilha usando apenas uma fila?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "226",
    "paidOnly": false,
    "title": "Invert Binary Tree",
    "titleSlug": "invert-binary-tree",
    "url": "https://leetcode.com/problems/invert-binary-tree",
    "description_url": "https://leetcode.com/problems/invert-binary-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, invert the tree, and return <em>its root</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg\" style=\"width: 500px; height: 165px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,7,1,3,6,9]\n<strong>Output:</strong> [4,7,2,9,6,3,1]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg\" style=\"width: 500px; height: 120px;\" />\n<pre>\n<strong>Input:</strong> root = [2,1,3]\n<strong>Output:</strong> [2,3,1]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/invert-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n    if not root:\n      return None\n\n    left = root.left\n    right = root.right\n    root.left = self.invertTree(right)\n    root.right = self.invertTree(left)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode invertTree(TreeNode root) {\n    if (root == null)\n      return null;\n\n    TreeNode left = root.left;\n    TreeNode right = root.right;\n    root.left = invertTree(right);\n    root.right = invertTree(left);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* invertTree(TreeNode* root) {\n    if (root == nullptr)\n      return nullptr;\n\n    TreeNode* const left = root->left;\n    TreeNode* const right = root->right;\n    root->left = invertTree(right);\n    root->right = invertTree(left);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/226.html",
    "category": "Algorithms",
    "acceptance_rate": 78.8866432737948,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 14583,
    "dislikes": 242,
    "similar_questions": "[{\"title\": \"Reverse Odd Levels of Binary Tree\", \"titleSlug\": \"reverse-odd-levels-of-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.6M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 2578870, \"totalSubmissionRaw\": 3269083, \"acRate\": \"78.9%\"}",
    "title_pt": "Inverter Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, inverta a árvore e retorne <em>sua raiz</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg\" style=\"width: 500px; height: 165px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,7,1,3,6,9]\n<strong>Saída:</strong> [4,7,2,9,6,3,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg\" style=\"width: 500px; height: 120px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,1,3]\n<strong>Saída:</strong> [2,3,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "227",
    "paidOnly": false,
    "title": "Basic Calculator II",
    "titleSlug": "basic-calculator-ii",
    "url": "https://leetcode.com/problems/basic-calculator-ii",
    "description_url": "https://leetcode.com/problems/basic-calculator-ii/description/",
    "description": "<p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p>\n\n<p>The integer division should truncate toward zero.</p>\n\n<p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>\n\n<p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"3+2*2\"\n<strong>Output:</strong> 7\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \" 3/2 \"\n<strong>Output:</strong> 1\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> s = \" 3+5 / 2 \"\n<strong>Output:</strong> 5\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of integers and operators <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separated by some number of spaces.</li>\n\t<li><code>s</code> represents <strong>a valid expression</strong>.</li>\n\t<li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li>\n\t<li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/basic-calculator-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Overview\nThere are multiple variations of this problem like [Basic Calculator](https://leetcode.com/problems/basic-calculator/) and [Basic Calculator III](https://leetcode.com/problems/basic-calculator-iii/). This problem is relatively simpler to solve, as we don't have to take care of the parenthesis.\n\nThe aim is to evaluate the given mathematical expression by applying the basic mathematical rules. The expressions are evaluated from left to right and the order of evaluation depends on the [Operator Precedence](https://en.wikipedia.org/wiki/Order_of_operations). Let's understand how we could implement the problem using different approaches.\n\n---\n### Approach 1: Using Stack\n\n#### Intuition\n\nWe know that there could be 4 types of operations - addition `(+)`, subtraction `(-)`, multiplication `(*)` and division `(/)`.  Without parenthesis, we know that, multiplication  `(*)` and `(\\)` operations would always have higher precedence than addition `(+)` and subtraction `(-)` based on operator precedence rules.\n\n ![img](../Figures/227/calculator_overview.png)\n\nIf we look at the above examples, we can make the following observations -\n- If the current operation is addition `(+)` or subtraction `(-)`, then the expression is evaluated based on the precedence of the next operation.\n\nIn example 1, `4+3` is evaluated later because the next operation is multiplication `(3*5)` which has higher precedence.\nBut,  in example 2, `4+3` is evaluated first because the next operation is subtraction `(3-5)` which has equal precedence.\n\n- If the current operator is multiplication `(*)` or division `(/)`, then the expression is evaluated irrespective of the next operation. This is because in the given set of operations `(+,-,*,/)`, the  `*` and `/` operations have the highest precedence and therefore must be evaluated first.\n\nIn the above examples 3 and 4, `4*3` is always evaluated first irrespective of the next operation.\n\nUsing this intuition let's look at the algorithm to implement the problem.\n\n\n#### Algorithm\n\nScan the input string `s` from left to right and evaluate the expressions based on the following rules\n\n1) If the current character is a digit `0-9` ( operand ), add it to the number `currentNumber`.\n2) Otherwise, the current character must be an operation `(+,-,*, /)`. Evaluate the expression based on the type of operation.\n- Addition `(+)` or Subtraction `(-)`: We must evaluate the expression later based on the next operation. So, we must store the `currentNumber` to be used later. Let's push the currentNumber in the Stack.\n\n>[Stack data structure](https://leetcode.com/explore/learn/card/queue-stack/230/usage-stack/) follows Last In First Out (LIFO) principle. Hence, the last pushed number in the stack would be popped out first for evaluation.  In addition, when we pop from the stack and evaluate this expression in the future, we need a way to determine if the operation was Addition `(+)` or Subtraction `(-)`. To simplify our evaluation, we can push `-currentNumber` in a stack if the current operation is subtraction (`-`) and assume that the operation for all the values in the stack is addition `(+)`. This works because `(a - currentNumber)` is equivalent to `(a + (-currentNumber))`.\n\n - Multiplication `(*)` or Division `(/)`: Pop the top values from the stack and evaluate the current expression. Push the evaluated value back to the stack.\n\nOnce the string is scanned, pop from the stack and add to the `result`.\n\n\n!?!../Documents/227_LIS.json:1414,716!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/6A5bNZvg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"6A5bNZvg\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$\\mathcal{O}(n)$$,  where $$n$$ is the length of the string $$s$$. We iterate over the string $$s$$ at most twice.\n\n* Space Complexity: $$\\mathcal{O}(n)$$, where $$n$$ is the length of the string $$s$$.\n\n---\n### Approach 2: Optimised Approach without the stack\n\n#### Intuition\n\nIn the previous approach, we used a stack to track the values of the evaluated expressions. In the end, we pop all the values from the stack and add to the result. Instead of that, we could add the values to the result beforehand and keep track of the last calculated number, thus eliminating the need for the stack. Let's understand the algorithm in detail.\n\n#### Algorithm\n\nThe approach works similar to _Approach 1_ with the following differences :\n\n- Instead of using a `stack`, we use a variable `lastNumber` to track the value of the last evaluated expression.\n- If the operation is Addition `(+)` or Subtraction `(-)`, add the `lastNumber` to the result instead of pushing it to the stack. The `currentNumber` would be updated to `lastNumber` for the next iteration.\n- If the operation is Multiplication `(*)` or Division `(/)`, we must evaluate the expression `lastNumber * currentNumber` and update the `lastNumber` with the result of the expression.  This would be added to the result after the entire string is scanned.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ao7b4uv8/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ao7b4uv8\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$\\mathcal{O}(n)$$,  where $$n$$ is the length of the string $$s$$.\n\n* Space Complexity: $$\\mathcal{O}(1)$$, as we use constant extra space to store `lastNumber`, `result` and so on.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def calculate(self, s: str) -> int:\n    ans = 0\n    prevNum = 0\n    currNum = 0\n    op = '+'\n\n    for i, c in enumerate(s):\n      if c.isdigit():\n        currNum = currNum * 10 + int(c)\n      if not c.isdigit() and c != ' ' or i == len(s) - 1:\n        if op == '+' or op == '-':\n          ans += prevNum\n          prevNum = currNum if op == '+' else -currNum\n        elif op == '*':\n          prevNum = prevNum * currNum\n        elif op == '/':\n          if prevNum < 0:\n            prevNum = ceil(prevNum / currNum)\n          else:\n            prevNum = prevNum // currNum\n        op = c\n        currNum = 0\n\n    return ans + prevNum",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int calculate(String s) {\n    Deque<Integer> nums = new ArrayDeque<>();  // Stores nums\n    Deque<Character> ops = new ArrayDeque<>(); // Stores operators and parentheses\n\n    for (int i = 0; i < s.length(); ++i) {\n      final char c = s.charAt(i);\n      if (Character.isDigit(c)) {\n        int num = c - '0';\n        while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {\n          num = num * 10 + (s.charAt(i + 1) - '0');\n          ++i;\n        }\n        nums.push(num);\n      } else if (c == '+' || c == '-' || c == '*' || c == '/') {\n        while (!ops.isEmpty() && compare(ops.peek(), c))\n          nums.push(calculate(ops.pop(), nums.pop(), nums.pop()));\n        ops.push(c);\n      }\n    }\n\n    while (!ops.isEmpty())\n      nums.push(calculate(ops.pop(), nums.pop(), nums.pop()));\n\n    return nums.peek();\n  }\n\n  private int calculate(char op, int b, int a) {\n    switch (op) {\n      case '+':\n        return a + b;\n      case '-':\n        return a - b;\n      case '*':\n        return a * b;\n      case '/':\n        return a / b;\n    }\n    throw new IllegalArgumentException();\n  }\n\n  // Returns true if priority(op1) >= priority(op2)\n  private boolean compare(char op1, char op2) {\n    return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-';\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int calculate(string s) {\n    stack<int> nums;  // Stores nums\n    stack<char> ops;  // Stores operators\n\n    for (int i = 0; i < s.length(); ++i) {\n      const char c = s[i];\n      if (isdigit(c)) {\n        int num = c - '0';\n        while (i + 1 < s.length() && isdigit(s[i + 1])) {\n          num = num * 10 + (s[i + 1] - '0');\n          ++i;\n        }\n        nums.push(num);\n      } else if (c == '+' || c == '-' || c == '*' || c == '/') {\n        while (!ops.empty() && compare(ops.top(), c))\n          nums.push(calculate(pop(ops), pop(nums), pop(nums)));\n        ops.push(c);\n      }\n    }\n\n    while (!ops.empty())\n      nums.push(calculate(pop(ops), pop(nums), pop(nums)));\n\n    return nums.top();\n  }\n\n private:\n  int calculate(char op, int b, int a) {\n    switch (op) {\n      case '+':\n        return a + b;\n      case '-':\n        return a - b;\n      case '*':\n        return a * b;\n      case '/':\n        return a / b;\n    }\n    throw;\n  }\n\n  // Returns true if priority(op1) >= priority(op2)\n  bool compare(char op1, char op2) {\n    return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-';\n  }\n\n  char pop(stack<char>& ops) {\n    const char op = ops.top();\n    ops.pop();\n    return op;\n  }\n\n  int pop(stack<int>& nums) {\n    const int num = nums.top();\n    nums.pop();\n    return num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/227.html",
    "category": "Algorithms",
    "acceptance_rate": 45.64939050932382,
    "topics": [
      "Math",
      "String",
      "Stack"
    ],
    "hints": [],
    "likes": 6405,
    "dislikes": 918,
    "similar_questions": "[{\"title\": \"Basic Calculator\", \"titleSlug\": \"basic-calculator\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Expression Add Operators\", \"titleSlug\": \"expression-add-operators\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator III\", \"titleSlug\": \"basic-calculator-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"823.2K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 823233, \"totalSubmissionRaw\": 1803375, \"acRate\": \"45.6%\"}",
    "title_pt": "Calculadora Básica II",
    "description_pt": "<p>Dada uma string <code>s</code> que representa uma expressão, <em>avalie esta expressão e retorne seu valor</em>.&nbsp;</p>\n\n<p>A divisão inteira deve truncar em direção a zero.</p>\n\n<p>Você pode assumir que a expressão fornecida é sempre válida. Todos os resultados intermediários estarão no intervalo <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>\n\n<p><strong>Nota:</strong> Não é permitido usar nenhuma função embutida que avalie strings como expressões matemáticas, como <code>eval()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"3+2*2\"\n<strong>Saída:</strong> 7\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \" 3/2 \"\n<strong>Saída:</strong> 1\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> s = \" 3+5 / 2 \"\n<strong>Saída:</strong> 5\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em inteiros e operadores <code>(&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;)</code> separados por algum número de espaços.</li>\n\t<li><code>s</code> representa <strong>uma expressão válida</strong>.</li>\n\t<li>Todos os inteiros na expressão são inteiros não negativos no intervalo <code>[0, 2<sup>31</sup> - 1]</code>.</li>\n\t<li>A resposta é <strong>garantidamente</strong> compatível com um <strong>inteiro de 32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "228",
    "paidOnly": false,
    "title": "Summary Ranges",
    "titleSlug": "summary-ranges",
    "url": "https://leetcode.com/problems/summary-ranges",
    "description_url": "https://leetcode.com/problems/summary-ranges/description/",
    "description": "<p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p>\n\n<p>A <strong>range</strong> <code>[a,b]</code> is the set of all integers from <code>a</code> to <code>b</code> (inclusive).</p>\n\n<p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p>\n\n<p>Each range <code>[a,b]</code> in the list should be output as:</p>\n\n<ul>\n\t<li><code>&quot;a-&gt;b&quot;</code> if <code>a != b</code></li>\n\t<li><code>&quot;a&quot;</code> if <code>a == b</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,2,4,5,7]\n<strong>Output:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;]\n<strong>Explanation:</strong> The ranges are:\n[0,2] --&gt; &quot;0-&gt;2&quot;\n[4,5] --&gt; &quot;4-&gt;5&quot;\n[7,7] --&gt; &quot;7&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,2,3,4,6,8,9]\n<strong>Output:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;]\n<strong>Explanation:</strong> The ranges are:\n[0,0] --&gt; &quot;0&quot;\n[2,4] --&gt; &quot;2-&gt;4&quot;\n[6,6] --&gt; &quot;6&quot;\n[8,9] --&gt; &quot;8-&gt;9&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is sorted in ascending order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/summary-ranges/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def summaryRanges(self, nums: List[int]) -> List[str]:\n    ans = []\n\n    i = 0\n    while i < len(nums):\n      begin = nums[i]\n      while i < len(nums) - 1 and nums[i] == nums[i + 1] - 1:\n        i += 1\n      end = nums[i]\n      if begin == end:\n        ans.append(str(begin))\n      else:\n        ans.append(str(begin) + \"->\" + str(end))\n      i += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> summaryRanges(int[] nums) {\n    List<String> ans = new ArrayList<>();\n\n    for (int i = 0; i < nums.length; ++i) {\n      final int begin = nums[i];\n      while (i + 1 < nums.length && nums[i] == nums[i + 1] - 1)\n        ++i;\n      final int end = nums[i];\n      if (begin == end)\n        ans.add(\"\" + begin);\n      else\n        ans.add(\"\" + begin + \"->\" + end);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> summaryRanges(vector<int>& nums) {\n    vector<string> ans;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const int begin = nums[i];\n      while (i + 1 < nums.size() && nums[i] == nums[i + 1] - 1)\n        ++i;\n      const int end = nums[i];\n      if (begin == end)\n        ans.push_back(to_string(begin));\n      else\n        ans.push_back(to_string(begin) + \"->\" + to_string(end));\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/228.html",
    "category": "Algorithms",
    "acceptance_rate": 52.91037119971972,
    "topics": [
      "Array"
    ],
    "hints": [],
    "likes": 4269,
    "dislikes": 2315,
    "similar_questions": "[{\"title\": \"Missing Ranges\", \"titleSlug\": \"missing-ranges\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Data Stream as Disjoint Intervals\", \"titleSlug\": \"data-stream-as-disjoint-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Maximal Uncovered Ranges\", \"titleSlug\": \"find-maximal-uncovered-ranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"779.3K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 779265, \"totalSubmissionRaw\": 1472806, \"acRate\": \"52.9%\"}",
    "title_pt": "Intervalos de Resumo",
    "description_pt": "<p>Você recebe um array de inteiros <strong>ordenado e com valores únicos</strong> <code>nums</code>.</p>\n\n<p>Um <strong>intervalo</strong> <code>[a,b]</code> é o conjunto de todos os inteiros de <code>a</code> até <code>b</code> (inclusive).</p>\n\n<p>Retorne <em>a menor lista <strong>ordenada</strong> de intervalos que <strong>cubra exatamente todos os números no array</strong></em>. Isto é, cada elemento de <code>nums</code> é coberto exatamente por um dos intervalos, e não existe nenhum inteiro <code>x</code> tal que <code>x</code> esteja em um dos intervalos, mas não esteja em <code>nums</code>.</p>\n\n<p>Cada intervalo <code>[a,b]</code> na lista deve ser exibido como:</p>\n\n<ul>\n\t<li><code>&quot;a-&gt;b&quot;</code> se <code>a != b</code></li>\n\t<li><code>&quot;a&quot;</code> se <code>a == b</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,2,4,5,7]\n<strong>Saída:</strong> [&quot;0-&gt;2&quot;,&quot;4-&gt;5&quot;,&quot;7&quot;]\n<strong>Explicação:</strong> Os intervalos são:\n[0,2] --&gt; &quot;0-&gt;2&quot;\n[4,5] --&gt; &quot;4-&gt;5&quot;\n[7,7] --&gt; &quot;7&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,2,3,4,6,8,9]\n<strong>Saída:</strong> [&quot;0&quot;,&quot;2-&gt;4&quot;,&quot;6&quot;,&quot;8-&gt;9&quot;]\n<strong>Explicação:</strong> Os intervalos são:\n[0,0] --&gt; &quot;0&quot;\n[2,4] --&gt; &quot;2-&gt;4&quot;\n[6,6] --&gt; &quot;6&quot;\n[8,9] --&gt; &quot;8-&gt;9&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Todos os valores de <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li><code>nums</code> está ordenado em ordem crescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "229",
    "paidOnly": false,
    "title": "Majority Element II",
    "titleSlug": "majority-element-ii",
    "url": "https://leetcode.com/problems/majority-element-ii",
    "description_url": "https://leetcode.com/problems/majority-element-ii/description/",
    "description": "<p>Given an integer array of size <code>n</code>, find all elements that appear more than <code>&lfloor; n/3 &rfloor;</code> times.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,3]\n<strong>Output:</strong> [3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1]\n<strong>Output:</strong> [1]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2]\n<strong>Output:</strong> [1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</p>\n",
    "solution_url": "https://leetcode.com/problems/majority-element-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def majorityElement(self, nums: List[int]) -> List[int]:\n    ans1 = 0\n    ans2 = 1\n    count1 = 0\n    count2 = 0\n\n    for num in nums:\n      if num == ans1:\n        count1 += 1\n      elif num == ans2:\n        count2 += 1\n      elif count1 == 0:\n        ans1 = num\n        count1 = 1\n      elif count2 == 0:\n        ans2 = num\n        count2 = 1\n      else:\n        count1 -= 1\n        count2 -= 1\n\n    return [ans for ans in (ans1, ans2) if nums.count(ans) > len(nums) // 3]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> majorityElement(int[] nums) {\n    List<Integer> ans = new ArrayList<>();\n    int candidate1 = 0;\n    int candidate2 = 1;  // Any number different from candidate1\n    int countSoFar1 = 0; // # of candidate1 so far\n    int countSoFar2 = 0; // # of candidate2 so far\n\n    for (final int num : nums)\n      if (num == candidate1) {\n        ++countSoFar1;\n      } else if (num == candidate2) {\n        ++countSoFar2;\n      } else if (countSoFar1 == 0) { // Assign new candidate\n        candidate1 = num;\n        ++countSoFar1;\n      } else if (countSoFar2 == 0) { // Assign new candidate\n        candidate2 = num;\n        ++countSoFar2;\n      } else { // Meet a new number, so pair out previous counts\n        --countSoFar1;\n        --countSoFar2;\n      }\n\n    int count1 = 0;\n    int count2 = 0;\n\n    for (final int num : nums)\n      if (num == candidate1)\n        ++count1;\n      else if (num == candidate2)\n        ++count2;\n\n    if (count1 > nums.length / 3)\n      ans.add(candidate1);\n    if (count2 > nums.length / 3)\n      ans.add(candidate2);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> majorityElement(vector<int>& nums) {\n    vector<int> ans;\n    int candidate1 = 0;\n    int candidate2 = 1;   // Any number different from candidate1\n    int countSoFar1 = 0;  // # of candidate1 so far\n    int countSoFar2 = 0;  // # of candidate2 so far\n\n    for (const int num : nums)\n      if (num == candidate1) {\n        ++countSoFar1;\n      } else if (num == candidate2) {\n        ++countSoFar2;\n      } else if (countSoFar1 == 0) {  // Assign new candidate\n        candidate1 = num;\n        ++countSoFar1;\n      } else if (countSoFar2 == 0) {  // Assign new candidate\n        candidate2 = num;\n        ++countSoFar2;\n      } else {  // Meet a new number, so pair out previous counts\n        --countSoFar1;\n        --countSoFar2;\n      }\n\n    const int count1 = count(begin(nums), end(nums), candidate1);\n    const int count2 = count(begin(nums), end(nums), candidate2);\n\n    if (count1 > nums.size() / 3)\n      ans.push_back(candidate1);\n    if (count2 > nums.size() / 3)\n      ans.push_back(candidate2);\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/229.html",
    "category": "Algorithms",
    "acceptance_rate": 54.12962479314525,
    "topics": [
      "Array",
      "Hash Table",
      "Sorting",
      "Counting"
    ],
    "hints": [
      "Think about the possible number of elements that can appear more than ⌊ n/3 ⌋ times in the array.",
      "It can be at most two. Why?",
      "Consider using Boyer-Moore Voting Algorithm, which is efficient for finding elements that appear more than a certain threshold."
    ],
    "likes": 10290,
    "dislikes": 460,
    "similar_questions": "[{\"title\": \"Majority Element\", \"titleSlug\": \"majority-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Check If a Number Is Majority Element in a Sorted Array\", \"titleSlug\": \"check-if-a-number-is-majority-element-in-a-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"949.2K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 949213, \"totalSubmissionRaw\": 1753601, \"acRate\": \"54.1%\"}",
    "title_pt": "Elemento da Maioria II",
    "description_pt": "<p>Dado um array de inteiros de tamanho <code>n</code>, encontre todos os elementos que aparecem mais de <code>&lfloor; n/3 &rfloor;</code> vezes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,3]\n<strong>Saída:</strong> [3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> [1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2]\n<strong>Saída:</strong> [1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria resolver o problema em tempo linear e em espaço <code>O(1)</code>?</p>",
    "hints_pt": [
      "Dica 1: Pense sobre o número possível de elementos que podem aparecer mais de ⌊ n/3 ⌋ vezes no array.",
      "Dica 2: Pode haver no máximo dois. Por quê?",
      "Dica 3: Considere usar o Algoritmo de Votação de Boyer-Moore, que é eficiente para encontrar elementos que aparecem mais do que um certo limite."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "230",
    "paidOnly": false,
    "title": "Kth Smallest Element in a BST",
    "titleSlug": "kth-smallest-element-in-a-bst",
    "url": "https://leetcode.com/problems/kth-smallest-element-in-a-bst",
    "description_url": "https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/",
    "description": "<p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg\" style=\"width: 212px; height: 301px;\" />\n<pre>\n<strong>Input:</strong> root = [3,1,4,null,2], k = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg\" style=\"width: 382px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is <code>n</code>.</li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>\n",
    "solution_url": "https://leetcode.com/problems/kth-smallest-element-in-a-bst/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n    def countNodes(root: Optional[TreeNode]) -> int:\n      if not root:\n        return 0\n      return 1 + countNodes(root.left) + countNodes(root.right)\n\n    leftCount = countNodes(root.left)\n\n    if leftCount == k - 1:\n      return root.val\n    if leftCount >= k:\n      return self.kthSmallest(root.left, k)\n    return self.kthSmallest(root.right, k - 1 - leftCount)  # LeftCount < k",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int kthSmallest(TreeNode root, int k) {\n    final int leftCount = countNodes(root.left);\n\n    if (leftCount == k - 1)\n      return root.val;\n    if (leftCount >= k)\n      return kthSmallest(root.left, k);\n    return kthSmallest(root.right, k - 1 - leftCount); // LeftCount < k\n  }\n\n  private int countNodes(TreeNode root) {\n    if (root == null)\n      return 0;\n    return 1 + countNodes(root.left) + countNodes(root.right);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int kthSmallest(TreeNode* root, int k) {\n    const int leftCount = countNodes(root->left);\n\n    if (leftCount == k - 1)\n      return root->val;\n    if (leftCount >= k)\n      return kthSmallest(root->left, k);\n    return kthSmallest(root->right, k - 1 - leftCount);  // LeftCount < k\n  }\n\n private:\n  int countNodes(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    return 1 + countNodes(root->left) + countNodes(root->right);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/230.html",
    "category": "Algorithms",
    "acceptance_rate": 75.115996060204,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [
      "Try to utilize the property of a BST.",
      "Try in-order traversal. (Credits to @chan13)",
      "What if you could modify the BST node's structure?",
      "The optimal runtime complexity is O(height of BST)."
    ],
    "likes": 12051,
    "dislikes": 242,
    "similar_questions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Second Minimum Node In a Binary Tree\", \"titleSlug\": \"second-minimum-node-in-a-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1845558, \"totalSubmissionRaw\": 2456950, \"acRate\": \"75.1%\"}",
    "title_pt": "K-ésimo Menor Elemento em uma BST",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária de busca e um inteiro <code>k</code>, retorne <em>o</em> <code>k<sup>ésimo</sup></code> <em>menor valor (<strong>indexado em 1</strong>) dentre todos os valores dos nós na árvore</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg\" style=\"width: 212px; height: 301px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,1,4,null,2], k = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg\" style=\"width: 382px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,3,6,2,4,null,null,1], k = 3\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore é <code>n</code>.</li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Se a BST for modificada com frequência (isto é, podemos realizar operações de inserção e remoção) e você precisar encontrar o k-ésimo menor com frequência, como você otimizaria?</p>",
    "hints_pt": [
      "Dica 1: Tente utilizar a propriedade de uma BST.",
      "Dica 2: Tente uma travessia em ordem. (Créditos para @chan13)",
      "Dica 3: E se você pudesse modificar a estrutura do nó da BST?",
      "Dica 4: A complexidade de tempo ótima é O(height of BST)."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "231",
    "paidOnly": false,
    "title": "Power of Two",
    "titleSlug": "power-of-two",
    "url": "https://leetcode.com/problems/power-of-two",
    "description_url": "https://leetcode.com/problems/power-of-two/description/",
    "description": "<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of two. Otherwise, return <code>false</code></em>.</p>\n\n<p>An integer <code>n</code> is a power of two, if there exists an integer <code>x</code> such that <code>n == 2<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n<strong>Explanation: </strong>2<sup>0</sup> = 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 16\n<strong>Output:</strong> true\n<strong>Explanation: </strong>2<sup>4</sup> = 16\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without loops/recursion?",
    "solution_url": "https://leetcode.com/problems/power-of-two/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPowerOfTwo(self, n: int) -> bool:\n    return False if n < 0 else bin(n).count('1') == 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPowerOfTwo(int n) {\n    return n < 0 ? false : Integer.bitCount(n) == 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPowerOfTwo(int n) {\n    return n < 0 ? false : __builtin_popcountll(n) == 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/231.html",
    "category": "Algorithms",
    "acceptance_rate": 48.3286174311799,
    "topics": [
      "Math",
      "Bit Manipulation",
      "Recursion"
    ],
    "hints": [],
    "likes": 7229,
    "dislikes": 467,
    "similar_questions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Three\", \"titleSlug\": \"power-of-three\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Four\", \"titleSlug\": \"power-of-four\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 1667678, \"totalSubmissionRaw\": 3450705, \"acRate\": \"48.3%\"}",
    "title_pt": "Potência de Dois",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em><code>true</code> se ele for uma potência de dois. Caso contrário, retorne <code>false</code></em>.</p>\n\n<p>Um inteiro <code>n</code> é uma potência de dois se existir um inteiro <code>x</code> tal que <code>n == 2<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> true\n<strong>Explicação: </strong>2<sup>0</sup> = 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 16\n<strong>Saída:</strong> true\n<strong>Explicação: </strong>2<sup>4</sup> = 16\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue resolvê-lo sem loops/recursão?",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "232",
    "paidOnly": false,
    "title": "Implement Queue using Stacks",
    "titleSlug": "implement-queue-using-stacks",
    "url": "https://leetcode.com/problems/implement-queue-using-stacks",
    "description_url": "https://leetcode.com/problems/implement-queue-using-stacks/description/",
    "description": "<p>Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (<code>push</code>, <code>peek</code>, <code>pop</code>, and <code>empty</code>).</p>\n\n<p>Implement the <code>MyQueue</code> class:</p>\n\n<ul>\n\t<li><code>void push(int x)</code> Pushes element x to the back of the queue.</li>\n\t<li><code>int pop()</code> Removes the element from the front of the queue and returns it.</li>\n\t<li><code>int peek()</code> Returns the element at the front of the queue.</li>\n\t<li><code>boolean empty()</code> Returns <code>true</code> if the queue is empty, <code>false</code> otherwise.</li>\n</ul>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n\t<li>You must use <strong>only</strong> standard operations of a stack, which means only <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, and <code>is empty</code> operations are valid.</li>\n\t<li>Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack&#39;s standard operations.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;]\n[[], [1], [2], [], [], []]\n<strong>Output</strong>\n[null, null, null, 1, 1, false]\n\n<strong>Explanation</strong>\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x &lt;= 9</code></li>\n\t<li>At most <code>100</code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>peek</code>, and <code>empty</code>.</li>\n\t<li>All the calls to <code>pop</code> and <code>peek</code> are valid.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Can you implement the queue such that each operation is <strong><a href=\"https://en.wikipedia.org/wiki/Amortized_analysis\" target=\"_blank\">amortized</a></strong> <code>O(1)</code> time complexity? In other words, performing <code>n</code> operations will take overall <code>O(n)</code> time even if one of those operations may take longer.</p>\n",
    "solution_url": "https://leetcode.com/problems/implement-queue-using-stacks/solutions/",
    "solution": "[TOC]\n\n## Summary\nThis article is for beginners. It introduces the following ideas:\nQueue, Stack.\n\n## Solution\n\nQueue is **FIFO** (first in - first out) data structure, in which the elements are inserted from one side - `rear` and removed from the other - `front`.\nThe most intuitive way to implement it is with linked lists, but this article will introduce another approach  using stacks.\nStack is **LIFO** (last in - first out) data structure, in which elements are added and removed from the same end, called `top`.\nTo satisfy **FIFO** property of a queue we need to keep two stacks. They serve to reverse arrival order of the  elements and one of them store the queue elements in their final order.\n\n---\n\n### Approach #1 (Two Stacks) Push - $O(n)$ per operation, Pop - $O(1)$ per operation.\n\n#### Push\n\nA queue is FIFO (first-in-first-out) but a stack is LIFO (last-in-first-out). This means the newest element must be pushed to the bottom of the stack. To do so we first transfer all `s1` elements to auxiliary stack `s2`. Then the newly arrived element is pushed on top of `s2` and all its elements are popped and pushed to `s1`.\n\n![Push an element in queue](https://leetcode.com/media/original_images/232_queue_using_stacksBPush.png){:width=\"539px\"}\n\n\n*Figure 1. Push an element in queue*\n\n\n\n<iframe src=\"https://leetcode.com/playground/ZddHrP5d/shared\" frameBorder=\"0\" name=\"ZddHrP5d\" width=\"100%\" height=\"241\"></iframe>\n\n#### Complexity Analysis**\n\n* Time complexity : $O(n)$.\n\n Each element, with the exception of the newly arrived, is pushed and popped twice. The last inserted element is popped and pushed once. Therefore this gives  $4 n + 2$  operations where $n$ is the queue size. The  `push` and `pop` operations have $O(1)$ time complexity.\n\n* Space complexity : $O(n)$.\nWe need additional memory to store the queue elements\n\n#### Pop\n\nThe algorithm pops an element from  the stack `s1`, because `s1` stores always on its top the first inserted element in the queue.\nThe front element of the queue is kept as `front`.\n\n![Pop an element from queue](https://leetcode.com/media/original_images/232_queue_using_stacksBPop.png){:width=\"539px\"}\n\n\n*Figure 2. Pop an element from queue*\n\n\n<iframe src=\"https://leetcode.com/playground/UZJY8ns5/shared\" frameBorder=\"0\" width=\"100%\" height=\"157\" name=\"UZJY8ns5\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$.\n* Space complexity : $O(1)$.\n\n#### Empty\n\nStack `s1` contains all stack elements, so the algorithm checks `s1` size to return if the queue is empty.\n\n<iframe src=\"https://leetcode.com/playground/2urvcw97/shared\" frameBorder=\"0\" name=\"2urvcw97\" width=\"100%\" height=\"122\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$.\n* Space complexity : $O(1)$.\n\n#### Peek\n\nThe `front` element is kept in constant memory and is modified when we push or pop an element.\n\n<iframe src=\"https://leetcode.com/playground/VGjvtStE/shared\" frameBorder=\"0\" name=\"VGjvtStE\" width=\"100%\" height=\"122\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$. The `front` element has been calculated in advance and only returned in `peek` operation.\n* Space complexity : $O(1)$.\n\n---\n\n### Approach #2 (Two Stacks) Push - $O(1)$ per operation, Pop - Amortized $O(1)$ per operation.\n\n\n#### Push\n\nThe newly arrived element is always added on top of stack `s1` and the first element is kept as `front` queue element\n\n![Push an element in queue](https://leetcode.com/media/original_images/232_queue_using_stacksAPush.png){:width=\"539px\"}\n\n\n*Figure 3. Push an element in queue*\n\n\n\n<iframe src=\"https://leetcode.com/playground/qaVbztQ7/shared\" frameBorder=\"0\" name=\"qaVbztQ7\" width=\"100%\" height=\"224\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$. Аppending an element to a stack is an O(1) operation.\n\n* Space complexity : $O(n)$. We need additional memory to store the queue elements\n\n#### Pop\n\nWe have to remove element in front of the queue. This is the first inserted element in the stack `s1` and it is positioned at the bottom of the stack because of stack's `LIFO (last in - first out)` policy. To remove the bottom element  from  `s1`, we have to pop all elements from `s1` and to push them on to an additional stack `s2`, which helps us to store the elements of `s1` in reversed order. This way  the bottom element of `s1` will be positioned on top of `s2` and we can simply pop it from stack `s2`. Once `s2` is empty, the algorithm transfer data from `s1` to `s2` again.\n\n![Pop an element from stack](https://leetcode.com/media/original_images/232_queue_using_stacksAPop.png){:width=\"539px\"}\n\n\n*Figure 4. Pop an element from stack*\n\n\n\n<iframe src=\"https://leetcode.com/playground/PF3J5wXs/shared\" frameBorder=\"0\" width=\"100%\" height=\"174\" name=\"PF3J5wXs\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: Amortized $O(1)$, Worst-case $O(n)$. In the worst case scenario when stack `s2` is empty, the algorithm pops $n$ elements from stack s1 and pushes $n$ elements to `s2`, where $n$ is the queue size. This gives $2n$ operations, which is $O(n)$. But when stack `s2` is not empty the algorithm has $O(1)$ time complexity. So what does it mean by Amortized $O(1)$? Please see the next section on Amortized Analysis for more information.\n\n* Space complexity : $O(1)$.\n\n#### Amortized Analysis\n\nAmortized analysis gives the average performance (over time) of each operation in the worst case. The basic idea is that a worst case operation can alter the state in such a way that the worst case cannot occur again for a long time, thus amortizing its cost.\n\nConsider this example where we start with an empty queue with the following sequence of operations applied:\n\n$$\npush_1, push_2, \\ldots, push_n, pop_1,pop_2 \\ldots, pop_n\n$$\n\nThe worst case time complexity of a single pop operation is $O(n)$. Since we have $n$ pop operations, using the worst-case per operation analysis gives us a total of $O(n^2)$ time.\n\nHowever, in a sequence of operations the worst case does not occur often in each operation - some operations may be cheap, some may be expensive. Therefore, a traditional worst-case per operation analysis can give overly pessimistic bound. For example, in a dynamic array only some inserts take a linear time, though others - a constant time.\n\nIn the example above, the number of times pop operation can be called is limited by the number of push operations before it. Although a single pop operation could be expensive, it is expensive only once per `n` times (queue size), when `s2` is empty and there is a need for data transfer between `s1` and `s2`. Hence the total time complexity of the sequence is : `n` (for push operations) + `2*n` (for first pop operation) + `n - 1` ( for pop operations) which is $O(2*n)$.This gives $O(2n/2n)$ = $O(1)$ average time per operation.\n\n#### Empty\n\nBoth stacks `s1` and `s2` contain all stack elements, so the algorithm checks `s1` and `s2` size to return if the queue is empty.\n\n<iframe src=\"https://leetcode.com/playground/hswBjmcT/shared\" frameBorder=\"0\" name=\"hswBjmcT\" width=\"100%\" height=\"139\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$.\n* Space complexity : $O(1)$.\n\n\n#### Peek\n\nThe `front` element is kept in constant memory and is modified when we push an element. When `s2` is not empty, front element is positioned on the top of `s2`\n\n<iframe src=\"https://leetcode.com/playground/xmLcBbmw/shared\" frameBorder=\"0\" name=\"xmLcBbmw\" width=\"100%\" height=\"173\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(1)$. The `front` element was either previously calculated or returned as a top element of stack `s2`. Therefore complexity is $O(1)$\n* Space complexity : $O(1)$.",
    "solution_code_python": "\t\t\t\n\nclass MyQueue:\n  def __init__(self):\n    self.input = []\n    self.output = []\n\n  def push(self, x: int) -> None:\n    self.input.append(x)\n\n  def pop(self) -> int:\n    self.peek()\n    return self.output.pop()\n\n  def peek(self) -> int:\n    if not self.output:\n      while self.input:\n        self.output.append(self.input.pop())\n    return self.output[-1]\n\n  def empty(self) -> bool:\n    return not self.input and not self.output",
    "solution_code_java": "\t\t\t\n\nclass MyQueue {\n  public void push(int x) {\n    input.push(x);\n  }\n\n  public int pop() {\n    peek();\n    return output.pop();\n  }\n\n  public int peek() {\n    if (output.isEmpty())\n      while (!input.isEmpty())\n        output.push(input.pop());\n    return output.peek();\n  }\n\n  public boolean empty() {\n    return input.isEmpty() && output.isEmpty();\n  }\n\n  private Deque<Integer> input = new ArrayDeque<>();\n  private Deque<Integer> output = new ArrayDeque<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyQueue {\n public:\n  void push(int x) {\n    input.push(x);\n  }\n\n  int pop() {\n    peek();\n    const int val = output.top();\n    output.pop();\n    return val;\n  }\n\n  int peek() {\n    if (output.empty())\n      while (!input.empty())\n        output.push(input.top()), input.pop();\n    return output.top();\n  }\n\n  bool empty() {\n    return input.empty() && output.empty();\n  }\n\n private:\n  stack<int> input;\n  stack<int> output;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/232.html",
    "category": "Algorithms",
    "acceptance_rate": 67.8904266772194,
    "topics": [
      "Stack",
      "Design",
      "Queue"
    ],
    "hints": [],
    "likes": 8085,
    "dislikes": 461,
    "similar_questions": "[{\"title\": \"Implement Stack using Queues\", \"titleSlug\": \"implement-stack-using-queues\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1178597, \"totalSubmissionRaw\": 1736033, \"acRate\": \"67.9%\"}",
    "title_pt": "Implementar Fila usando Pilhas",
    "description_pt": "<p>Implemente uma fila first in first out (FIFO) usando apenas duas pilhas. A fila implementada deve suportar todas as funções de uma fila normal (<code>push</code>, <code>peek</code>, <code>pop</code>, e <code>empty</code>).</p>\n\n<p>Implemente a classe <code>MyQueue</code>:</p>\n\n<ul>\n\t<li><code>void push(int x)</code> Adiciona o elemento x à parte de trás da fila.</li>\n\t<li><code>int pop()</code> Remove o elemento da frente da fila e o retorna.</li>\n\t<li><code>int peek()</code> Retorna o elemento da frente da fila.</li>\n\t<li><code>boolean empty()</code> Retorna <code>true</code> se a fila estiver vazia, <code>false</code> caso contrário.</li>\n</ul>\n\n<p><strong>Notas:</strong></p>\n\n<ul>\n\t<li>Você deve usar <strong>apenas</strong> operações padrão de uma pilha, o que significa que somente as operações <code>push to top</code>, <code>peek/pop from top</code>, <code>size</code>, e <code>is empty</code> são válidas.</li>\n\t<li>Dependendo da sua linguagem, a pilha pode não ser suportada nativamente. Você pode simular uma pilha usando uma lista ou deque (fila de duas extremidades) contanto que use apenas as operações padrão de uma pilha.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyQueue&quot;, &quot;push&quot;, &quot;push&quot;, &quot;peek&quot;, &quot;pop&quot;, &quot;empty&quot;]\n[[], [1], [2], [], [], []]\n<strong>Saída</strong>\n[null, null, null, 1, 1, false]\n\n<strong>Explicação</strong>\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x &lt;= 9</code></li>\n\t<li>No máximo <code>100</code>&nbsp;chamadas serão feitas para <code>push</code>, <code>pop</code>, <code>peek</code>, e <code>empty</code>.</li>\n\t<li>Todas as chamadas para <code>pop</code> e <code>peek</code> são válidas.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue implementar a fila de modo que cada operação tenha complexidade de tempo <strong><a href=\"https://en.wikipedia.org/wiki/Amortized_analysis\" target=\"_blank\">amortizada</a></strong> <code>O(1)</code>? Em outras palavras, realizar <code>n</code> operações levará, no total, <code>O(n)</code> de tempo, mesmo que uma dessas operações possa levar mais tempo.</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "233",
    "paidOnly": false,
    "title": "Number of Digit One",
    "titleSlug": "number-of-digit-one",
    "url": "https://leetcode.com/problems/number-of-digit-one",
    "description_url": "https://leetcode.com/problems/number-of-digit-one/description/",
    "description": "<p>Given an integer <code>n</code>, count <em>the total number of digit </em><code>1</code><em> appearing in all non-negative integers less than or equal to</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 13\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-digit-one/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n### Approach #1 Brute force [Time Limit Exceeded]\n\n**Intuition**\n\nDo as directed in question.\n\n**Algorithm**\n\n* Iterate over $$i$$ from $$1$$ to $$n$$:\n  + Convert $$i$$ to string and count $$\\text{'1'}$$ in each integer string\n  + Add count of $$\\text{'1'}$$ in each string to the sum, say $$countr$$\n\n\n<iframe src=\"https://leetcode.com/playground/VwAzPgne/shared\" frameBorder=\"0\" name=\"VwAzPgne\" width=\"100%\" height=\"207\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n*log_{10}(n))$$.\n  + We iterate from $$1$$ to $$n$$\n  + In each iteration, we convert integer to string and count '1' in string which takes linear time in number of digits in $$i$$, which is $$log_{10}(n)$$.\n\n* Space complexity: $$O(log_{10}(n))$$ Extra space for the countr and the converted string $$\\text{str}$$.\n\n---\n### Approach #2 Solve it mathematically [Accepted]\n\n**Intuition**\n\nIn Approach #1, we manually calculated the number of all the $$'1'$$s in the digits, but this is very slow. Hence, we need a way to find a pattern in the way $$'1'$$s (or for that matter any digit) appears in the numbers. We could then use the pattern to formulate the answer.\n\nConsider the $$1$$s in $$\\text{ones}$$ place , $$\\text{tens}$$ place, $$\\text{hundreds}$$ place and so on... An analysis\nhas been performed in the following figure.\n\n![Number of digit one](../Figures/233/number_of_digit_one.png){:width=\"800px\"}\n\n\nFrom the figure, we can see that from digit '1' at $$\\text{ones}$$ place repeat in group of 1 after interval of $$10$$. Similarly, '1' at $$\\text{tens}$$ place repeat in group of 10 after interval of $$100$$.\nThis can be formulated as $$(n/(i*10))*i$$.\n\nAlso, notice that if the digit at $$\\text{tens}$$ place is $$\\text{'1'}$$, then the number of terms with $$\\text{'1's}$$  is increased by $$x+1$$, if the number is say $$\\text{\"ab1x\"}$$. As if digits at $$\\text{tens}$$ place is greater than $$1$$, then all the $$10$$ occurances of numbers with $$'1'$$ at $$\\text{tens}$$ place have taken place, hence, we add $$10$$.\nThis is formluated as $${\\min(\\max((\\text{n mod (i*10)} )-i+1,0),i)}$$.\n\nLets take an example, say $$n= 1234$$.\n\nNo of $$\\text{'1'}$$ in $$\\text{ones}$$ place = $$1234/10$$(corresponding to 1,11,21,...1221) + $$\\min(4,1)$$(corresponding to 1231) =$$124$$\n\nNo of $$\\text{'1'}$$ in $$\\text{tens}$$ place = $$(1234/100)*10$$(corresponding to 10,11,12,...,110,111,...1919) +$$\\min(21,10)$$(corresponding to 1210,1211,...1219)=$$130$$\n\nNo of $$\\text{'1'}$$ in $$\\text{hundreds}$$ place = $$(1234/1000)*100$$(corresponding to 100,101,12,...,199) +$$\\min(135,100)$$(corresponding to 1100,1101...1199)=$$200$$\n\nNo of $$\\text{'1'}$$ in $$\\text{thousands}$$ place = $$(1234/10000)*10000$$ +$$\\min(235,1000)$$(corresponding to 1000,1001,...1234)=$$235$$\n\nTherefore, Total = $$124+130+200+235 = 689$$.\n\nHerein, one formula has been devised, but many other formulae can be devised for faster implementations, but the essence and complexity remains the same. The users are encouraged to try to devise their own version of solution using the mathematical concepts.\n\n**Algorithm**\n\n* Iterate over $$i$$ from $$1$$ to $$n$$ incrementing by $$10$$ each time:\n\n    - Add  $$(n/(i*10))*i$$ to $$\\text{countr}$$ representing the repetition of groups of $$i$$ sizes after each $$(i*10)$$ interval.\n\n    - Add $${\\min(\\max((\\text{n mod (i*10)} )-i+1,0),i)}$$ to $$\\text{countr}$$ representing the additional digits dependant on the digit in $$i$$th place as described in intuition.\n\n<iframe src=\"https://leetcode.com/playground/QVzpgtNB/shared\" frameBorder=\"0\" name=\"QVzpgtNB\" width=\"100%\" height=\"207\"></iframe>\n\n**Complexity analysis**\n\n* Time complexity: $$O(log_{10}(n))$$.\n\n  + No of iterations equal to the number of digits in n which is $$log_{10}(n)$$\n\n* Space complexity: $$O(1)$$ space required.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countDigitOne(self, n: int) -> int:\n    ans = 0\n\n    pow10 = 1\n    while pow10 <= n:\n      divisor = pow10 * 10\n      quotient = n // divisor\n      remainder = n % divisor\n      if quotient > 0:\n        ans += quotient * pow10\n      if remainder >= pow10:\n        ans += min(remainder - pow10 + 1, pow10)\n      pow10 *= 10\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countDigitOne(int n) {\n    int ans = 0;\n\n    for (long pow10 = 1; pow10 <= n; pow10 *= 10) {\n      final long divisor = pow10 * 10;\n      final int quotient = (int) (n / divisor);\n      final int remainder = (int) (n % divisor);\n      if (quotient > 0)\n        ans += quotient * pow10;\n      if (remainder >= pow10)\n        ans += Math.min(remainder - pow10 + 1, pow10);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countDigitOne(int n) {\n    int ans = 0;\n\n    for (long pow10 = 1; pow10 <= n; pow10 *= 10) {\n      const long divisor = pow10 * 10;\n      const int quotient = n / divisor;\n      const int remainder = n % divisor;\n      if (quotient > 0)\n        ans += quotient * pow10;\n      if (remainder >= pow10)\n        ans += min(remainder - pow10 + 1, pow10);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/233.html",
    "category": "Algorithms",
    "acceptance_rate": 35.86785180523873,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Recursion"
    ],
    "hints": [
      "Beware of overflow."
    ],
    "likes": 1678,
    "dislikes": 1511,
    "similar_questions": "[{\"title\": \"Factorial Trailing Zeroes\", \"titleSlug\": \"factorial-trailing-zeroes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Digit Count in Range\", \"titleSlug\": \"digit-count-in-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"114K\", \"totalSubmission\": \"317.8K\", \"totalAcceptedRaw\": 113997, \"totalSubmissionRaw\": 317825, \"acRate\": \"35.9%\"}",
    "title_pt": "Número de Dígito Um",
    "description_pt": "<p>Dado um inteiro <code>n</code>, conte <em>o número total do dígito </em><code>1</code><em> que aparece em todos os inteiros não negativos menores ou iguais a</em> <code>n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 13\n<strong>Saída:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Tome cuidado com overflow."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "234",
    "paidOnly": false,
    "title": "Palindrome Linked List",
    "titleSlug": "palindrome-linked-list",
    "url": "https://leetcode.com/problems/palindrome-linked-list",
    "description_url": "https://leetcode.com/problems/palindrome-linked-list/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list, return <code>true</code><em> if it is a </em><span data-keyword=\"palindrome-sequence\"><em>palindrome</em></span><em> or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg\" style=\"width: 422px; height: 62px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,2,1]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg\" style=\"width: 182px; height: 62px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you do it in <code>O(n)</code> time and <code>O(1)</code> space?",
    "solution_url": "https://leetcode.com/problems/palindrome-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPalindrome(self, head: ListNode) -> bool:\n    def reverseList(head: ListNode) -> ListNode:\n      prev = None\n      curr = head\n\n      while curr:\n        next = curr.next\n        curr.next = prev\n        prev = curr\n        curr = next\n\n      return prev\n\n    slow = head\n    fast = head\n\n    while fast and fast.next:\n      slow = slow.next\n      fast = fast.next.next\n\n    if fast:\n      slow = slow.next\n    slow = reverseList(slow)\n\n    while slow:\n      if slow.val != head.val:\n        return False\n      slow = slow.next\n      head = head.next\n\n    return True",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPalindrome(ListNode head) {\n    ListNode slow = head;\n    ListNode fast = head;\n\n    while (fast != null && fast.next != null) {\n      slow = slow.next;\n      fast = fast.next.next;\n    }\n\n    if (fast != null)\n      slow = slow.next;\n    slow = reverseList(slow);\n\n    while (slow != null) {\n      if (slow.val != head.val)\n        return false;\n      slow = slow.next;\n      head = head.next;\n    }\n\n    return true;\n  }\n\n  private ListNode reverseList(ListNode head) {\n    ListNode prev = null;\n\n    while (head != null) {\n      ListNode next = head.next;\n      head.next = prev;\n      prev = head;\n      head = next;\n    }\n\n    return prev;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPalindrome(ListNode* head) {\n    ListNode* slow = head;\n    ListNode* fast = head;\n\n    while (fast && fast->next) {\n      slow = slow->next;\n      fast = fast->next->next;\n    }\n\n    if (fast != nullptr)\n      slow = slow->next;\n    slow = reverseList(slow);\n\n    while (slow) {\n      if (slow->val != head->val)\n        return false;\n      slow = slow->next;\n      head = head->next;\n    }\n\n    return true;\n  }\n\n private:\n  ListNode* reverseList(ListNode* head) {\n    ListNode* prev = nullptr;\n\n    while (head) {\n      ListNode* next = head->next;\n      head->next = prev;\n      prev = head;\n      head = next;\n    }\n\n    return prev;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/234.html",
    "category": "Algorithms",
    "acceptance_rate": 55.61585915233124,
    "topics": [
      "Linked List",
      "Two Pointers",
      "Stack",
      "Recursion"
    ],
    "hints": [],
    "likes": 17323,
    "dislikes": 931,
    "similar_questions": "[{\"title\": \"Palindrome Number\", \"titleSlug\": \"palindrome-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome\", \"titleSlug\": \"valid-palindrome\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse Linked List\", \"titleSlug\": \"reverse-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Twin Sum of a Linked List\", \"titleSlug\": \"maximum-twin-sum-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.4M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 2387634, \"totalSubmissionRaw\": 4293084, \"acRate\": \"55.6%\"}",
    "title_pt": "Lista Encadeada Palíndroma",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada simplesmente ligada, retorne <code>true</code><em> se ela for um </em><span data-keyword=\"palindrome-sequence\"><em>palíndromo</em></span><em> ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg\" style=\"width: 422px; height: 62px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,2,1]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg\" style=\"width: 182px; height: 62px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[1, 10<sup>5</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria fazer isso em <code>O(n)</code> de tempo e <code>O(1)</code> de espaço?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "235",
    "paidOnly": false,
    "title": "Lowest Common Ancestor of a Binary Search Tree",
    "titleSlug": "lowest-common-ancestor-of-a-binary-search-tree",
    "url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree",
    "description_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/",
    "description": "<p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).&rdquo;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [2,1], p = 2, q = 1\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>All <code>Node.val</code> are <strong>unique</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> and <code>q</code> will exist in the BST.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n    if root.val > max(p.val, q.val):\n      return self.lowestCommonAncestor(root.left, p, q)\n    if root.val < min(p.val, q.val):\n      return self.lowestCommonAncestor(root.right, p, q)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n    if (root.val > Math.max(p.val, q.val))\n      return lowestCommonAncestor(root.left, p, q);\n    if (root.val < Math.min(p.val, q.val))\n      return lowestCommonAncestor(root.right, p, q);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n    if (root->val > max(p->val, q->val))\n      return lowestCommonAncestor(root->left, p, q);\n    if (root->val < min(p->val, q->val))\n      return lowestCommonAncestor(root->right, p, q);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/235.html",
    "category": "Algorithms",
    "acceptance_rate": 68.01259855764786,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 11667,
    "dislikes": 336,
    "similar_questions": "[{\"title\": \"Lowest Common Ancestor of a Binary Tree\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Common Region\", \"titleSlug\": \"smallest-common-region\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree II\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree III\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree IV\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"2.8M\", \"totalAcceptedRaw\": 1876054, \"totalSubmissionRaw\": 2758398, \"acRate\": \"68.0%\"}",
    "title_pt": "Menor Ancestral Comum de uma Árvore Binária de Busca",
    "description_pt": "<p>Dada uma árvore binária de busca (BST), encontre o nó ancestral comum mais baixo (LCA) de dois nós dados na BST.</p>\n\n<p>De acordo com a <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definição de LCA na Wikipedia</a>: &ldquo;O ancestral comum mais baixo é definido entre dois nós <code>p</code> e <code>q</code> como o nó mais baixo em <code>T</code> que tem tanto <code>p</code> quanto <code>q</code> como descendentes (onde permitimos que <strong>um nó seja descendente de si mesmo</strong>).&rdquo;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Entrada:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O LCA dos nós 2 e 8 é 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Entrada:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> O LCA dos nós 2 e 4 é 2, já que um nó pode ser descendente de si mesmo de acordo com a definição de LCA.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [2,1], p = 2, q = 1\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>Todos os <code>Node.val</code> são <strong>únicos</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> e <code>q</code> existirão na BST.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "236",
    "paidOnly": false,
    "title": "Lowest Common Ancestor of a Binary Tree",
    "titleSlug": "lowest-common-ancestor-of-a-binary-tree",
    "url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree",
    "description_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/",
    "description": "<p>Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definition of LCA on Wikipedia</a>: &ldquo;The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <b>a node to be a descendant of itself</b>).&rdquo;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The LCA of nodes 5 and 1 is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1,2], p = 1, q = 2\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>All <code>Node.val</code> are <strong>unique</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> and <code>q</code> will exist in the tree.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n    if not root or root == p or root == q:\n      return root\n\n    l = self.lowestCommonAncestor(root.left, p, q)\n    r = self.lowestCommonAncestor(root.right, p, q)\n\n    if l and r:\n      return root\n    return l or r",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {\n    if (root == null || root == p || root == q)\n      return root;\n\n    TreeNode l = lowestCommonAncestor(root.left, p, q);\n    TreeNode r = lowestCommonAncestor(root.right, p, q);\n\n    if (l != null && r != null)\n      return root;\n    return l == null ? r : l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n    if (root == nullptr || root == p || root == q)\n      return root;\n\n    TreeNode* l = lowestCommonAncestor(root->left, p, q);\n    TreeNode* r = lowestCommonAncestor(root->right, p, q);\n\n    if (l && r)\n      return root;\n    return l ? l : r;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/236.html",
    "category": "Algorithms",
    "acceptance_rate": 66.40643172467267,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 17557,
    "dislikes": 462,
    "similar_questions": "[{\"title\": \"Lowest Common Ancestor of a Binary Search Tree\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Common Region\", \"titleSlug\": \"smallest-common-region\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Players With Zero or One Losses\", \"titleSlug\": \"find-players-with-zero-or-one-losses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree II\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree III\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Lowest Common Ancestor of a Binary Tree IV\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Step-By-Step Directions From a Binary Tree Node to Another\", \"titleSlug\": \"step-by-step-directions-from-a-binary-tree-node-to-another\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Cycle Length Queries in a Tree\", \"titleSlug\": \"cycle-length-queries-in-a-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 2124012, \"totalSubmissionRaw\": 3198508, \"acRate\": \"66.4%\"}",
    "title_pt": "Ancestral Comum Mais Baixo de uma Árvore Binária",
    "description_pt": "<p>Dada uma árvore binária, encontre o ancestral comum mais baixo (LCA) de dois nós dados na árvore.</p>\n\n<p>De acordo com a <a href=\"https://en.wikipedia.org/wiki/Lowest_common_ancestor\" target=\"_blank\">definição de LCA na Wikipedia</a>: &ldquo;O ancestral comum mais baixo é definido entre dois nós <code>p</code> e <code>q</code> como o nó mais baixo em <code>T</code> que tem tanto <code>p</code> quanto <code>q</code> como descendentes (onde permitimos que <b>um nó seja descendente de si mesmo</b>).&rdquo;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> O LCA dos nós 5 e 1 é 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/12/14/binarytree.png\" style=\"width: 200px; height: 190px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> O LCA dos nós 5 e 4 é 5, pois um nó pode ser descendente de si mesmo de acordo com a definição de LCA.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,2], p = 1, q = 2\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[2, 10<sup>5</sup>]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li>Todos os <code>Node.val</code> são <strong>únicos</strong>.</li>\n\t<li><code>p != q</code></li>\n\t<li><code>p</code> e <code>q</code> existirão na árvore.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "237",
    "paidOnly": false,
    "title": "Delete Node in a Linked List",
    "titleSlug": "delete-node-in-a-linked-list",
    "url": "https://leetcode.com/problems/delete-node-in-a-linked-list",
    "description_url": "https://leetcode.com/problems/delete-node-in-a-linked-list/description/",
    "description": "<p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p>\n\n<p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p>\n\n<p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p>\n\n<p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p>\n\n<ul>\n\t<li>The value of the given node should not exist in the linked list.</li>\n\t<li>The number of nodes in the linked list should decrease by one.</li>\n\t<li>All the values before <code>node</code> should be in the same order.</li>\n\t<li>All the values after <code>node</code> should be in the same order.</li>\n</ul>\n\n<p><strong>Custom testing:</strong></p>\n\n<ul>\n\t<li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li>\n\t<li>We will build the linked list and pass the node to your function.</li>\n\t<li>The output will be the entire list after calling your function.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node1.jpg\" style=\"width: 400px; height: 286px;\" />\n<pre>\n<strong>Input:</strong> head = [4,5,1,9], node = 5\n<strong>Output:</strong> [4,1,9]\n<strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node2.jpg\" style=\"width: 400px; height: 315px;\" />\n<pre>\n<strong>Input:</strong> head = [4,5,1,9], node = 1\n<strong>Output:</strong> [4,5,9]\n<strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li>The value of each node in the list is <strong>unique</strong>.</li>\n\t<li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/delete-node-in-a-linked-list/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nTo delete a node from a linked list, we typically redirect the previous node's `next` pointer to the subsequent node of the one being deleted. For example, to remove node 3 from a linked list, we would adjust node 2's `next` pointer to reference node 4 directly. This effectively excludes node 3 from the traversal path, rendering it inaccessible during iteration, and thus, it is considered deleted.\n\n![initial_linkedlist](../Documents/237/237-Page-1.svg)\n\n![changing_pointers](../Documents/237/237-Page-2.svg)\n\n<br />\n\nHowever, a challenge arises when we cannot access the previous node, as is the case in this specific problem. Since we can only traverse forward from the node to be deleted, the conventional deletion method is not feasible.\n\n**Key Observations:** \n- We've been presented with a scenario where we can't access the entire linked list structure, forcing us to devise a strategy that works within those limitations.\n- This problem goes beyond rote memorization of DSA techniques. **It emphasizes the importance of creative thinking under limitations.** It highlights the assessment of the candidate's problem-solving approach.\n\n---\n\n### Approach: Data Overwriting\n\n#### Intuition\n\nTo circumvent this limitation, we can employ an alternative strategy. By comparing the original linked list with the desired outcome post-deletion, we notice that the nodes following the target node appear to shift one position to the left. \n\n![initial_linkedlist](../Documents/237/237-Page-3.svg)\n\n\n![after_deletion](../Documents/237/237-Page-4.svg)\n\n<br />\n\n\nWe can replicate this effect by copying the data from each subsequent node into its predecessor, starting from the node to be deleted, and then unlinking the last node.\n\n![overwrite_linkedlist](../Documents/237/237-Page-5.svg)\n\n\n![after_overwrite](../Documents/237/237-Page-6.svg)\n\n<br />\n\nThis approach can be further optimized. Instead of shifting the data of all subsequent nodes, we only need to overwrite the data of the node to be deleted with that of its immediate successor. Subsequently, we update the `next` pointer of the node to be deleted to point to the successor's next node. This effectively removes the successor node, achieving the desired result with minimal operations.\n\n![overwrite_linkedlist](../Documents/237/237-Page-7.svg)\n\n\n![after_overwrite_1_node](../Documents/237/237-Page-8.svg)\n\nLet's take a simpler example to understand this approach.    \nImagine the linked list as a train with connected cars (nodes). We want to remove a specific car (target node), but the conductor (you) can only access the current car and not the engine (head).\nBy shifting all passengers from current car (\"overwriting\" the data of the current node) with the data from the next car, and then connecting the current car to the car after the next (skipping the unwanted car), we achieve the deletion effect.\n\n**Note:** This method will not work if we need to delete the last node of the linked list since there is no immediate successor. However, the problem description explicitly states that the node to be deleted is not the tail node in the list.\n\n<br />\n\n#### Algorithm\n\n1. Copy the data from the successor node into the current node to be deleted.\n2. Update the `next` pointer of the current node to reference the `next` pointer of the successor node.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/WZX53viv/shared\" frameBorder=\"0\" width=\"100%\" height=\"208\" name=\"WZX53viv\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $O(1)$\n\n    - The method involves a constant number of operations: updating the data of the current node and altering its `next` pointer. Each of these operations requires a fixed amount of time, irrespective of the size of the linked list.\n    \n* Space Complexity: $O(1)$\n\n    - This deletion technique does not necessitate any extra memory allocation, as it operates directly on the existing nodes without creating additional data structures.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def deleteNode(self, node):\n    node.val = node.next.val\n    node.next = node.next.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void deleteNode(ListNode node) {\n    node.val = node.next.val;\n    node.next = node.next.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void deleteNode(ListNode* node) {\n    node->val = node->next->val;\n    node->next = node->next->next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/237.html",
    "category": "Algorithms",
    "acceptance_rate": 82.09646415336253,
    "topics": [
      "Linked List"
    ],
    "hints": [],
    "likes": 5662,
    "dislikes": 1687,
    "similar_questions": "[{\"title\": \"Remove Linked List Elements\", \"titleSlug\": \"remove-linked-list-elements\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Remove Nodes From Linked List\", \"titleSlug\": \"remove-nodes-from-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete Nodes From Linked List Present in Array\", \"titleSlug\": \"delete-nodes-from-linked-list-present-in-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1699367, \"totalSubmissionRaw\": 2069965, \"acRate\": \"82.1%\"}",
    "title_pt": "Remover Nó em uma Lista Encadeada",
    "description_pt": "<p>Há uma lista encadeada simplesmente ligada <code>head</code> e queremos excluir um nó <code>node</code> nela.</p>\n\n<p>Você recebe o nó a ser excluído <code>node</code>. Você <strong>não terá acesso</strong> ao primeiro nó de <code>head</code>.</p>\n\n<p>Todos os valores da lista encadeada são <strong>únicos</strong>, e é garantido que o nó fornecido <code>node</code> não é o último nó da lista encadeada.</p>\n\n<p>Exclua o nó fornecido. Note que, ao excluir o nó, não queremos dizer removê-lo da memória. Queremos dizer:</p>\n\n<ul>\n\t<li>O valor do nó fornecido não deve existir na lista encadeada.</li>\n\t<li>O número de nós na lista encadeada deve diminuir em um.</li>\n\t<li>Todos os valores antes de <code>node</code> devem estar na mesma ordem.</li>\n\t<li>Todos os valores após <code>node</code> devem estar na mesma ordem.</li>\n</ul>\n\n<p><strong>Teste personalizado:</strong></p>\n\n<ul>\n\t<li>Para a entrada, você deve fornecer a lista encadeada completa <code>head</code> e o nó a ser fornecido <code>node</code>. <code>node</code> não deve ser o último nó da lista e deve ser um nó real na lista.</li>\n\t<li>Nós construiremos a lista encadeada e passaremos o nó para sua função.</li>\n\t<li>A saída será a lista completa após chamar sua função.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node1.jpg\" style=\"width: 400px; height: 286px;\" />\n<pre>\n<strong>Entrada:</strong> head = [4,5,1,9], node = 5\n<strong>Saída:</strong> [4,1,9]\n<strong>Explicação: </strong>Você recebe o segundo nó com valor 5, a lista encadeada deve se tornar 4 -&gt; 1 -&gt; 9 após chamar sua função.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/node2.jpg\" style=\"width: 400px; height: 315px;\" />\n<pre>\n<strong>Entrada:</strong> head = [4,5,1,9], node = 1\n<strong>Saída:</strong> [4,5,9]\n<strong>Explicação: </strong>Você recebe o terceiro nó com valor 1, a lista encadeada deve se tornar 4 -&gt; 5 -&gt; 9 após chamar sua função.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista fornecida está no intervalo <code>[2, 1000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li>O valor de cada nó na lista é <strong>único</strong>.</li>\n\t<li>O <code>node</code> a ser excluído está <strong>na lista</strong> e <strong>não é</strong> um nó de cauda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "238",
    "paidOnly": false,
    "title": "Product of Array Except Self",
    "titleSlug": "product-of-array-except-self",
    "url": "https://leetcode.com/problems/product-of-array-except-self",
    "description_url": "https://leetcode.com/problems/product-of-array-except-self/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p>\n\n<p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p>\n\n<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> [24,12,8,6]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [-1,1,0,-3,3]\n<strong>Output:</strong> [0,0,9,0,0]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-30 &lt;= nums[i] &lt;= 30</code></li>\n\t<li>The input is generated such that <code>answer[i]</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)</code>&nbsp;extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>\n",
    "solution_url": "https://leetcode.com/problems/product-of-array-except-self/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def productExceptSelf(self, nums: List[int]) -> List[int]:\n    n = len(nums)\n    prefix = [1] * n  # Prefix product\n    suffix = [1] * n  # Suffix product\n\n    for i in range(1, n):\n      prefix[i] = prefix[i - 1] * nums[i - 1]\n\n    for i in reversed(range(n - 1)):\n      suffix[i] = suffix[i + 1] * nums[i + 1]\n\n    return [prefix[i] * suffix[i] for i in range(n)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] productExceptSelf(int[] nums) {\n    final int n = nums.length;\n    int[] ans = new int[n];    // Can also use nums as the ans array\n    int[] prefix = new int[n]; // Prefix product\n    int[] suffix = new int[n]; // Suffix product\n\n    prefix[0] = 1;\n    for (int i = 1; i < n; ++i)\n      prefix[i] = prefix[i - 1] * nums[i - 1];\n\n    suffix[n - 1] = 1;\n    for (int i = n - 2; i >= 0; --i)\n      suffix[i] = suffix[i + 1] * nums[i + 1];\n\n    for (int i = 0; i < n; ++i)\n      ans[i] = prefix[i] * suffix[i];\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> productExceptSelf(vector<int>& nums) {\n    const int n = nums.size();\n    vector<int> ans(n);        // Can also use nums as the ans array\n    vector<int> prefix(n, 1);  // Prefix product\n    vector<int> suffix(n, 1);  // Suffix product\n\n    for (int i = 1; i < n; ++i)\n      prefix[i] = prefix[i - 1] * nums[i - 1];\n\n    for (int i = n - 2; i >= 0; --i)\n      suffix[i] = suffix[i + 1] * nums[i + 1];\n\n    for (int i = 0; i < n; ++i)\n      ans[i] = prefix[i] * suffix[i];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/238.html",
    "category": "Algorithms",
    "acceptance_rate": 67.63905709358838,
    "topics": [
      "Array",
      "Prefix Sum"
    ],
    "hints": [
      "Think how you can efficiently utilize prefix and suffix products to calculate the product of all elements except self for each index. Can you pre-compute the prefix and suffix products in linear time to avoid redundant calculations?",
      "Can you minimize additional space usage by reusing memory or modifying the input array to store intermediate results?"
    ],
    "likes": 24085,
    "dislikes": 1550,
    "similar_questions": "[{\"title\": \"Trapping Rain Water\", \"titleSlug\": \"trapping-rain-water\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Product Subarray\", \"titleSlug\": \"maximum-product-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint House II\", \"titleSlug\": \"paint-house-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Difference in Sums After Removal of Elements\", \"titleSlug\": \"minimum-difference-in-sums-after-removal-of-elements\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Construct Product Matrix\", \"titleSlug\": \"construct-product-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Sum of Array Product of Magical Sequences\", \"titleSlug\": \"find-sum-of-array-product-of-magical-sequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.6M\", \"totalSubmission\": \"5.3M\", \"totalAcceptedRaw\": 3594518, \"totalSubmissionRaw\": 5314267, \"acRate\": \"67.6%\"}",
    "title_pt": "Produto de um Array Exceto o Próprio",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>um array</em> <code>answer</code> <em>tal que</em> <code>answer[i]</code> <em>seja igual ao produto de todos os elementos de</em> <code>nums</code> <em>exceto</em> <code>nums[i]</code>.</p>\n\n<p>O produto de qualquer prefixo ou sufixo de <code>nums</code> é <strong>garantido</strong> caber em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>Você deve escrever um algoritmo que execute em&nbsp;<code>O(n)</code>&nbsp;tempo e sem usar a operação de divisão.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,3,4]\n<strong>Saída:</strong> [24,12,8,6]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [-1,1,0,-3,3]\n<strong>Saída:</strong> [0,0,9,0,0]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-30 &lt;= nums[i] &lt;= 30</code></li>\n\t<li>A entrada é gerada de forma que <code>answer[i]</code> é <strong>garantido</strong> caber em um inteiro de <strong>32 bits</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong>&nbsp;Você consegue resolver o problema com complexidade de espaço extra <code>O(1)</code>? (O array de saída <strong>não</strong> conta como espaço extra para a análise de complexidade de espaço.)</p>",
    "hints_pt": [
      "Dica 1: Pense em como você pode utilizar de forma eficiente os produtos de prefixo e sufixo para calcular o produto de todos os elementos exceto o próprio para cada índice. Você consegue pré-computar os produtos de prefixo e sufixo em tempo linear para evitar cálculos redundantes?",
      "Dica 2: Você consegue minimizar o uso de espaço adicional reutilizando memória ou modificando o array de entrada para armazenar resultados intermediários?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "239",
    "paidOnly": false,
    "title": "Sliding Window Maximum",
    "titleSlug": "sliding-window-maximum",
    "url": "https://leetcode.com/problems/sliding-window-maximum",
    "description_url": "https://leetcode.com/problems/sliding-window-maximum/description/",
    "description": "<p>You are given an array of integers&nbsp;<code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>\n\n<p>Return <em>the max sliding window</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3\n<strong>Output:</strong> [3,3,5,5,6,7]\n<strong>Explanation:</strong> \nWindow position                Max\n---------------               -----\n[1  3  -1] -3  5  3  6  7       <strong>3</strong>\n 1 [3  -1  -3] 5  3  6  7       <strong>3</strong>\n 1  3 [-1  -3  5] 3  6  7      <strong> 5</strong>\n 1  3  -1 [-3  5  3] 6  7       <strong>5</strong>\n 1  3  -1  -3 [5  3  6] 7       <strong>6</strong>\n 1  3  -1  -3  5 [3  6  7]      <strong>7</strong>\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1], k = 1\n<strong>Output:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= nums.length</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sliding-window-maximum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n    ans = []\n    q = deque()  # Max queue\n\n    for i, num in enumerate(nums):\n      while q and q[-1] < num:\n        q.pop()\n      q.append(num)\n      if i >= k and nums[i - k] == q[0]:  # Out of bound\n        q.popleft()\n      if i >= k - 1:\n        ans.append(q[0])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] maxSlidingWindow(int[] nums, int k) {\n    int[] ans = new int[nums.length - k + 1];\n    Deque<Integer> q = new ArrayDeque<>(); // Max queue\n\n    for (int i = 0; i < nums.length; ++i) {\n      while (!q.isEmpty() && q.peekLast() < nums[i])\n        q.pollLast();\n      q.offerLast(nums[i]);\n      if (i >= k && nums[i - k] == q.peekFirst()) // Out of bound\n        q.pollFirst();\n      if (i >= k - 1)\n        ans[i - k + 1] = q.peekFirst();\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> maxSlidingWindow(vector<int>& nums, int k) {\n    vector<int> ans;\n    deque<int> q;  // Max queue\n\n    for (int i = 0; i < nums.size(); ++i) {\n      while (!q.empty() && q.back() < nums[i])\n        q.pop_back();\n      q.push_back(nums[i]);\n      if (i >= k && nums[i - k] == q.front())  // Out of bound\n        q.pop_front();\n      if (i >= k - 1)\n        ans.push_back(q.front());\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/239.html",
    "category": "Algorithms",
    "acceptance_rate": 47.48051353342805,
    "topics": [
      "Array",
      "Queue",
      "Sliding Window",
      "Heap (Priority Queue)",
      "Monotonic Queue"
    ],
    "hints": [
      "How about using a data structure such as deque (double-ended queue)?",
      "The queue size need not be the same as the window’s size.",
      "Remove redundant elements and the queue should store only elements that need to be considered."
    ],
    "likes": 19126,
    "dislikes": 749,
    "similar_questions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Min Stack\", \"titleSlug\": \"min-stack\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Substring with At Most Two Distinct Characters\", \"titleSlug\": \"longest-substring-with-at-most-two-distinct-characters\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint House II\", \"titleSlug\": \"paint-house-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Jump Game VI\", \"titleSlug\": \"jump-game-vi\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Robots Within Budget\", \"titleSlug\": \"maximum-number-of-robots-within-budget\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Tastiness of Candy Basket\", \"titleSlug\": \"maximum-tastiness-of-candy-basket\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximal Score After Applying K Operations\", \"titleSlug\": \"maximal-score-after-applying-k-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1302291, \"totalSubmissionRaw\": 2742796, \"acRate\": \"47.5%\"}",
    "title_pt": "Máximo da Janela Deslizante",
    "description_pt": "<p>Você recebe um array de inteiros&nbsp;<code>nums</code>; há uma janela deslizante de tamanho <code>k</code> que se move desde a extremidade esquerda do array até a extremidade direita. Você só pode ver os <code>k</code> números dentro da janela. A cada vez, a janela deslizante se move uma posição para a direita.</p>\n\n<p>Retorne <em>o máximo da janela deslizante</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3\n<strong>Saída:</strong> [3,3,5,5,6,7]\n<strong>Explicação:</strong> \nWindow position                Max\n---------------               -----\n[1  3  -1] -3  5  3  6  7       <strong>3</strong>\n 1 [3  -1  -3] 5  3  6  7       <strong>3</strong>\n 1  3 [-1  -3  5] 3  6  7      <strong> 5</strong>\n 1  3  -1 [-3  5  3] 6  7       <strong>5</strong>\n 1  3  -1  -3 [5  3  6] 7       <strong>6</strong>\n 1  3  -1  -3  5 [3  6  7]      <strong>7</strong>\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1], k = 1\n<strong>Saída:</strong> [1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= nums.length</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Que tal usar uma estrutura de dados como deque (fila de extremidades duplas)?",
      "Dica 2: O tamanho da fila não precisa ser o mesmo que o tamanho da janela.",
      "Dica 3: Remova elementos redundantes e a fila deve armazenar apenas os elementos que precisam ser considerados."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "240",
    "paidOnly": false,
    "title": "Search a 2D Matrix II",
    "titleSlug": "search-a-2d-matrix-ii",
    "url": "https://leetcode.com/problems/search-a-2d-matrix-ii",
    "description_url": "https://leetcode.com/problems/search-a-2d-matrix-ii/description/",
    "description": "<p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p>\n\n<ul>\n\t<li>Integers in each row are sorted in ascending from left to right.</li>\n\t<li>Integers in each column are sorted in ascending from top to bottom.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n, m &lt;= 300</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>All the integers in each row are <strong>sorted</strong> in ascending order.</li>\n\t<li>All the integers in each column are <strong>sorted</strong> in ascending order.</li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/search-a-2d-matrix-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n    r = 0\n    c = len(matrix[0]) - 1\n\n    while r < len(matrix) and c >= 0:\n      if matrix[r][c] == target:\n        return True\n      if target < matrix[r][c]:\n        c -= 1\n      else:\n        r += 1\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean searchMatrix(int[][] matrix, int target) {\n    int r = 0;\n    int c = matrix[0].length - 1;\n\n    while (r <= matrix.length && c >= 0) {\n      if (matrix[r][c] == target)\n        return true;\n      if (matrix[r][c] > target)\n        --c;\n      else\n        ++r;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool searchMatrix(vector<vector<int>>& matrix, int target) {\n    int r = 0;\n    int c = matrix[0].size() - 1;\n\n    while (r < matrix.size() && c >= 0) {\n      if (matrix[r][c] == target)\n        return true;\n      if (matrix[r][c] > target)\n        --c;\n      else\n        ++r;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/240.html",
    "category": "Algorithms",
    "acceptance_rate": 54.97620779785905,
    "topics": [
      "Array",
      "Binary Search",
      "Divide and Conquer",
      "Matrix"
    ],
    "hints": [],
    "likes": 12439,
    "dislikes": 218,
    "similar_questions": "[{\"title\": \"Search a 2D Matrix\", \"titleSlug\": \"search-a-2d-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1132003, \"totalSubmissionRaw\": 2059077, \"acRate\": \"55.0%\"}",
    "title_pt": "Buscar em uma Matriz 2D II",
    "description_pt": "<p>Escreva um algoritmo eficiente que pesquise por um valor <code>target</code> em uma matriz inteira <code>m x n</code> <code>matrix</code>. Esta matriz possui as seguintes propriedades:</p>\n\n<ul>\n\t<li>Os inteiros em cada linha são ordenados em ordem crescente da esquerda para a direita.</li>\n\t<li>Os inteiros em cada coluna são ordenados em ordem crescente de cima para baixo.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid2.jpg\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/24/searchgrid.jpg\" style=\"width: 300px; height: 300px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n, m &lt;= 300</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>Todos os inteiros em cada linha são <strong>ordenados</strong> em ordem crescente.</li>\n\t<li>Todos os inteiros em cada coluna são <strong>ordenados</strong> em ordem crescente.</li>\n\t<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "241",
    "paidOnly": false,
    "title": "Different Ways to Add Parentheses",
    "titleSlug": "different-ways-to-add-parentheses",
    "url": "https://leetcode.com/problems/different-ways-to-add-parentheses",
    "description_url": "https://leetcode.com/problems/different-ways-to-add-parentheses/description/",
    "description": "<p>Given a string <code>expression</code> of numbers and operators, return <em>all possible results from computing all the different possible ways to group numbers and operators</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed <code>10<sup>4</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> expression = &quot;2-1-1&quot;\n<strong>Output:</strong> [0,2]\n<strong>Explanation:</strong>\n((2-1)-1) = 0 \n(2-(1-1)) = 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> expression = &quot;2*3-4*5&quot;\n<strong>Output:</strong> [-34,-14,-10,-10,10]\n<strong>Explanation:</strong>\n(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= expression.length &lt;= 20</code></li>\n\t<li><code>expression</code> consists of digits and the operator <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, and <code>&#39;*&#39;</code>.</li>\n\t<li>All the integer values in the input expression are in the range <code>[0, 99]</code>.</li>\n\t<li>The integer values in the input expression do not have a leading <code>&#39;-&#39;</code> or <code>&#39;+&#39;</code> denoting the sign.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/different-ways-to-add-parentheses/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a string `expression` containing:\n1. Numbers from 0 - 99.\n2. Operators (+, -, *)  \n\nOur task is to determine all possible results obtainable by grouping the numbers and operators in various ways.\n    \n---\n\n### Approach 1: Recursion\n\n#### Intuition\n\nWhen we add parentheses to an expression, they group parts of the expression, telling us to evaluate those parts first. To decide where to place these parentheses, we look at each operator in the expression. Each operator offers a chance to split the expression into two smaller parts: everything before the operator and everything after it. These smaller parts are similar to our original problem, so we use recursion to solve them.\n\nWe start by defining our base cases, where we can return a result without further recursion:\n1. If the expression is empty, return an empty list.\n2. If the expression is a single digit, return a list with that number.\n3. If the expression has two characters and the first is a digit, the second must also be a digit. We convert the expression to a number and return it in a list.\n\nFor longer expressions, we find operators to split the expression. We iterate through each character, and when we find an operator, we recursively evaluate the parts before and after it. We store the results of these evaluations in separate lists. Then, we combine the results from the left and right parts using the operator and store the final values in a list.\n\nHere’s a visual example of how a recursion subtree might look:\n\n![](../Figures/241/subtree.png)\n\nBy the end of the process, the `results` list will contain all possible results from grouping the numbers and operators in the expression.\n\n#### Algorithm\n\n- Initialize a list `results` to store the possible outcomes.\n- If the input string is empty, return the empty `results` list.\n- Check if `expression` is a single character:\n  - If so, convert it to an integer and add it to `results`.\n  - Return `results`.\n- Check if `expression` has only two characters and starts with a digit:\n  - If so, convert the entire string to an integer and add it to `results`.\n  - Return `results`.\n- Iterate through each character of `expression`:\n  - Set the current character as `currentChar`.\n  - If `currentChar` is a digit, continue to the next iteration.\n  - Recursively call `diffWaysToCompute` for the left part of `expression` (from indices `0` to `i-1`) and set it to a list `leftResults`.\n  - Recursively call `diffWaysToCompute` for the right part of `expression` (from indices `i+1` to the end) and set it to a list `rightResults`.\n  - Iterate through `leftValue` in `leftResults`:\n    - For each `leftValue`, iterate through each `rightValue` in the `rightResults`:\n      - Initialize a variable `computedResult` to store the result of the current operation.\n      - Perform the operation (addition, subtraction, or multiplication) based on the current character.\n      - Add the `computedResult` to the `results` list.\n- Return `results` as our answer.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/a5L9xDMj/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"a5L9xDMj\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the the length of the input string `expression`.\n\n- Time complexity: $O(n \\cdot 2^n)$\n\n    For each sub-expression, we iterate through the string to identify the operators, which takes $O(n)$ time. However, the key aspect is the recursive combination of results from the left and right sub-expressions. The number of results grows exponentially because each sub-expression produces multiple results, and combining these results takes $O(k \\times l)$, where $k$ and $l$ are the numbers of results from the left and right sub-problems, respectively.\n\n    There were some suggestions to model the number of results using Catalan numbers which we deemed as incorrect. Catalan numbers apply when counting distinct ways to fully parenthesize an expression or structure. In this problem, however, we're not just counting valid ways to split the expression but also calculating and combining all possible results. This introduces exponential growth in the number of possible results, not the polynomial growth typical of Catalan numbers. The number of combinations grows exponentially with the depth of recursive splitting, which means the overall complexity is driven by the exponential growth in results.\n\n    Thus, the time complexity of the algorithm is $O(n \\cdot 2^n)$, where the $O(2^n)$ factor reflects the exponential growth in the number of ways to combine results from sub-expressions.\n\n- Space complexity: $O(2^n)$\n\n    The algorithm stores the intermediate results at each step. Since the total number of results can be equal to the $O(2^n)$, the space complexity of the algorithm is $O(2^n)$.\n\n---\n\n### Approach 2: Memoization\n\n#### Intuition\n\nWhen dealing with complex expressions, we often find ourselves repeating the same calculations. Take the expression `2 + 2 - 2 - 2 - 2`. You could group it in different ways:\n\n1. `((2 + 2) - (2 - 2) - 2)`\n2. `((2 + 2) - 2 - (2 - 2))`\n\nAs you can see, the sub-expression (2 + 2) is evaluated more than once.\n\nTo avoid this, we can store the results of these sub-calculations. This way, if we hit the same sub-problem again, we can use the stored result instead of recalculating it, which speeds things up.\n\nAnother issue with the previous method was that it repeatedly created substrings of the expression. Since creating a substring takes $O(n)$ time, where $n$ is the length of the string, this can be quite slow. Instead, we’ll pass the entire `expression` to each recursive call and use `start` and `end` indices to specify the part we're interested in. This avoids the costly substring operations.\n\nIn our updated approach, each state in the recursion is defined by the `start` and `end` indices. We use a 2D array for memoization, where each cell `memo[i][j]` holds the list of possible results for the sub-expression from index `i` to index `j`.\n\n> Note: There is an alternative way to apply memoization in this problem. Consider the expression \"2-2-2\". This can be grouped in two ways: `(2 - 2) - 2` and `2 - (2 - 2)`. As you can see, the expression \"2 - 2\" is being evaluated repeatedly, even though the instances do not share the same indices.\n>\n> To memoize this, we need to store the substring itself as the state of the sub-problem. This can be achieved by using a map with the substring as the key and the list of results as the value. Whenever we encounter the same substring, we can return the result from the map.\n>\n> While this approach leads us to identify and cache more sub-problems, it forces us to use substrings in our recursion. In an interview setting, you can highlight both approaches and discuss their advantages and disadvantages for extra credit.\n\n#### Algorithm\n \nMain method `diffWaysToCompute`:\n\n- Initialize a 2D array `memo` to store computed results for sub-expressions.\n- Call the `computeResults` method with the full expression range and return the result.\n\nHelper method `computeResults(expression, memo, start, end)`:\n\n- Check if the result for the range `[start, end]` is memoized. If so, return the memoized result.\n- Initialize a list `results` to store computed values for the current sub-expression.\n- Check if the current range is a single digit:\n  - - If so, convert `expression` to an integer and add it to `results`.\n  - Return `results`.\n- Check if the current range is a two-digit number:\n  -  If so, compute its value and add it to `results`.\n  -  Return `results`.\n- Iterate through each character in the current range of the expression:\n  - Skip the current iteration if the character is a digit.\n  - Recursively call `computeResults` for the left part of the expression up to the current character (from `start` to `i-1`). Store the result in `leftResults`.\n  - Recursively call `computeResults` for the right part of the expression after the current character (from `i+1` to `end`). Store the result in `rightResults`.\n  - Iterate through each `leftValue` in the `leftResults`:\n    - For each `leftValue`, iterate through each `rightValue` in `rightResults`:\n      - Perform the operation (addition, subtraction, or multiplication) based on the current character.\n      - Add the computed result to the `results` list.\n  - Store the result in `memo` for the range `[start, end]`.\n- Return the `results` list.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/4xf4Rnor/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4xf4Rnor\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the the length of the input string `expression`.\n\n* Time complexity: $O(n \\cdot 2^n)$\n\n    The algorithm uses memoization to store the results of sub-problems, ensuring that each sub-problem is evaluated exactly once. There are at most $O(n^2)$ possible sub-problems, as each sub-problem is defined by its start and end indices, both ranging from $0$ to $n-1$. \n\n    Despite the efficiency gains from memoization, the time complexity is still dominated by the recursive nature of the algorithm. The recursion tree expands exponentially, with a growth factor of $O(2^n)$.\n\n    Thus, the overall time complexity remains $O(n \\cdot 2^n)$.\n\n* Space complexity: $O(n^2 \\cdot 2^n)$\n\n    The space complexity is $O(n^2 \\cdot 2^n)$, where $O(n^2)$ comes from the memoization table storing results for all sub-problems, and $O(2^n)$ accounts for the space required to store the exponentially growing number of results for each sub-problem. The recursion stack depth is at most $O(n)$, which is dominated by the exponential complexity and can therefore be omitted from the overall space complexity analysis.\n\n---\n\n### Approach 3: Tabulation\n\n#### Intuition\n\nRecursive solutions can use up a lot of stack space, which might lead to stack overflow errors. To avoid this, we'll switch to an iterative approach and build our solution step by step.\n\nWe’ll use a 2-D array, called `dp`, to keep track of intermediate results. This table will have dimensions `n x n`, where `n` is the length of our input `expression`. Each cell `dp[i][j]` will store all possible results for the sub-expression starting at index `i` and ending at index `j`. For instance, `dp[0][2]` will hold all possible results for the first three characters of the expression.\n\nFirst, we need to fill in our base cases. We loop through the `expression` to identify all single-digit and double-digit numbers.\n1. For single-digit numbers, add the digit's value to `dp[i][i]`.\n2. For double-digit numbers, add the number's value to `dp[i][i+1]`.\n\nNext, we handle longer sub-expressions. We start with lengths of 3 and go up to the length of the `expression`. For each length, we consider all possible starting points in the expression. This double loop structure ensures we consider all possible substrings of `expression`. For each sub-expression, we try different ways to split it. We go through each character and, when we find an operator, split the expression at that point. We then combine the results from the left and right parts using the operator.\n\nAfter we've filled our entire `dp` table, the cell `dp[0][n-1]` contains all possible results for the entire expression. We can return this list as our final answer.\n\n#### Algorithm\n\nMain method `diffWaysToCompute`:\n\n- Initialize a variable `n` to store the length of the input string `expression`.\n- Create a 2D array `dp` of lists to store the results of sub-problems.\n- Initialize the base cases using the `initializeBaseCases` method.\n- Iterate through all possible sub-expression lengths, starting from `3` up to `n`.\n  - For each length, iterate through all possible `start` positions of the sub-expression.\n  - Set `end` as `start + length - 1`.\n  - Calculate the results for the sub-expression `[start, end]` using the `processSubexpression` method.\n- Return `dp[0][n-1]`, which contains all possible results for the entire `expression`.\n\nHelper method `initializeBaseCases(expression, dp)`:\n\n- Initialize the `dp` array.\n- Handle base cases by iterating through the `expression`:\n  - For single digits, add the digit value to `dp[i][i]`.\n  - For two-digit numbers, add the number value to `dp[i][i+1]`.\n\nHelper method `processSubexpression(expression, dp, start, end)`:\n\n- Try all possible `split` positions from `start` to `end`:\n  - If the character is numeric, continue to the next iteration\n  - If not, retrieve the results of the left sub-expression from `dp[start][split-1]` and assign it to `leftResults`.\n  - Retrieve the results of the right sub-expression from `dp[split+1][end]` and assign it to `rightResults`.\n  - Call `computeResults` with `leftResults`, `rightResults`, and the operator at the `split` position.\n\nHelper method `computeResults(op, leftResults, rightResults, results)`:\n\n- For each combination of `leftResults` and `rightResults`:\n  - Perform the operation specified by `op`.\n  - Add the result to `results`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/3Gw7Y5ZR/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3Gw7Y5ZR\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the the length of the input string `expression`.\n\n* Time complexity: $O(n \\cdot 2^n)$\n\n    Similar to the memoization approach, the algorithm evaluates each sub-problem exactly once. Thus, the time complexity remains the same as Approach 2: $O(n \\cdot 2^n)$.\n\n* Space complexity: $O(n^2 \\cdot 2^n)$\n\n    The space complexity is similar to the previous approach, with one key difference: the absence of the recursive stack space. \n\n    However, the `dp` table dominates the space complexity anyway, keeping the overall space complexity as $O(n^2 \\cdot 2^n)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  @functools.lru_cache(None)\n  def diffWaysToCompute(self, expression: str) -> List[int]:\n    ans = []\n\n    for i, c in enumerate(expression):\n      if c in '+-*':\n        for a in self.diffWaysToCompute(expression[:i]):\n          for b in self.diffWaysToCompute(expression[i + 1:]):\n            ans.append(eval(str(a) + c + str(b)))\n\n    return ans or [int(expression)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> diffWaysToCompute(String expression) {\n    return ways(expression, new HashMap<>());\n  }\n\n  private List<Integer> ways(final String s, Map<String, List<Integer>> memo) {\n    if (memo.containsKey(s))\n      return memo.get(s);\n\n    List<Integer> ans = new ArrayList<>();\n\n    for (int i = 0; i < s.length(); ++i)\n      if (!Character.isDigit(s.charAt(i)))\n        for (final int a : ways(s.substring(0, i), memo))\n          for (final int b : ways(s.substring(i + 1), memo))\n            if (s.charAt(i) == '+')\n              ans.add(a + b);\n            else if (s.charAt(i) == '-')\n              ans.add(a - b);\n            else\n              ans.add(a * b);\n\n    if (ans.isEmpty()) { // Single number\n      memo.put(s, Arrays.asList(Integer.parseInt(s)));\n      return memo.get(s);\n    }\n    memo.put(s, ans);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> diffWaysToCompute(string expression) {\n    return ways(expression, {});\n  }\n\n private:\n  vector<int> ways(const string& s, unordered_map<string, vector<int>>&& memo) {\n    if (memo.count(s))\n      return memo[s];\n\n    vector<int> ans;\n\n    for (int i = 0; i < s.length(); ++i)\n      if (ispunct(s[i]))\n        for (const int a : ways(s.substr(0, i), move(memo)))\n          for (const int b : ways(s.substr(i + 1), move(memo)))\n            if (s[i] == '+')\n              ans.push_back(a + b);\n            else if (s[i] == '-')\n              ans.push_back(a - b);\n            else\n              ans.push_back(a * b);\n\n    return memo[s] = (ans.empty() ? vector<int>{stoi(s)} : ans);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/241.html",
    "category": "Algorithms",
    "acceptance_rate": 72.26778071118662,
    "topics": [
      "Math",
      "String",
      "Dynamic Programming",
      "Recursion",
      "Memoization"
    ],
    "hints": [],
    "likes": 6177,
    "dislikes": 384,
    "similar_questions": "[{\"title\": \"Unique Binary Search Trees II\", \"titleSlug\": \"unique-binary-search-trees-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator\", \"titleSlug\": \"basic-calculator\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Expression Add Operators\", \"titleSlug\": \"expression-add-operators\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"The Score of Students Solving Math Expression\", \"titleSlug\": \"the-score-of-students-solving-math-expression\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimize Result by Adding Parentheses to Expression\", \"titleSlug\": \"minimize-result-by-adding-parentheses-to-expression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"345.5K\", \"totalSubmission\": \"478K\", \"totalAcceptedRaw\": 345453, \"totalSubmissionRaw\": 478018, \"acRate\": \"72.3%\"}",
    "title_pt": "Diferentes Maneiras de Adicionar Parênteses",
    "description_pt": "<p>Dada uma string <code>expression</code> de números e operadores, retorne <em>todos os resultados possíveis de calcular todas as diferentes maneiras possíveis de agrupar números e operadores</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>Os casos de teste são gerados de forma que os valores de saída caibam em um inteiro de 32 bits e o número de resultados diferentes não exceda <code>10<sup>4</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> expression = &quot;2-1-1&quot;\n<strong>Saída:</strong> [0,2]\n<strong>Explicação:</strong>\n((2-1)-1) = 0 \n(2-(1-1)) = 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> expression = &quot;2*3-4*5&quot;\n<strong>Saída:</strong> [-34,-14,-10,-10,10]\n<strong>Explicação:</strong>\n(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= expression.length &lt;= 20</code></li>\n\t<li><code>expression</code> consiste em dígitos e nos operadores <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, e <code>&#39;*&#39;</code>.</li>\n\t<li>Todos os valores inteiros na expressão de entrada estão no intervalo <code>[0, 99]</code>.</li>\n\t<li>Os valores inteiros na expressão de entrada não possuem um <code>&#39;-&#39;</code> ou <code>&#39;+&#39;</code> à esquerda denotando o sinal.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "242",
    "paidOnly": false,
    "title": "Valid Anagram",
    "titleSlug": "valid-anagram",
    "url": "https://leetcode.com/problems/valid-anagram",
    "description_url": "https://leetcode.com/problems/valid-anagram/description/",
    "description": "<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> if <code>t</code> is an <span data-keyword=\"anagram\">anagram</span> of <code>s</code>, and <code>false</code> otherwise.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;rat&quot;, t = &quot;car&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>\n",
    "solution_url": "https://leetcode.com/problems/valid-anagram/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isAnagram(self, s: str, t: str) -> bool:\n    if len(s) != len(t):\n      return False\n\n    dict = Counter(s)\n\n    for c in t:\n      dict[c] -= 1\n      if dict[c] < 0:\n        return False\n\n    return True",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isAnagram(String s, String t) {\n    if (s.length() != t.length())\n      return false;\n\n    int[] count = new int[128];\n\n    for (final char c : s.toCharArray())\n      ++count[c];\n\n    for (final char c : t.toCharArray())\n      if (--count[c] < 0)\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isAnagram(string s, string t) {\n    if (s.length() != t.length())\n      return false;\n\n    vector<int> count(128);\n\n    for (const char c : s)\n      ++count[c];\n\n    for (const char c : t)\n      if (--count[c] < 0)\n        return false;\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/242.html",
    "category": "Algorithms",
    "acceptance_rate": 66.48923581966272,
    "topics": [
      "Hash Table",
      "String",
      "Sorting"
    ],
    "hints": [],
    "likes": 12996,
    "dislikes": 430,
    "similar_questions": "[{\"title\": \"Group Anagrams\", \"titleSlug\": \"group-anagrams\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Permutation\", \"titleSlug\": \"palindrome-permutation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find All Anagrams in a String\", \"titleSlug\": \"find-all-anagrams-in-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Resultant Array After Removing Anagrams\", \"titleSlug\": \"find-resultant-array-after-removing-anagrams\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4.7M\", \"totalSubmission\": \"7.1M\", \"totalAcceptedRaw\": 4717121, \"totalSubmissionRaw\": 7094570, \"acRate\": \"66.5%\"}",
    "title_pt": "Anagrama Válido",
    "description_pt": "<p>Dadas duas strings <code>s</code> e <code>t</code>, retorne <code>true</code> se <code>t</code> for um <span data-keyword=\"anagram\">anagrama</span> de <code>s</code>, e <code>false</code> caso contrário.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;anagram&quot;, t = &quot;nagaram&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;rat&quot;, t = &quot;car&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> e <code>t</code> consistem de letras minúsculas do inglês.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> E se as entradas contiverem caracteres Unicode? Como você adaptaria sua solução para tal caso?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "257",
    "paidOnly": false,
    "title": "Binary Tree Paths",
    "titleSlug": "binary-tree-paths",
    "url": "https://leetcode.com/problems/binary-tree-paths",
    "description_url": "https://leetcode.com/problems/binary-tree-paths/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</p>\n\n<p>A <strong>leaf</strong> is a node with no children.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg\" style=\"width: 207px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,null,5]\n<strong>Output:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> [&quot;1&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-paths/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n    ans = []\n\n    def dfs(root: Optional[TreeNode], path: List[str]) -> None:\n      if not root:\n        return\n      if not root.left and not root.right:\n        ans.append(''.join(path) + str(root.val))\n        return\n\n      path.append(str(root.val) + '->')\n      dfs(root.left, path)\n      dfs(root.right, path)\n      path.pop()\n\n    dfs(root, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> binaryTreePaths(TreeNode root) {\n    List<String> ans = new ArrayList<>();\n    dfs(root, new StringBuilder(), ans);\n    return ans;\n  }\n\n  private void dfs(TreeNode root, StringBuilder sb, List<String> ans) {\n    if (root == null)\n      return;\n    if (root.left == null && root.right == null) {\n      ans.add(sb.append(root.val).toString());\n      return;\n    }\n\n    final int length = sb.length();\n    dfs(root.left, sb.append(root.val).append(\"->\"), ans);\n    sb.setLength(length);\n    dfs(root.right, sb.append(root.val).append(\"->\"), ans);\n    sb.setLength(length);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> binaryTreePaths(TreeNode* root) {\n    vector<string> ans;\n    dfs(root, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(TreeNode* root, vector<string>&& path, vector<string>& ans) {\n    if (root == nullptr)\n      return;\n    if (root->left == nullptr && root->right == nullptr) {\n      ans.push_back(join(path) + to_string(root->val));\n      return;\n    }\n\n    path.push_back(to_string(root->val) + \"->\");\n    dfs(root->left, move(path), ans);\n    dfs(root->right, move(path), ans);\n    path.pop_back();\n  }\n\n  string join(const vector<string>& path) {\n    string joined;\n    for (const string& s : path)\n      joined += s;\n    return joined;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/257.html",
    "category": "Algorithms",
    "acceptance_rate": 66.30133866398288,
    "topics": [
      "String",
      "Backtracking",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 6882,
    "dislikes": 325,
    "similar_questions": "[{\"title\": \"Path Sum II\", \"titleSlug\": \"path-sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest String Starting From Leaf\", \"titleSlug\": \"smallest-string-starting-from-leaf\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Step-By-Step Directions From a Binary Tree Node to Another\", \"titleSlug\": \"step-by-step-directions-from-a-binary-tree-node-to-another\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"861.7K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 861685, \"totalSubmissionRaw\": 1299645, \"acRate\": \"66.3%\"}",
    "title_pt": "Caminhos na Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>todos os caminhos da raiz até as folhas em <strong>qualquer ordem</strong></em>.</p>\n\n<p>Uma <strong>folha</strong> é um nó sem filhos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg\" style=\"width: 207px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,null,5]\n<strong>Saída:</strong> [&quot;1-&gt;2-&gt;5&quot;,&quot;1-&gt;3&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> [&quot;1&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 100]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "258",
    "paidOnly": false,
    "title": "Add Digits",
    "titleSlug": "add-digits",
    "url": "https://leetcode.com/problems/add-digits",
    "description_url": "https://leetcode.com/problems/add-digits/description/",
    "description": "<p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 38\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The process is\n38 --&gt; 3 + 8 --&gt; 11\n11 --&gt; 1 + 1 --&gt; 2 \nSince 2 has only one digit, return it.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>\n",
    "solution_url": "https://leetcode.com/problems/add-digits/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addDigits(self, num: int) -> int:\n    return 0 if num == 0 else 1 + (num - 1) % 9",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int addDigits(int num) {\n    return 1 + (num - 1) % 9;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int addDigits(int num) {\n    return 1 + (num - 1) % 9;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/258.html",
    "category": "Algorithms",
    "acceptance_rate": 67.8203294044704,
    "topics": [
      "Math",
      "Simulation",
      "Number Theory"
    ],
    "hints": [
      "A naive implementation of the above process is trivial. Could you come up with other methods?",
      "What are all the possible results?",
      "How do they occur, periodically or randomly?",
      "You may find this <a href=\"https://en.wikipedia.org/wiki/Digital_root\" target=\"_blank\">Wikipedia article</a> useful."
    ],
    "likes": 5096,
    "dislikes": 1954,
    "similar_questions": "[{\"title\": \"Happy Number\", \"titleSlug\": \"happy-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Digits in the Minimum Number\", \"titleSlug\": \"sum-of-digits-in-the-minimum-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Digits of String After Convert\", \"titleSlug\": \"sum-of-digits-of-string-after-convert\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Four Digit Number After Splitting Digits\", \"titleSlug\": \"minimum-sum-of-four-digit-number-after-splitting-digits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Calculate Digit Sum of a String\", \"titleSlug\": \"calculate-digit-sum-of-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Difference Between Element Sum and Digit Sum of an Array\", \"titleSlug\": \"difference-between-element-sum-and-digit-sum-of-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Alternating Digit Sum\", \"titleSlug\": \"alternating-digit-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"971.3K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 971329, \"totalSubmissionRaw\": 1432213, \"acRate\": \"67.8%\"}",
    "title_pt": "Somar Dígitos",
    "description_pt": "<p>Dado um inteiro <code>num</code>, some repetidamente todos os seus dígitos até que o resultado tenha apenas um dígito, e retorne-o.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 38\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> O processo é\n38 --&gt; 3 + 8 --&gt; 11\n11 --&gt; 1 + 1 --&gt; 2 \nComo 2 tem apenas um dígito, retorne-o.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue fazer isso sem nenhum laço/recursão em tempo de execução <code>O(1)</code>?</p>",
    "hints_pt": [
      "Dica 1: Uma implementação ingênua do processo acima é trivial. Você consegue pensar em outros métodos?",
      "Dica 2: Quais são todos os resultados possíveis?",
      "Dica 3: Como eles ocorrem, periodicamente ou aleatoriamente?",
      "Dica 4: Você pode achar este <a href=\"https://en.wikipedia.org/wiki/Digital_root\" target=\"_blank\">artigo da Wikipedia</a> útil."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "260",
    "paidOnly": false,
    "title": "Single Number III",
    "titleSlug": "single-number-iii",
    "url": "https://leetcode.com/problems/single-number-iii",
    "description_url": "https://leetcode.com/problems/single-number-iii/description/",
    "description": "<p>Given an integer array <code>nums</code>, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in <strong>any order</strong>.</p>\n\n<p>You must write an&nbsp;algorithm that runs in linear runtime complexity and uses&nbsp;only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,1,3,2,5]\n<strong>Output:</strong> [3,5]\n<strong>Explanation: </strong> [5, 3] is also a valid answer.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,0]\n<strong>Output:</strong> [-1,0]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1]\n<strong>Output:</strong> [1,0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Each integer in <code>nums</code> will appear twice, only two integers will appear once.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/single-number-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def singleNumber(self, nums: List[int]) -> List[int]:\n    xors = functools.reduce(operator.xor, nums)\n    lowbit = xors & -xors\n    ans = [0, 0]\n\n    # Seperate nums into two groups by the lowbit\n    for num in nums:\n      if num & lowbit:\n        ans[0] ^= num\n      else:\n        ans[1] ^= num\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] singleNumber(int[] nums) {\n    final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt();\n    final int lowbit = xors & -xors;\n    int[] ans = new int[2];\n\n    // Seperate nums into two groups by the lowbit\n    for (final int num : nums)\n      if ((num & lowbit) > 0)\n        ans[0] ^= num;\n      else\n        ans[1] ^= num;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> singleNumber(vector<int>& nums) {\n    const int xors = accumulate(begin(nums), end(nums), 0, bit_xor<>());\n    const int lowbit = xors & -xors;\n    vector<int> ans(2);\n\n    // Seperate nums into two groups by the lowbit\n    for (const int num : nums)\n      if (num & lowbit)\n        ans[0] ^= num;\n      else\n        ans[1] ^= num;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/260.html",
    "category": "Algorithms",
    "acceptance_rate": 70.66416701107173,
    "topics": [
      "Array",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 6550,
    "dislikes": 272,
    "similar_questions": "[{\"title\": \"Single Number\", \"titleSlug\": \"single-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Single Number II\", \"titleSlug\": \"single-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find The Original Array of Prefix Xor\", \"titleSlug\": \"find-the-original-array-of-prefix-xor\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the XOR of Numbers Which Appear Twice\", \"titleSlug\": \"find-the-xor-of-numbers-which-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"519.8K\", \"totalSubmission\": \"735.6K\", \"totalAcceptedRaw\": 519782, \"totalSubmissionRaw\": 735566, \"acRate\": \"70.7%\"}",
    "title_pt": "Single Number III",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, no qual exatamente dois elementos aparecem apenas uma vez e todos os outros elementos aparecem exatamente duas vezes. Encontre os dois elementos que aparecem apenas uma vez. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>Você deve escrever um&nbsp;algoritmo que tenha complexidade de tempo linear e use&nbsp;apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,1,3,2,5]\n<strong>Saída:</strong> [3,5]\n<strong>Explicação: </strong> [5, 3] também é uma resposta válida.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,0]\n<strong>Saída:</strong> [-1,0]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1]\n<strong>Saída:</strong> [1,0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>Cada inteiro em <code>nums</code> aparecerá duas vezes, apenas dois inteiros aparecerão uma vez.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "262",
    "paidOnly": false,
    "title": "Trips and Users",
    "titleSlug": "trips-and-users",
    "url": "https://leetcode.com/problems/trips-and-users",
    "description_url": "https://leetcode.com/problems/trips-and-users/description/",
    "description": "<p>Table: <code>Trips</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| id          | int      |\n| client_id   | int      |\n| driver_id   | int      |\n| city_id     | int      |\n| status      | enum     |\n| request_at  | varchar  |     \n+-------------+----------+\nid is the primary key (column with unique values) for this table.\nThe table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table.\nStatus is an ENUM (category) type of (&#39;completed&#39;, &#39;cancelled_by_driver&#39;, &#39;cancelled_by_client&#39;).\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Users</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| users_id    | int      |\n| banned      | enum     |\n| role        | enum     |\n+-------------+----------+\nusers_id is the primary key (column with unique values) for this table.\nThe table holds all users. Each user has a unique users_id, and role is an ENUM type of (&#39;client&#39;, &#39;driver&#39;, &#39;partner&#39;).\nbanned is an ENUM (category) type of (&#39;Yes&#39;, &#39;No&#39;).\n</pre>\n\n<p>&nbsp;</p>\n\n<p>The <strong>cancellation rate</strong> is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.</p>\n\n<p>Write a solution to find the <strong>cancellation rate</strong> of requests with unbanned users (<strong>both client and driver must not be banned</strong>) each day between <code>&quot;2013-10-01&quot;</code> and <code>&quot;2013-10-03&quot;</code> with <strong>at least</strong> one trip. Round <code>Cancellation Rate</code> to <strong>two decimal</strong> points.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nTrips table:\n+----+-----------+-----------+---------+---------------------+------------+\n| id | client_id | driver_id | city_id | status              | request_at |\n+----+-----------+-----------+---------+---------------------+------------+\n| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |\n| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |\n| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |\n| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |\n| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |\n| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |\n| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |\n| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |\n| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |\n| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |\n+----+-----------+-----------+---------+---------------------+------------+\nUsers table:\n+----------+--------+--------+\n| users_id | banned | role   |\n+----------+--------+--------+\n| 1        | No     | client |\n| 2        | Yes    | client |\n| 3        | No     | client |\n| 4        | No     | client |\n| 10       | No     | driver |\n| 11       | No     | driver |\n| 12       | No     | driver |\n| 13       | No     | driver |\n+----------+--------+--------+\n<strong>Output:</strong> \n+------------+-------------------+\n| Day        | Cancellation Rate |\n+------------+-------------------+\n| 2013-10-01 | 0.33              |\n| 2013-10-02 | 0.00              |\n| 2013-10-03 | 0.50              |\n+------------+-------------------+\n<strong>Explanation:</strong> \nOn 2013-10-01:\n  - There were 4 requests in total, 2 of which were canceled.\n  - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation.\n  - Hence there are 3 unbanned requests in total, 1 of which was canceled.\n  - The Cancellation Rate is (1 / 3) = 0.33\nOn 2013-10-02:\n  - There were 3 requests in total, 0 of which were canceled.\n  - The request with Id=6 was made by a banned client, so it is ignored.\n  - Hence there are 2 unbanned requests in total, 0 of which were canceled.\n  - The Cancellation Rate is (0 / 2) = 0.00\nOn 2013-10-03:\n  - There were 3 requests in total, 1 of which was canceled.\n  - The request with Id=8 was made by a banned client, so it is ignored.\n  - Hence there are 2 unbanned request in total, 1 of which were canceled.\n  - The Cancellation Rate is (1 / 2) = 0.50\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/trips-and-users/solutions/",
    "solution": "[TOC]\n\n# Solution\n\n---\n\n### Overview\n\nCalculate the daily cancellation rate for taxi trip requests made by unbanned users between \"2013-10-01\" and \"2013-10-03\". The cancellation rate for a day is the number of canceled trips (either by client or driver) divided by the total number of trips requested by unbanned users.\n\n**Visualized Output**\n\n![fig](../Figures/262/262.png)\n\n**Tables and Fields**\n\n1. **Trips**: The table holds all taxi trips.\n   - Fields: `id`, `client_id`, `driver_id`, `status`, `request_at`\n   - We are interested in the `client_id`, `driver_id`, `status`, and `request_at` columns.\n2. **Users**: The table holds all users.\n   - Fields: id, client_id, driver_id, status, request_at\n   - The `users_id` and `banned` columns are essential to filter out banned users.\n\n**Relationships**\n1. `Trips.client_id` = `Users.users_id`\n2. `Trips.driver_id` = `Users.users_id`\n\n---\n\n## pandas\n\n### Approach 1: DataFrame Merging\n\n#### Intuition\n\nThe algorithm merges trip information with user details, filters out trips with banned users and those outside a specific date range, and then calculates the daily cancellation rate for the selected trips.\n\n#### Algorithm\n\n1. **Preliminary Check**:\n   - Check if either the `trips` or `users` DataFrame is empty.\n   - If either is empty, return a DataFrame with \"Day\" and \"Cancellation Rate\" columns.\n\n2. **Prepare Data for Client Merge**:\n   - Adjust the `users` DataFrame column names for clarity: \n     - Rename `users_id` to `client_id`.\n     - Rename `banned` to `client_banned`.\n\n<table>\n  <tr>\n    <th>client_id</th>\n    <th>client_banned</th>\n    <th>role</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>No</td>\n    <td>client</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>Yes</td>\n    <td>client</td>\n  </tr>\n  <tr>\n    <td>3</td>\n    <td>No</td>\n    <td>client</td>\n  </tr>\n  <tr>\n    <td>4</td>\n    <td>No</td>\n    <td>client</td>\n  </tr>\n</table>\n<br>\n\n3. **Client Merge**:\n   - Merge `trips` with the modified `users` DataFrame using `client_id`.\n   - Use a left merge to ensure retention of all trip records.\n   - The outcome is the `trips_with_clients` DataFrame.\n\n<table>\n  <tr>\n    <th>id</th>\n    <th>client_id</th>\n    <th>driver_id</th>\n    <th>city_id</th>\n    <th>status</th>\n    <th>request_at</th>\n    <th>client_banned</th>\n    <th>role</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>1</td>\n    <td>10</td>\n    <td>1</td>\n    <td>completed</td>\n    <td>2013-10-01</td>\n    <td>No</td>\n    <td>client</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>2</td>\n    <td>11</td>\n    <td>1</td>\n    <td>cancelled_by_driver</td>\n    <td>2013-10-01</td>\n    <td>Yes</td>\n    <td>client</td>\n  </tr>\n</table>\n<br>\n\n4. **Prepare Data for Driver Merge**:\n   - Modify column names in the `users` DataFrame to differentiate drivers:\n     - Change `users_id` to `driver_id`.\n     - Adjust `banned` to `driver_banned`.\n\n<table>\n  <tr>\n    <th>driver_id</th>\n    <th>driver_banned</th>\n    <th>role</th>\n  </tr>\n  <tr>\n    <td>10</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n  <tr>\n    <td>11</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n  <tr>\n    <td>12</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n  <tr>\n    <td>13</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n</table>\n<br>\n\n5. **Driver Merge**:\n   - Combine `trips_with_clients` with the modified `users` DataFrame based on `driver_id`.\n   - Utilize a left merge once more. \n   - The final merged data is stored as `full_trips`.\n\n<table>\n  <tr>\n    <th>id</th>\n    <th>client_id</th>\n    <th>driver_id</th>\n    <th>city_id</th>\n    <th>status</th>\n    <th>request_at</th>\n    <th>client_banned</th>\n    <th>client_role</th>\n    <th>driver_banned</th>\n    <th>driver_role</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>1</td>\n    <td>10</td>\n    <td>1</td>\n    <td>completed</td>\n    <td>2013-10-01</td>\n    <td>No</td>\n    <td>client</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n  <tr>\n    <td>2</td>\n    <td>2</td>\n    <td>11</td>\n    <td>1</td>\n    <td>cancelled_by_driver</td>\n    <td>2013-10-01</td>\n    <td>Yes</td>\n    <td>client</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n</table>\n<br>\n\n6. **Filtering**:\n   - Apply boolean indexing to `full_trips` to:\n     - Omit entries with banned clients or drivers.\n     - Retain rows where the `request_at` date falls between '2013-10-01' and '2013-10-03'.\n   - The filtered data is saved as `filtered_trips`.\n\n<table>\n  <tr>\n    <th>id</th>\n    <th>client_id</th>\n    <th>driver_id</th>\n    <th>city_id</th>\n    <th>status</th>\n    <th>request_at</th>\n    <th>client_banned</th>\n    <th>client_role</th>\n    <th>driver_banned</th>\n    <th>driver_role</th>\n  </tr>\n  <tr>\n    <td>1</td>\n    <td>1</td>\n    <td>10</td>\n    <td>1</td>\n    <td>completed</td>\n    <td>2013-10-01</td>\n    <td>No</td>\n    <td>client</td>\n    <td>No</td>\n    <td>driver</td>\n  </tr>\n</table>\n<br>\n\n7. **Calculate Cancellation Rate**:\n   - Group `filtered_trips` by the `request_at` column.\n   - Within each group, determine the cancellation rate, which is the proportion of trips not marked as 'completed'. \n   - Round the result to two decimal places.\n\n<table>\n  <tr>\n    <th>request_at</th>\n    <th>Cancellation Rate</th>\n  </tr>\n  <tr>\n    <td>2013-10-01</td>\n    <td>0.33</td>\n  </tr>\n  <tr>\n    <td>2013-10-02</td>\n    <td>0.00</td>\n  </tr>\n  <tr>\n    <td>2013-10-03</td>\n    <td>0.50</td>\n  </tr>\n</table>\n<br>\n\n8. **Result Presentation**:\n   - If the computed result is empty after determining the cancellation rate, output an empty DataFrame with \"Day\" and \"Cancellation Rate\" columns.\n   - Otherwise, reset the index of the result and rename the `request_at` column as \"Day\".\n\n<table>\n  <tr>\n    <th>Day</th>\n    <th>Cancellation Rate</th>\n  </tr>\n  <tr>\n    <td>2013-10-01</td>\n    <td>0.33</td>\n  </tr>\n  <tr>\n    <td>2013-10-02</td>\n    <td>0.00</td>\n  </tr>\n  <tr>\n    <td>2013-10-03</td>\n    <td>0.50</td>\n  </tr>\n</table>\n<br>\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n<iframe src=\"https://leetcode.com/playground/Hkj2oqPS/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Hkj2oqPS\"></iframe>\n\n### Approach 2: Utilizing Intermediate DataFrames\n\n#### Intuition\n\nThe key idea here is to pinpoint the undesirable rows (or indices) and then discard them.\n\nUse boolean indexing to spot rows in the `users` DataFrame representing banned users. Subsequently, with the `isin` method, eliminate rows in the `trips` DataFrame associated with these users. Essentially, this method is about tagging certain rows or indices as \"unwanted\" and then bypassing them in the main operation.\n\n#### Algorithm\n\n1. **Data Verification:** \n    - Check if either `trips` or `users` DataFrames are empty.\n    - If so, return a DataFrame with columns \"Day\" and \"Cancellation Rate\" without any data.\n\n2. **Isolating Banned Users:** \n    - Use boolean indexing on the `users` DataFrame to extract the IDs (`users_id`) of users who are banned.\n\n3. **Filtering Relevant Trip Data:** \n    - Discard rows from the `trips` DataFrame with `client_id` or `driver_id` matching the IDs of banned users.\n    - Retain rows in the `trips` DataFrame with `request_at` dates from '2013-10-01' to '2013-10-03'.\n\n4. **Aggregating Data:** \n    - Group data in the `selected_trips` DataFrame by the `request_at` column.\n    - For each group, compute the cancellation rate by finding the ratio of non-completed trips to the total trips, rounded to two decimal places.\n\n5. **Result Compilation:** \n    - If `aggregated_result` DataFrame isn't empty, reset its index and rename the `request_at` column to 'Date'.\n    - If it's empty, return a DataFrame with columns \"Date\" and \"Cancellation Rate\" without any data.\n\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n```python\nimport pandas as pd\n\ndef trips_and_users(trips: pd.DataFrame, users: pd.DataFrame) -> pd.DataFrame:\n    # Step 1: Data Verification\n    # Check if either `trips` or `users` DataFrames are empty.\n    # If so, return a DataFrame with columns \"Day\" and \"Cancellation Rate\" without any data.\n    if trips.empty or users.empty:\n        return pd.DataFrame(columns=[\"Day\", \"Cancellation Rate\"])\n\n    # Step 2: Isolating Banned Users\n    # Using boolean indexing on the `users` DataFrame, extract the IDs (`users_id`) of users who are banned.\n    banned_users_ids = users[users[\"banned\"] == \"Yes\"][\"users_id\"]\n\n    # Step 3: Filtering Relevant Trip Data\n    # Remove rows from `trips` DataFrame that have `client_id` or `driver_id` matching the IDs of banned users.\n    # Retain rows in the `trips` DataFrame that have `request_at` dates within the range of '2013-10-01' to '2013-10-03'.\n    selected_trips = trips[\n        (~trips[\"client_id\"].isin(banned_users_ids))\n        & (~trips[\"driver_id\"].isin(banned_users_ids))\n        & (trips[\"request_at\"].between(\"2013-10-01\", \"2013-10-03\"))\n    ]\n\n    # Step 4: Aggregating Data\n    # Group the data in the `selected_trips` DataFrame based on the `request_at` column.\n    # For each group, calculate the cancellation rate by determining the ratio of non-completed trips to the total number of trips, rounding to two decimal places.\n    aggregated_result = selected_trips.groupby(\"request_at\").apply(\n        lambda group: pd.Series(\n            {\n                \"Cancellation Rate\": round(\n                    (group[\"status\"] != \"completed\").sum() / len(group), 2\n                )\n            }\n        )\n    )\n\n    # Step 5: Result Compilation\n    # If the `aggregated_result` DataFrame isn't empty, reset its index and rename the `request_at` column to 'Date'.\n    # If it's empty, return a DataFrame with columns \"Date\" and \"Cancellation Rate\" without any data.\n    if aggregated_result.empty:\n        return pd.DataFrame(columns=[\"Day\", \"Cancellation Rate\"])\n    else:\n        return aggregated_result.reset_index().rename(columns={\"request_at\": \"Day\"})\n\n```\n\n### Approach 3: DataFrame Transformations (Common Table Expression Equivalent)\n\n#### Intuition\n\nThe idea is to filter out trips outside of the three-day window and those involving banned users. The cancellation status of trips is simplified into binary values for easy computation. Data is grouped by day to provide granular insights, and the results are structured for clarity, offering a straightforward representation of daily cancellation rates.\n\n#### Algorithm\n\n1. **Initial Check:**\n   - If either the `trips` or `users` DataFrames are empty, return an empty DataFrame with columns \"Day\" and \"Cancellation Rate\".\n\n2. **Date-based Filtering:**\n   - Filter the `trips` DataFrame to only include records between October 1st and October 3rd, 2013.\n\n3. **Merge with Non-Banned Clients:**\n   - Merge the filtered `trips` DataFrame with the `users` DataFrame, specifically targeting non-banned users (`banned` column value is 'No'). \n   - This merge operation is based on the `client_id` from `trips` and `users_id` from `users`.\n   - This ensures that trips with banned clients are excluded.\n\n4. **Merge with Non-Banned Drivers:**\n   - Merge the resultant DataFrame from step 3 with the `users` DataFrame again, focusing on non-banned users.\n   - This time, the merge operation is based on the `driver_id` from the trips and `users_id` from `users`.\n   - This ensures that trips with banned drivers are excluded.\n\n5. **Calculate Day-wise Cancellation Rate:**\n   - Group the DataFrame by the `request_at` column, which represents the day of the trip.\n   - For each group, compute the cancellation rate by finding the ratio of non-completed trips to the total trips, rounded to two decimal places.\n\n6. **Format and Return the Result:**\n   - Reset the index of the resultant DataFrame for proper sequencing.\n   - Rename the `request_at` column to 'Day'.\n   - If the resulting DataFrame is empty, return an empty DataFrame with columns \"Day\" and \"Cancellation Rate\". Otherwise, return the computed results.\n\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n```python\nimport pandas as pd\n\ndef trips_and_users(trips: pd.DataFrame, users: pd.DataFrame) -> pd.DataFrame:\n    # Step 1: Initial Check\n    if trips.empty or users.empty:\n        return pd.DataFrame(columns=[\"Day\", \"Cancellation Rate\"])\n\n    # Step 2: Date-based Filtering\n    filtered_trips = trips[trips[\"request_at\"].between(\"2013-10-01\", \"2013-10-03\")]\n\n    # Step 3: Merge with Non-Banned Clients\n    trips_with_clients = filtered_trips.merge(\n        users.loc[users[\"banned\"] == \"No\", [\"users_id\"]],\n        left_on=\"client_id\",\n        right_on=\"users_id\",\n        how=\"inner\",\n    )\n\n    # Step 4: Merge with Non-Banned Drivers\n    trip_status = trips_with_clients.merge(\n        users.loc[users[\"banned\"] == \"No\", [\"users_id\"]],\n        left_on=\"driver_id\",\n        right_on=\"users_id\",\n        how=\"inner\",\n    )\n\n    # Step 5: Calculate Day-wise Cancellation Rate\n    result = trip_status.groupby(\"request_at\").apply(\n        lambda group: pd.Series(\n            {\"Cancellation Rate\": round(\n                 (group[\"status\"] != \"completed\").sum() / len(group), 2\n                 )\n             }\n        )\n    )\n\n    # Step 6: Format and Return the Result\n    if result.empty:\n        return pd.DataFrame(columns=[\"Day\", \"Cancellation Rate\"])\n    else:\n        return result.reset_index().rename(columns={\"request_at\": \"Day\"})\n\n\n```\n\n---\n\n## Database\n### Approach 1: Join\n\n#### Intuition\n\nThe idea here is to bring all the related information together first, and then decide what we need.\n\nBy joining the `Trips` table with the `Users `table twice (once for clients and once for drivers), we combine all the data we might need into one unified table. After this \"assembly\", we filter out the data that doesn't meet our criteria (e.g., banned users or dates outside our range). \n\nThis method is very direct: get everything together, then sift through to keep what's relevant.\n\n#### Algorithm\n\n1. **Table Selection**:\n   - Begin with the `Trips` table.\n\n2. **Joins**:\n   - Perform a `LEFT JOIN` with the `Users` table (aliased as `Clients`). Join on the condition that `Trips.client_id` matches `Clients.users_id`. This combines each trip with information about its client.\n   - Perform another `LEFT JOIN` with the `Users` table (aliased as `Drivers`). Join on the condition that `Trips.driver_id` matches `Drivers.users_id`. This combines each trip with information about its driver.\n\n3. **Filter Data**:\n   - `WHERE` clause: \n     - Exclude trips where the client (`Clients.banned`) is banned (`='No'`).\n     - Exclude trips where the driver (`Drivers.banned`) is banned (`='No'`).\n     - Only consider trips requested between October 1, 2013, and October 3, 2013 (`request_at BETWEEN '2013-10-01' AND '2013-10-03'`).\n\n4. **Column Selection**:\n   - Select the date the trip was requested (`request_at`) and alias it as `Day`.\n   - Calculate the cancellation rate:\n     - The numerator is the sum of trips that are not completed (`SUM(status != 'completed')`). This counts trips with a status other than 'completed' as 1, and those with 'completed' status as 0.\n     - The denominator is the total count of trips (`COUNT(*)`).\n     - Divide the numerator by the denominator and round to two decimal places using `ROUND()`. Alias this calculated value as `'Cancellation Rate'`.\n\n5. **Grouping**:\n   - `GROUP BY Day`: This groups the result set by the date of the trip request, meaning the cancellation rate will be calculated for each day separately.\n\n6. **Final Result**:\n   - For each day between October 1, 2013, and October 3, 2013, where there are trips with non-banned clients and drivers, you will get:\n     - The day.\n     - The cancellation rate for that day, rounded to two decimal places.\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n```sql\nSELECT \n  request_at AS Day, \n  ROUND(\n    SUM(status != 'completed') / COUNT(*), \n    2\n  ) AS 'Cancellation Rate' \nFROM \n  Trips \n  LEFT JOIN Users AS Clients ON Trips.client_id = Clients.users_id \n  LEFT JOIN Users AS Drivers ON Trips.driver_id = Drivers.users_id \nWHERE \n  Clients.banned = 'No' \n  AND Drivers.banned = 'No' \n  AND request_at BETWEEN '2013-10-01' \n  AND '2013-10-03' \nGROUP BY \n  Day\n\n```\n\n### Approach 2: Using Subqueries\n\n#### Intuition\n\nThe idea here is to first identify the data we don't want, and then exclude them from the following calculation.\n\nInstead of gathering everything and then filtering, this approach starts by explicitly listing what to exclude. The subqueries identify banned users. The main query then fetches trips, ensuring that any trips involving these banned users are avoided.\n\n#### Algorithm\n\n1. **Initial Data Retrieval**\n    - From the table named `Trips`, retrieve rows (or records).\n\n2. **Filter by Date**\n    - Only consider rows where the `request_at` date is between the inclusive range from '2013-10-01' to '2013-10-03'.\n\n3. **Remove Banned Drivers**\n    - From the table named `Users`, retrieve all `users_id` values where `banned` is set to 'Yes'. These represent banned users.\n    - From the `Trips` table, exclude all rows where the `driver_id` is among the list of banned users from the previous step.\n\n4. **Remove Banned Clients**\n    - Similarly, from the `Trips` table, exclude all rows where the `client_id` is among the list of banned users.\n\n5. **Grouping**\n    - Group the filtered rows from the `Trips` table by the `request_at` date. For simplicity, we're renaming `request_at` to `Day`.\n\n6. **Calculate Cancellation Rate for Each Group**\n    - For each group (or for each unique date):\n        - Calculate the sum of statuses that are not 'completed'. This is done by evaluating the condition `(status != 'completed')`, which will return `1` if the status is not 'completed' and `0` otherwise. Summing this up will give the total number of non-completed statuses.\n        - Calculate the total count of `status` for that group.\n        - Divide the sum of non-completed statuses by the total count of statuses.\n        - Round the resulting value to 2 decimal places.\n        - The final result represents the \"Cancellation Rate\" for that date.\n\n7. **Output**\n    - For each date in the range, return:\n        - The date (`Day`).\n        - The corresponding cancellation rate (`Cancellation Rate`).\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n```sql\nSELECT \n  request_at AS Day, \n  ROUND(\n    SUM(status != 'completed') / COUNT(status), \n    2\n  ) AS 'Cancellation Rate' \nFROM \n  Trips \nWHERE \n  request_at BETWEEN '2013-10-01' \n  AND '2013-10-03' \n  AND driver_id NOT IN (\n    SELECT \n      users_id \n    FROM \n      Users \n    WHERE \n      banned = 'Yes'\n  ) \n  AND client_id NOT IN (\n    SELECT \n      users_id \n    FROM \n      Users \n    WHERE \n      banned = 'Yes'\n  ) \nGROUP BY \n  Day\n\n```\n\n### Approach 3: Using Common Table Expression (CTE)\n\n#### Intuition\n\nThe idea here is to prepare a clean workspace with only what we need, and then work on it.\n\nThe CTE serves as this \"workspace\" or intermediary step. It pre-processes the data, filters out banned users, and selects only the desired date range. Once this clean, streamlined dataset (CTE) is ready, the main query can quickly compute the cancellation rate without distractions. \n\n#### Algorithm\n\n1. **Initialize CTE (Common Table Expression) `TripStatus`**:\n    - A CTE is like a temporary result set that you can reference within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement.\n\n2. **From the `Trips` table**:\n    - Select the `Request_at` column and rename it to `Day`.\n    - Evaluate if the trip status is not 'completed'. If true, it will return 1 (true), otherwise 0 (false). This is represented by the column `cancelled`.\n\n3. **Join the `Trips` table with `Users` table for Clients**:\n    - The join condition is where `Client_Id` from the `Trips` table matches `Users_Id` from the `Users` table.\n    - Furthermore, only consider those rows where the client is not banned. This means that the `Banned` column for the client should be 'No'.\n\n4. **Join the result with `Users` table again but now for Drivers**:\n    - Similarly, the join condition is where `Driver_Id` from the `Trips` table matches `Users_Id` from the `Users` table.\n    - Again, only consider those rows where the driver is not banned. This implies that the `Banned` column for the driver should be 'No'.\n\n5. **Filter the data**:\n    - Only consider those trips which have the `Request_at` value between '2013-10-01' and '2013-10-03'.\n\n6. **Now, for the main query, using the CTE `TripStatus`**:\n    - Group the data by `Day`.\n\n7. **Calculate the Cancellation Rate for each day**:\n    - For each day, sum the `cancelled` column. This will give the total number of cancelled trips for that day because a cancelled trip is represented by 1.\n    - For each day, count the `cancelled` column. This will give the total number of trips for that day, regardless of their status.\n    - Divide the sum by the count to get the cancellation rate for each day.\n    - Round this rate to 2 decimal places.\n\n8. **Final output**:\n    - Return the `Day` and the calculated 'Cancellation Rate' for each day.\n\n#### Implementation\n\nBased on the understanding above, the solution can be implemented as:\n\n```sql\nWITH TripStatus AS (\n  SELECT \n    Request_at AS Day, \n    T.status != 'completed' AS cancelled \n  FROM \n    Trips T \n    JOIN Users C ON Client_Id = C.Users_Id \n    AND C.Banned = 'No' \n    JOIN Users D ON Driver_Id = D.Users_Id \n    AND D.Banned = 'No' \n  WHERE \n    Request_at BETWEEN '2013-10-01' \n    AND '2013-10-03'\n) \nSELECT \n  Day, \n  ROUND(\n    SUM(cancelled) / COUNT(cancelled), \n    2\n  ) AS 'Cancellation Rate' \nFROM \n  TripStatus \nGROUP BY \n  Day;\n\n```",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/262.html",
    "category": "Database",
    "acceptance_rate": 37.05966772169941,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1317,
    "dislikes": 687,
    "similar_questions": "[{\"title\": \"Hopper Company Queries I\", \"titleSlug\": \"hopper-company-queries-i\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries II\", \"titleSlug\": \"hopper-company-queries-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries III\", \"titleSlug\": \"hopper-company-queries-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"227.5K\", \"totalSubmission\": \"613.9K\", \"totalAcceptedRaw\": 227501, \"totalSubmissionRaw\": 613881, \"acRate\": \"37.1%\"}",
    "title_pt": "Viagens e Usuários",
    "description_pt": "<p>Tabela: <code>Trips</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| id          | int      |\n| client_id   | int      |\n| driver_id   | int      |\n| city_id     | int      |\n| status      | enum     |\n| request_at  | varchar  |     \n+-------------+----------+\nid é a chave primária (coluna com valores únicos) desta tabela.\nA tabela armazena todas as viagens de táxi. Cada viagem possui um id único, enquanto client_id e driver_id são chaves estrangeiras para users_id na tabela Users.\nStatus é um tipo ENUM (categoria) de (&#39;completed&#39;, &#39;cancelled_by_driver&#39;, &#39;cancelled_by_client&#39;).\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Users</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| users_id    | int      |\n| banned      | enum     |\n| role        | enum     |\n+-------------+----------+\nusers_id é a chave primária (coluna com valores únicos) desta tabela.\nA tabela armazena todos os usuários. Cada usuário possui um users_id único, e role é um tipo ENUM de (&#39;client&#39;, &#39;driver&#39;, &#39;partner&#39;).\nbanned é um tipo ENUM (categoria) de (&#39;Yes&#39;, &#39;No&#39;).\n</pre>\n\n<p>&nbsp;</p>\n\n<p>A <strong>taxa de cancelamento</strong> é calculada dividindo-se o número de solicitações canceladas (pelo cliente ou pelo motorista) com usuários não banidos pelo número total de solicitações com usuários não banidos naquele dia.</p>\n\n<p>Escreva uma solução para encontrar a <strong>taxa de cancelamento</strong> de solicitações com usuários não banidos (<strong>tanto o cliente quanto o motorista não devem estar banidos</strong>) em cada dia entre <code>&quot;2013-10-01&quot;</code> e <code>&quot;2013-10-03&quot;</code> com <strong>pelo menos</strong> uma viagem. Arredonde <code>Cancellation Rate</code> para <strong>dois</strong> casas decimais.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Trips:\n+----+-----------+-----------+---------+---------------------+------------+\n| id | client_id | driver_id | city_id | status              | request_at |\n+----+-----------+-----------+---------+---------------------+------------+\n| 1  | 1         | 10        | 1       | completed           | 2013-10-01 |\n| 2  | 2         | 11        | 1       | cancelled_by_driver | 2013-10-01 |\n| 3  | 3         | 12        | 6       | completed           | 2013-10-01 |\n| 4  | 4         | 13        | 6       | cancelled_by_client | 2013-10-01 |\n| 5  | 1         | 10        | 1       | completed           | 2013-10-02 |\n| 6  | 2         | 11        | 6       | completed           | 2013-10-02 |\n| 7  | 3         | 12        | 6       | completed           | 2013-10-02 |\n| 8  | 2         | 12        | 12      | completed           | 2013-10-03 |\n| 9  | 3         | 10        | 12      | completed           | 2013-10-03 |\n| 10 | 4         | 13        | 12      | cancelled_by_driver | 2013-10-03 |\n+----+-----------+-----------+---------+---------------------+------------+\nTabela Users:\n+----------+--------+--------+\n| users_id | banned | role   |\n+----------+--------+--------+\n| 1        | No     | client |\n| 2        | Yes    | client |\n| 3        | No     | client |\n| 4        | No     | client |\n| 10       | No     | driver |\n| 11       | No     | driver |\n| 12       | No     | driver |\n| 13       | No     | driver |\n+----------+--------+--------+\n<strong>Saída:</strong> \n+------------+-------------------+\n| Day        | Cancellation Rate |\n+------------+-------------------+\n| 2013-10-01 | 0.33              |\n| 2013-10-02 | 0.00              |\n| 2013-10-03 | 0.50              |\n+------------+-------------------+\n<strong>Explicação:</strong> \nEm 2013-10-01:\n  - Houve 4 solicitações no total, 2 das quais foram canceladas.\n  - No entanto, a solicitação com Id=2 foi feita por um cliente banido (User_Id=2), então ela é ignorada no cálculo.\n  - Portanto, há 3 solicitações não banidas no total, 1 das quais foi cancelada.\n  - A Taxa de Cancelamento é (1 / 3) = 0.33\nEm 2013-10-02:\n  - Houve 3 solicitações no total, 0 das quais foram canceladas.\n  - A solicitação com Id=6 foi feita por um cliente banido, então ela é ignorada.\n  - Portanto, há 2 solicitações não banidas no total, 0 das quais foram canceladas.\n  - A Taxa de Cancelamento é (0 / 2) = 0.00\nEm 2013-10-03:\n  - Houve 3 solicitações no total, 1 das quais foi cancelada.\n  - A solicitação com Id=8 foi feita por um cliente banido, então ela é ignorada.\n  - Portanto, há 2 solicitações não banidas no total, 1 das quais foi cancelada.\n  - A Taxa de Cancelamento é (1 / 2) = 0.50\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "263",
    "paidOnly": false,
    "title": "Ugly Number",
    "titleSlug": "ugly-number",
    "url": "https://leetcode.com/problems/ugly-number",
    "description_url": "https://leetcode.com/problems/ugly-number/description/",
    "description": "<p>An <strong>ugly number</strong> is a <em>positive</em> integer which does not have a prime factor other than 2, 3, and 5.</p>\n\n<p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 6 = 2 &times; 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 1 has no prime factors.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 14\n<strong>Output:</strong> false\n<strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/ugly-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isUgly(self, n: int) -> bool:\n    if n == 0:\n      return False\n\n    for prime in 2, 3, 5:\n      while n % prime == 0:\n        n //= prime\n\n    return n == 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isUgly(int n) {\n    if (n == 0)\n      return false;\n\n    for (final int prime : new int[] {2, 3, 5})\n      while (n % prime == 0)\n        n /= prime;\n\n    return n == 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isUgly(int n) {\n    if (n == 0)\n      return false;\n\n    for (const int prime : {2, 3, 5})\n      while (n % prime == 0)\n        n /= prime;\n\n    return n == 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/263.html",
    "category": "Algorithms",
    "acceptance_rate": 42.29930047026814,
    "topics": [
      "Math"
    ],
    "hints": [],
    "likes": 3589,
    "dislikes": 1755,
    "similar_questions": "[{\"title\": \"Happy Number\", \"titleSlug\": \"happy-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Primes\", \"titleSlug\": \"count-primes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ugly Number II\", \"titleSlug\": \"ugly-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"630.3K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 630257, \"totalSubmissionRaw\": 1489997, \"acRate\": \"42.3%\"}",
    "title_pt": "Número Feio",
    "description_pt": "<p>Um <strong>número feio</strong> é um inteiro <em>positivo</em> que não tem nenhum fator primo além de 2, 3 e 5.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne <code>true</code> <em>se</em> <code>n</code> <em>é um <strong>número feio</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 6\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 6 = 2 &times; 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 1 não tem fatores primos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 14\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> 14 não é feio, pois inclui o fator primo 7.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "264",
    "paidOnly": false,
    "title": "Ugly Number II",
    "titleSlug": "ugly-number-ii",
    "url": "https://leetcode.com/problems/ugly-number-ii",
    "description_url": "https://leetcode.com/problems/ugly-number-ii/description/",
    "description": "<p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p>\n\n<p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 10\n<strong>Output:</strong> 12\n<strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1690</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/ugly-number-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nAn ugly number is a positive integer whose prime factors are limited to `2`, `3`, and `5`. This means that for a number to be classified as ugly, it can only be divided by these primes without leaving a remainder.\n\nIn Example 2, we observe that the number `1` is considered an ugly number, even though it lacks any prime factors of `2`, `3`, or `5`. This might seem confusing initially, but the explanation clarifies that \"`1` has no prime factors; therefore, all of its prime factors are limited to `2`, `3`, and `5`.\" This statement can be somewhat misleading if not properly understood. It implies that since `1` has no prime factors, it doesn't violate the rule that ugly numbers can only have prime factors of `2`, `3`, or `5`. In essence, `1` automatically meets the condition, as there are no prime factors to contradict the rule.\n\n> In short `1` is an ugly number because it can be expressed as $2^0 \\times 3^0 \\times 5^0$\n\n### Approach 1: Using Set \n\n#### Intuition\n\nWe begin with a brute force approach where the goal is to count ugly numbers one by one until we reach the nth ugly number. We can create a helper function that checks if a number is ugly by repeatedly dividing it by `2`, `3`, and `5` until it's no longer divisible by these primes. If the result is `1`, the number is ugly. We then iterate through integers applying this check, and count the ugly numbers we encounter. While this method works, it’s inefficient as it checks every number sequentially, including those clearly not ugly (e.g., numbers divisible by other primes). This results in high time complexity, making it unsuitable for large values of `n`.\n\nTo improve upon the brute force method, we can leverage a key property of ugly numbers: if a number is ugly, multiplying it by `2`, `3`, or `5` also yields an ugly number. This insight allows us to generate ugly numbers systematically rather than checking each number individually.\n\nWe start with the first ugly number, which is `1`. From there, we generate the next candidates by multiplying `1` by `2`, `3`, and `5`. These candidates represent the next potential ugly numbers. To ensure we always process the smallest ugly numbers first (necessary to find the nth one), we use a set that keeps elements in sorted order and removes duplicates. We continue this process until we reach the nth ugly number.\n\nThis approach is more efficient as it avoids unnecessary checks and focuses solely on generating and managing ugly numbers. However, it requires maintaining a set, which can grow large and impact memory usage.\n\n#### Algorithm\n\n- Initialize a set named `uglyNumbersSet` to store potential ugly numbers.\n- Insert the first ugly number, `1`, into the `uglyNumbersSet`.\n- Initialize a variable `currentUgly` to store the current smallest ugly number.\n\n- Loop `n` times to find the `n`th ugly number:\n  - In each iteration:\n    - Set `currentUgly` to the smallest number in the `uglyNumbersSet` by accessing the first element.\n    - Remove this smallest number from the `uglyNumbersSet` using `erase`.\n    \n    - Insert the next potential ugly numbers by multiplying `currentUgly` by `2`, `3`, and `5`:\n      - Insert `currentUgly * 2` into the `uglyNumbersSet`.\n      - Insert `currentUgly * 3` into the `uglyNumbersSet`.\n      - Insert `currentUgly * 5` into the `uglyNumbersSet`.\n\n- After the loop completes, `currentUgly` will hold the nth ugly number.\n\n- Return `currentUgly` as the result, casting it to `int`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/EoE3dVbv/shared\" frameBorder=\"0\" width=\"100%\" height=\"446\" name=\"EoE3dVbv\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the given index value of the ugly number and $m$ be the size of set.\n\n- Time complexity: $O(n \\log m)$\n\n    Each insertion and removal operation in the set takes logarithmic time.\n\n    > In Python, the `min` function has a time complexity of $O(n)$ due to the need to scan through all elements of the set to find the minimum. Since this function is called once per iteration of the loop and there are $n$ iterations, the overall time complexity is $O(n \\times m)$.\n\n- Space complexity: $O(m)$\n\n    The space required depends on the number of unique ugly numbers stored in the set.  \n\n---\n\n### Approach 2: Min-Heap/Priority Queue\n\n#### Intuition\n\nTo further streamline the process, we use a priority queue (min-heap) to efficiently manage and retrieve the smallest ugly number. We start with `1` as our base ugly number and insert it into the min-heap. The priority queue keeps the smallest element at the top, so we can easily access and remove it to get the next ugly number.\n\nAfter popping the smallest ugly number, we generate new ugly numbers by multiplying them by `2`, `3`, and `5`. These new numbers are then pushed back into the queue. To avoid duplicates, we use a set to track numbers that have already been added, ensuring each ugly number is processed only once.\n\n#### Algorithm\n \n- Create a min-heap (`minHeap`) to store ugly numbers and a set (`seenNumbers`) to track numbers already processed.\n- Push the first ugly number (1) into the heap and insert it into the set.\n- For `n` iterations:\n   - Pop the smallest ugly number (`currentUgly`) from the heap.\n   - Generate the next ugly numbers by multiplying `currentUgly` with 2, 3, and 5.\n   - If a generated ugly number is not in the set, push it into the heap and add it to the set.\n- After `n` iterations, the last popped number from the heap is the nth ugly number.\n- Return the `n`th ugly number.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5d395Zkn/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5d395Zkn\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the given index value of the ugly number and $m$ be the size of set.\n\n\n* Time complexity: $O(n \\log m)$\n\n    The operations on the priority queue (`push` and `pop`) take logarithmic time, and there are `m` such operations. \n\n* Space complexity: $O(m)$\n\n    The space is used by the heap and the set, which store up to `m` elements as it depends on the number of unique ugly numbers stored in the set.\n\n---\n\n### Approach 3: Dynamic Programming (DP)\n\n#### Intuition\n\nThe dynamic programming (DP) approach to finding ugly numbers is based on an idea: every ugly number, except for `1`, is generated by multiplying a smaller ugly number by either `2`, `3`, or `5`. This insight allows us to systematically generate ugly numbers in order.\n\nWe start with `1`, the smallest ugly number. To find the next ugly number, we have three options: $1 \\times 2$, $1 \\times 3$, and $1 \\times 5$. The smallest of these, $1 \\times 2 = 2$, becomes our second ugly number. For the third ugly number, we again have three choices: the next multiple of `2` ($2 \\times 2 = 4$), and the unused multiples of `3` and `5` from before ($1 \\times 3 = 3$ and $1 \\times 5 = 5$). We select the smallest of these (which is $3$) and continue this process.\n\nThis approach naturally leads to using three pointers, one each for multiplying by `2`, `3`, and `5`. These pointers track which ugly number should be multiplied by `2`, `3`, and `5` next. Each time, we choose the smallest of these three possible next ugly numbers, add it to our list, and move the pointer that produced this number.\n\nThe efficiency and cleverness of this method lie in its simplicity. We build our list of ugly numbers using the same list we are creating. This self-referencing nature characterizes it as dynamic programming. By maintaining the list in order and using pointers, we avoid the need for sorting or removing duplicates, making the algorithm both fast ($O(n)$) and memory-efficient.\n\nNow, let's think about why this method works for all ugly numbers:\n\nWe always start by choosing the smallest number available and manage the process of multiplying by `2`, `3`, and `5` separately. This approach ensures that no ugly numbers are missed. Specifically, any ugly number must be derived from a previously found smaller ugly number, multiplied by `2`, `3`, or `5`. By maintaining pointers to track these multiplications, we ensure that every number in our list is properly considered for these multiplications.\n\nBy always selecting the smallest number first from the available multiplications, we prevent the introduction of larger numbers before smaller ones. This strategy eliminates the possibility of missing any ugly numbers, ensuring a consistent and complete generation of ugly numbers.\n\n\n<details>\n<summary><b>For A Formal Proof Click Here:</b></summary>\n\n**Proof:**\n\n1. Base Case:\n   - We start with `1`, which is an ugly number because it can be expressed as $2^0 \\times 3^0 \\times 5^0$. This is our starting point and is correctly included in the list.\n\n2. Inductive Hypothesis:\n   - Assume that after generating $k$ ugly numbers, denoted as $U_1, U_2, \\ldots, U_k$, our list contains all ugly numbers up to the $k$-th position in ascending order.\n\n3. Inductive Step:\n   - **Goal:** Show that the algorithm correctly generates the $(k+1)$-th ugly number.\n\n   - Given our current list $U_1, U_2, \\ldots, U_k$, we consider the next possible ugly numbers by multiplying each number in the list by 2, 3, and 5. These potential numbers are $U_i \\times 2$, $U_i \\times 3$, and $U_i \\times 5$, where $U_i$ is the smallest number in the list at that step.\n\n   - We always select the smallest number from these candidates and add it to our list. Let’s denote this smallest number as $N$. By design, $N$ is the next smallest ugly number that hasn't been added to the list yet.\n\n   - Exhaustiveness:\n     - We ensure that every ugly number is generated by considering all possible multiplications of the smallest numbers. This way, we don't miss any possible ugly number.\n\n   - Non-Redundancy:\n     - By selecting the smallest number each time, we avoid adding duplicate numbers. This ensures that each number added to the list is unique and correctly ordered.\n\n   - Completeness:\n     - Every ugly number must be derived from previously generated ugly numbers through multiplication by 2, 3, or 5. Our method covers all such possible combinations, so it will eventually generate every ugly number.\n\n4. Termination:\n   - The algorithm stops once we have generated the desired number of ugly numbers. Since we are systematically adding the smallest possible ugly number at each step, our list will be complete and correctly ordered.\n\n**Conclusion:**\nBy using induction, we see that starting from the base case of `1`, and ensuring each subsequent number is the smallest possible ugly number, we guarantee that our algorithm will generate all ugly numbers in ascending order. This method is both correct and complete, as it ensures that no ugly numbers are missed or duplicated.\n\n</details>\n\n#### Algorithm\n \n1. Initialize a vector `uglyNumbers` of size `n` to store the ugly numbers, with the first ugly number set to `1`.\n2. Set up three pointers (`indexMultipleOf2`, `indexMultipleOf3`, `indexMultipleOf5`) to track the next multiples of 2, 3, and 5, respectively.\n3. Assign initial values to `nextMultipleOf2`, `nextMultipleOf3`, and `nextMultipleOf5` (i.e., `2`, `3`, and `5`).\n4. For `i` from `1` to `n-1`:\n   - Determine the next ugly number by taking the minimum of `nextMultipleOf2`, `nextMultipleOf3`, and `nextMultipleOf5`.\n   - Store this value in `uglyNumbers[i]`.\n   - Update the corresponding pointer and multiple:\n     - If the next ugly number equals `nextMultipleOf2`, increment `indexMultipleOf2` and update `nextMultipleOf2`.\n     - If the next ugly number equals `nextMultipleOf3`, increment `indexMultipleOf3` and update `nextMultipleOf3`.\n     - If the next ugly number equals `nextMultipleOf5`, increment `indexMultipleOf5` and update `nextMultipleOf5`.\n5. After completing the loop, return the last element in `uglyNumbers`, which is the `n`th ugly number.\n\nThe algorithm is visualized below:\n\n!?!../Documents/264/dp.json:975,595!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/KLoTWTep/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"KLoTWTep\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the given index value of the ugly number.\n\n* Time complexity: $O(n)$\n\n    This approach is linear because we generate each ugly number directly using the three pointers.\n\n* Space complexity: $O(n)$\n\n    We need space to store the first `n` ugly numbers.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nthUglyNumber(self, n: int) -> int:\n    nums = [1]\n    i2 = 0\n    i3 = 0\n    i5 = 0\n\n    while len(nums) < n:\n      next2 = nums[i2] * 2\n      next3 = nums[i3] * 3\n      next5 = nums[i5] * 5\n      next = min(next2, next3, next5)\n      if next == next2:\n        i2 += 1\n      if next == next3:\n        i3 += 1\n      if next == next5:\n        i5 += 1\n      nums.append(next)\n\n    return nums[-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int nthUglyNumber(int n) {\n    List<Integer> uglyNums = new ArrayList<>();\n    uglyNums.add(1);\n    int i2 = 0;\n    int i3 = 0;\n    int i5 = 0;\n\n    while (uglyNums.size() < n) {\n      final int next2 = uglyNums.get(i2) * 2;\n      final int next3 = uglyNums.get(i3) * 3;\n      final int next5 = uglyNums.get(i5) * 5;\n      final int next = Math.min(next2, Math.min(next3, next5));\n      if (next == next2)\n        ++i2;\n      if (next == next3)\n        ++i3;\n      if (next == next5)\n        ++i5;\n      uglyNums.add(next);\n    }\n\n    return uglyNums.get(uglyNums.size() - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int nthUglyNumber(int n) {\n    vector<int> uglyNums{1};\n    int i2 = 0;\n    int i3 = 0;\n    int i5 = 0;\n\n    while (uglyNums.size() < n) {\n      const int next2 = uglyNums[i2] * 2;\n      const int next3 = uglyNums[i3] * 3;\n      const int next5 = uglyNums[i5] * 5;\n      const int next = min({next2, next3, next5});\n      if (next == next2)\n        ++i2;\n      if (next == next3)\n        ++i3;\n      if (next == next5)\n        ++i5;\n      uglyNums.push_back(next);\n    }\n\n    return uglyNums.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/264.html",
    "category": "Algorithms",
    "acceptance_rate": 49.21745133482909,
    "topics": [
      "Hash Table",
      "Math",
      "Dynamic Programming",
      "Heap (Priority Queue)"
    ],
    "hints": [
      "The naive approach is to call <code>isUgly</code> for every number until you reach the n<sup>th</sup> one. Most numbers are <i>not</i> ugly. Try to focus your effort on generating only the ugly ones.",
      "An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.",
      "The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L<sub>1</sub>, L<sub>2</sub>, and L<sub>3</sub>.",
      "Assume you have U<sub>k</sub>, the k<sup>th</sup> ugly number. Then U<sub>k+1</sub> must be Min(L<sub>1</sub> * 2, L<sub>2</sub> * 3, L<sub>3</sub> * 5)."
    ],
    "likes": 6676,
    "dislikes": 422,
    "similar_questions": "[{\"title\": \"Merge k Sorted Lists\", \"titleSlug\": \"merge-k-sorted-lists\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Primes\", \"titleSlug\": \"count-primes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ugly Number\", \"titleSlug\": \"ugly-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Perfect Squares\", \"titleSlug\": \"perfect-squares\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Super Ugly Number\", \"titleSlug\": \"super-ugly-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ugly Number III\", \"titleSlug\": \"ugly-number-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"487.6K\", \"totalSubmission\": \"990.8K\", \"totalAcceptedRaw\": 487647, \"totalSubmissionRaw\": 990799, \"acRate\": \"49.2%\"}",
    "title_pt": "Número Feio II",
    "description_pt": "<p>Um <strong>número feio</strong> é um inteiro positivo cujos fatores primos são limitados a <code>2</code>, <code>3</code> e <code>5</code>.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>o</em> <code>n<sup>th</sup></code> <em><strong>número feio</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 10\n<strong>Saída:</strong> 12\n<strong>Explicação:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] é a sequência dos primeiros 10 números feios.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> 1 não possui fatores primos; portanto, todos os seus fatores primos são limitados a 2, 3 e 5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1690</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: A abordagem ingênua é chamar <code>isUgly</code> para cada número até você alcançar o <code>n<sup>th</sup></code>. A maioria dos números <i>não</i> é feia. Tente concentrar seu esforço em gerar somente os números feios.",
      "Dica 2: Um número feio deve ser multiplicado por 2, 3 ou 5 a partir de um número feio menor.",
      "Dica 3: A chave é como manter a ordem dos números feios. Tente uma abordagem semelhante à de mesclar três listas ordenadas: L<sub>1</sub>, L<sub>2</sub> e L<sub>3</sub>.",
      "Dica 4: Suponha que você tenha U<sub>k</sub>, o k<sup>th</sup> número feio. Então U<sub>k+1</sub> deve ser Min(L<sub>1</sub> * 2, L<sub>2</sub> * 3, L<sub>3</sub> * 5)."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "268",
    "paidOnly": false,
    "title": "Missing Number",
    "titleSlug": "missing-number",
    "url": "https://leetcode.com/problems/missing-number",
    "description_url": "https://leetcode.com/problems/missing-number/description/",
    "description": "<p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [3,0,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><code>n = 3</code> since there are 3 numbers, so all numbers are in the range <code>[0,3]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [0,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><code>n = 2</code> since there are 2 numbers, so all numbers are in the range <code>[0,2]</code>. 2 is the missing number in the range since it does not appear in <code>nums</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [9,6,4,2,3,5,7,0,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">8</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p><code>n = 9</code> since there are 9 numbers, so all numbers are in the range <code>[0,9]</code>. 8 is the missing number in the range since it does not appear in <code>nums</code>.</p>\n</div>\n\n<div class=\"simple-translate-system-theme\" id=\"simple-translate\">\n<div>\n<div class=\"simple-translate-button isShow\" style=\"background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;\">&nbsp;</div>\n\n<div class=\"simple-translate-panel \" style=\"width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;\">\n<div class=\"simple-translate-result-wrapper\" style=\"overflow: hidden;\">\n<div class=\"simple-translate-move\" draggable=\"true\">&nbsp;</div>\n\n<div class=\"simple-translate-result-contents\">\n<p class=\"simple-translate-result\" dir=\"auto\">&nbsp;</p>\n\n<p class=\"simple-translate-candidate\" dir=\"auto\">&nbsp;</p>\n</div>\n</div>\n</div>\n</div>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= n</code></li>\n\t<li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>\n",
    "solution_url": "https://leetcode.com/problems/missing-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def missingNumber(self, nums: List[int]) -> int:\n    ans = len(nums)\n\n    for i, num in enumerate(nums):\n      ans ^= i ^ num\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int missingNumber(int[] nums) {\n    int ans = nums.length;\n\n    for (int i = 0; i < nums.length; ++i)\n      ans ^= i ^ nums[i];\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int missingNumber(vector<int>& nums) {\n    int ans = nums.size();\n\n    for (int i = 0; i < nums.size(); ++i)\n      ans ^= i ^ nums[i];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/268.html",
    "category": "Algorithms",
    "acceptance_rate": 69.82003412582525,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Binary Search",
      "Bit Manipulation",
      "Sorting"
    ],
    "hints": [],
    "likes": 13073,
    "dislikes": 3409,
    "similar_questions": "[{\"title\": \"First Missing Positive\", \"titleSlug\": \"first-missing-positive\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Single Number\", \"titleSlug\": \"single-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Duplicate Number\", \"titleSlug\": \"find-the-duplicate-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Couples Holding Hands\", \"titleSlug\": \"couples-holding-hands\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Unique Binary String\", \"titleSlug\": \"find-unique-binary-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Largest Almost Missing Integer\", \"titleSlug\": \"find-the-largest-almost-missing-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 3012870, \"totalSubmissionRaw\": 4315198, \"acRate\": \"69.8%\"}",
    "title_pt": "Número Ausente",
    "description_pt": "<p>Dado um array <code>nums</code> contendo <code>n</code> números distintos no intervalo <code>[0, n]</code>, retorne <em>o único número no intervalo que está ausente do array.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [3,0,1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><code>n = 3</code> pois há 3 números, então todos os números estão no intervalo <code>[0,3]</code>. 2 é o número ausente no intervalo, pois ele não aparece em <code>nums</code>.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [0,1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><code>n = 2</code> pois há 2 números, então todos os números estão no intervalo <code>[0,2]</code>. 2 é o número ausente no intervalo, pois ele não aparece em <code>nums</code>.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [9,6,4,2,3,5,7,0,1]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">8</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p><code>n = 9</code> pois há 9 números, então todos os números estão no intervalo <code>[0,9]</code>. 8 é o número ausente no intervalo, pois ele não aparece em <code>nums</code>.</p>\n</div>\n\n<div class=\"simple-translate-system-theme\" id=\"simple-translate\">\n<div>\n<div class=\"simple-translate-button isShow\" style=\"background-image: url(&quot;moz-extension://8a9ffb6b-7e69-4e93-aae1-436a1448eff6/icons/512.png&quot;); height: 22px; width: 22px; top: 318px; left: 36px;\">&nbsp;</div>\n\n<div class=\"simple-translate-panel \" style=\"width: 300px; height: 200px; top: 0px; left: 0px; font-size: 13px;\">\n<div class=\"simple-translate-result-wrapper\" style=\"overflow: hidden;\">\n<div class=\"simple-translate-move\" draggable=\"true\">&nbsp;</div>\n\n<div class=\"simple-translate-result-contents\">\n<p class=\"simple-translate-result\" dir=\"auto\">&nbsp;</p>\n\n<p class=\"simple-translate-candidate\" dir=\"auto\">&nbsp;</p>\n</div>\n</div>\n</div>\n</div>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= n</code></li>\n\t<li>Todos os números de <code>nums</code> são <strong>únicos</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria implementar uma solução usando apenas complexidade de espaço extra <code>O(1)</code> e complexidade de tempo <code>O(n)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "273",
    "paidOnly": false,
    "title": "Integer to English Words",
    "titleSlug": "integer-to-english-words",
    "url": "https://leetcode.com/problems/integer-to-english-words",
    "description_url": "https://leetcode.com/problems/integer-to-english-words/description/",
    "description": "<p>Convert a non-negative integer <code>num</code> to its English words representation.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 123\n<strong>Output:</strong> &quot;One Hundred Twenty Three&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 12345\n<strong>Output:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 1234567\n<strong>Output:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/integer-to-english-words/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe need to create a program that converts any non-negative integer into its English word representation. The program must handle the English numbering system accurately, including terms like thousands, millions, and billions, and must follow the rules for numbers below one hundred to ensure correct phrasing.  \n\n**Key Points:**\n- The input can range from `0` to `2,147,483,647` (i.e., the maximum value for a 32-bit signed integer).\n- The first letter of each word must be capitalized.\n- Words should be separated by a single space, with no trailing spaces.\n\nObserve the tree diagram below to understand how numbers are spelled out in English, along with their corresponding units and scales. This will help us see the repetitive patterns and their resemblance to a tree data structure, which lends itself to a recursive approach.\n\n![Number_Tree](../Figures/273/273_Integer_to_english.png)\n\n---\n\n### Approach 1: Recursive Approach\n\n#### Intuition\n\nIn the recursive approach, we break down the number into smaller parts based on place values such as ones, tens, hundreds, thousands, millions, and so on.\n\nWe start with the largest place value and proceed downward. For example, with the number `1234567`, we first handle the millions part (`1 Million`).\n\nWe use a helper function that recursively breaks down the number. If the number is less than `10`, we return the corresponding word from a predefined list (`belowTen`). For numbers less than `20`, we use another list (`belowTwenty`) due to their unique names.\n\nFor numbers below `100`, we combine the word for the tens place (from `belowHundred`) with the word for the ones place, using further recursive calls. For numbers below `1000`, we break the number into hundreds and the remainder, processing each part recursively.\n\nFor larger numbers like `1234567`, the function handles the millions part (`1 Million`), then the thousands (`234 Thousand`), and finally the hundreds and smaller units (`567`). Each chunk is processed using recursive calls, building the final English representation from smallest to largest units.\n\nThe recursive function works as follows:\n- **Base Case**: For numbers less than 10, the function directly maps to a word using `belowTen`. For numbers between 10 and 19, `belowTwenty` handles these unique cases. For numbers between 20 and 99, it combines words from `belowHundred` for tens and recursively processes the remainder for units.\n- **Recursive Case**: For numbers 100 and above, the function processes hundreds, thousands, millions, and billions by breaking the number into smaller parts. For example, for `1234567`, it processes the millions part (`1 Million`), then the thousands part (`234 Thousand`), and finally the remainder (`567`). Each part is processed recursively to ensure accurate conversion.\n\nAfter processing each chunk, we combine the results, handling the hierarchical structure from the smallest unit up to the largest (like billions), ensuring that each segment is correctly represented in English.\n\n#### Algorithm\n\n- Initialize arrays to store words for different ranges of numbers:\n  - `belowTen` for numbers 1-9.\n  - `belowTwenty` for numbers 10-19.\n  - `belowHundred` for multiples of ten from 20-90.\n\n- Define the main function `numberToWords` to handle the conversion:\n  - If the number is zero, return `\"Zero\"`.\n  - Otherwise, call the helper function `convertToWords` to start the conversion process.\n\n- Implement the helper function `convertToWords` to convert numbers to words recursively:\n  - Base Case 1: Numbers less than 10:\n    - Return the corresponding word from `belowTen`.\n  - Base Case 2: Numbers less than 20:\n    - Return the corresponding word from `belowTwenty`.\n  - Numbers from 20 to 99:\n    - Combine the word for the tens place from `belowHundred` with the recursive result for the units place.\n  - Numbers from 100 to 999:\n    - Combine the recursive result for the hundreds place with `\"Hundred\"`, and the recursive result for the remaining part.\n  - Numbers from 1000 to 999,999:\n    - Combine the recursive result for thousands with `\"Thousand\"`, and the recursive result for the remaining part.\n  - Numbers from 1,000,000 to 999,999,999:\n    - Combine the recursive result for millions with `\"Million\"`, and the recursive result for the remaining part.\n  - Numbers 1,000,000,000 and above:\n    - Combine the recursive result for billions with `\"Billion\"`, and the recursive result for the remaining part.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/gWF2VCjV/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gWF2VCjV\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number.\n\n- Time complexity: $O(\\log_{10} N)$\n\n    The time complexity is $O(\\log_{10} N)$ because the number of recursive calls is proportional to the number of digits in the number, which grows logarithmically with the size of the number.\n\n- Space complexity: $O(\\log_{10} N)$\n\n    The space complexity is $O(\\log_{10} N)$, mainly because of the recursion stack. Each recursive call adds a frame to the stack until the base case is reached, leading to space usage proportional to the number of digits in the number.\n\n---\n\n### Approach 2: Iterative Approach\n\n#### Intuition\n\nIn the iterative approach, we convert a number into English words by processing it in chunks of three digits, corresponding to thousands, millions, billions, etc.\n\nWe initialize arrays for place value words (like thousand, million, billion) and for digit and tens names. A loop processes the number from the least significant chunk (ones, tens, hundreds) to the most significant chunk (thousands, millions, billions).\n\nFor instance, with the number `1234567`, we repeatedly use the modulus operation `% 1000` to extract chunks of three digits. We start by using `1234567 % 1000` to get `567`, then `1234 % 1000` to get `234`, and finally `1 % 1000` to get `1`. Each chunk is then converted to English words.\"\n\nTo convert each chunk:\n1. Handle the hundreds place if present (e.g., `567` becomes \"Five Hundred\").\n2. Process the tens and ones (e.g., `67` becomes \"Sixty-Seven\").\n3. Append the appropriate scale word (e.g., thousand, million) based on the chunk's position (e.g., `234` becomes \"Two Hundred Thirty-Four Thousand\").\n\nWe track the scale by using an index (`groupIndex`) that increments with each chunk processed. This index is used to fetch the correct scale word (thousand, million, billion) from the thousands array. For example:\n\n- `groupIndex = 0`: No scale word (ones place).\n- `groupIndex = 1`: \"Thousand\".\n- `groupIndex = 2`: \"Million\".\n- `groupIndex = 3`: \"Billion\".\n\nWe build the final result by concatenating the words for each chunk, starting from the least significant chunk and moving to the most significant. This ensures the correct placement of scale words and produces the final English representation of the entire number.\n\n#### Algorithm\n \n- Handle the special case where the number is zero by returning `\"Zero\"`.\n- Initialize arrays to store words for single digits, tens, and thousands:\n  - `ones` for numbers 1-19.\n  - `tens` for multiples of ten from 20-90.\n  - `thousands` for scales (`\"Thousand\"`, `\"Million\"`, `\"Billion\"`).\n- Process the number in chunks of 1000.\n  - Extract the last three digits of the number and handle hundreds, tens, and units:\n    - Handle hundreds place by adding the corresponding word from `ones` and `\"Hundred\"`.\n    - Handle tens and units place by combining the word from `tens` and `ones`.\n  - Append the scale (`\"Thousand\"`, `\"Million\"`, `\"Billion\"`) for the current group.\n  - Insert the group result at the beginning of the final result.\n- Move to the next chunk of 1000 by dividing the number by 1000.\n- Return the result after removing trailing spaces. \n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Zu9faq2G/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Zu9faq2G\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number.\n\n* Time complexity: $O(\\log_{10} N)$\n\n    $O(\\log_{10} N)$, because the number is divided by 1000 in each iteration, making the number of iterations proportional to the number of chunks, which is logarithmic.\n\n* Space complexity: $O(1)$\n\n    $O(1)$, constant space. The space used is independent of the number's size, as it involves only a few string builders and arrays.\n\n---\n\n### Approach 3: Pair-Based Approach\n\n#### Intuition\n\nIn the pair-based approach, we use a predefined list of numeric values and their corresponding English words to convert a number. We process the number by matching it against these pairs from largest to smallest, dividing the number, and converting each part recursively.\n\nWe start by defining a list of pairs where each pair consists of a numeric value and its English word, such as `1000000000` for \"Billion\", `1000000` for \"Million\", and down to `1` for \"One\". This list facilitates conversion by identifying which value fits into the current number.\n\nFor a number like `1234567`, we iterate through the list from the largest value to the smallest. We check if the number is greater than or equal to each value. If it is:\n- **Divide the Number**: Determine how many times the value fits into the number (the quotient) and calculate the remainder. For `1234567`, we match `1 Million`, resulting in \"One Million\", and then process the remainder (`234567`).\n- **Recursive Conversion**: Convert the quotient to words and recursively process the remainder using the same list of pairs.\n\nWe concatenate the word for the current pair with the results from the recursive call for the remainder. This process builds the final English word representation from the largest units (like billion) to the smallest (like one), ensuring an accurate representation of every part of the number.\n\n#### Algorithm\n\n- Initialize a pair `numberToWordsMap` that maps numeric values to their corresponding English words:\n  - Includes large scales (`\"Billion\"`, `\"Million\"`, `\"Thousand\"`, `\"Hundred\"`) and individual numbers (1-19, and multiples of ten from 20 to 90).\n\n- Handle the special case where the number is zero by returning `\"Zero\"`.\n\n- Call the function `numberToWords` to convert the number to English words:\n  - Iterate over the `numberToWordsMap`:\n    - For each pair `(value, word)` in `numberToWordsMap`, check if the number `num` is greater than or equal to `value`.\n      - If `num` is greater than or equal to `value`:\n        - Compute the `prefix`:\n          - If `num` is 100 or greater, recursively convert the quotient (`num / value`) to words and append `\" \"` (a space). If `num` is less than 100, set `prefix` to an empty string.\n        - Get the `unit` as the current `word` from `numberToWordsMap`.\n        - Compute the `suffix`:\n          - If the remainder (`num % value`) is zero, set `suffix` to an empty string. Otherwise, recursively convert the remainder to words and prepend `\" \"` (a space).\n        - Return the combined result: `prefix + unit + suffix`.\n\n- If the number is not zero, the function will return the complete English representation by combining the `prefix`, `unit`, and `suffix`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/KJL7Kbac/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"KJL7Kbac\"></iframe>\n\n#### Complexity Analysis\n\nLet $K$ be the number of pairs in `numberToWordsMap` and $N$ be the number.\n\n- Time complexity: $O(K)$\n\n    The time complexity is $O(K)$ because the loop iterates through the pairs until it finds a match. This complexity is linear with respect to the number of pairs, which is constant in practice as the number of pairs is fixed.\n\n- Space complexity: $O(\\log_{10} N)$\n\n    $O(\\log_{10} N)$, mainly due to the recursion stack in the `convert` function. The space used is proportional to the number of recursive calls made.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numberToWords(self, num: int) -> str:\n    if num == 0:\n      return \"Zero\"\n\n    belowTwenty = [\"\",        \"One\",       \"Two\",      \"Three\",\n                   \"Four\",    \"Five\",      \"Six\",      \"Seven\",\n                   \"Eight\",   \"Nine\",      \"Ten\",      \"Eleven\",\n                   \"Twelve\",  \"Thirteen\",  \"Fourteen\", \"Fifteen\",\n                   \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"]\n    tens = [\"\",      \"Ten\",   \"Twenty\",  \"Thirty\", \"Forty\",\n            \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"]\n\n    def helper(num: int) -> str:\n      if num < 20:\n        s = belowTwenty[num]\n      elif num < 100:\n        s = tens[num // 10] + \" \" + belowTwenty[num % 10]\n      elif num < 1000:\n        s = helper(num // 100) + \" Hundred \" + helper(num % 100)\n      elif num < 1000000:\n        s = helper(num // 1000) + \" Thousand \" + helper(num % 1000)\n      elif num < 1000000000:\n        s = helper(num // 1000000) + \" Million \" + \\\n            helper(num % 1000000)\n      else:\n        s = helper(num // 1000000000) + \" Billion \" + \\\n            helper(num % 1000000000)\n\n      return s.strip()\n\n    return helper(num)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String numberToWords(int num) {\n    return num == 0 ? \"Zero\" : helper(num);\n  }\n\n  private final String[] belowTwenty = {\"\",        \"One\",     \"Two\",       \"Three\",    \"Four\",\n                                        \"Five\",    \"Six\",     \"Seven\",     \"Eight\",    \"Nine\",\n                                        \"Ten\",     \"Eleven\",  \"Twelve\",    \"Thirteen\", \"Fourteen\",\n                                        \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n  private final String[] tens = {\"\",      \"\",      \"Twenty\",  \"Thirty\", \"Forty\",\n                                 \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"};\n\n  private String helper(int num) {\n    StringBuilder s = new StringBuilder();\n\n    if (num < 20)\n      s.append(belowTwenty[num]);\n    else if (num < 100)\n      s.append(tens[num / 10]).append(\" \").append(belowTwenty[num % 10]);\n    else if (num < 1000)\n      s.append(helper(num / 100)).append(\" Hundred \").append(helper(num % 100));\n    else if (num < 1000000)\n      s.append(helper(num / 1000)).append(\" Thousand \").append(helper(num % 1000));\n    else if (num < 1000000000)\n      s.append(helper(num / 1000000)).append(\" Million \").append(helper(num % 1000000));\n    else\n      s.append(helper(num / 1000000000)).append(\" Billion \").append(helper(num % 1000000000));\n\n    return s.toString().trim();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string numberToWords(int num) {\n    if (num == 0)\n      return \"Zero\";\n    return helper(num);\n  }\n\n private:\n  const vector<string> belowTwenty{\n      \"\",        \"One\",     \"Two\",       \"Three\",    \"Four\",\n      \"Five\",    \"Six\",     \"Seven\",     \"Eight\",    \"Nine\",\n      \"Ten\",     \"Eleven\",  \"Twelve\",    \"Thirteen\", \"Fourteen\",\n      \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eighteen\", \"Nineteen\"};\n  const vector<string> tens{\"\",      \"\",      \"Twenty\",  \"Thirty\", \"Forty\",\n                            \"Fifty\", \"Sixty\", \"Seventy\", \"Eighty\", \"Ninety\"};\n\n  string helper(int num) {\n    string s;\n\n    if (num < 20)\n      s = belowTwenty.at(num);\n    else if (num < 100)\n      s = tens.at(num / 10) + \" \" + belowTwenty.at(num % 10);\n    else if (num < 1000)\n      s = helper(num / 100) + \" Hundred \" + helper(num % 100);\n    else if (num < 1000000)\n      s = helper(num / 1000) + \" Thousand \" + helper(num % 1000);\n    else if (num < 1000000000)\n      s = helper(num / 1000000) + \" Million \" + helper(num % 1000000);\n    else\n      s = helper(num / 1000000000) + \" Billion \" + helper(num % 1000000000);\n\n    trim(s);\n    return s;\n  }\n\n  void trim(string& s) {\n    s.erase(0, s.find_first_not_of(' '));\n    s.erase(s.find_last_not_of(' ') + 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/273.html",
    "category": "Algorithms",
    "acceptance_rate": 34.308903519695505,
    "topics": [
      "Math",
      "String",
      "Recursion"
    ],
    "hints": [
      "Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000.",
      "Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words.",
      "There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)"
    ],
    "likes": 3726,
    "dislikes": 6789,
    "similar_questions": "[{\"title\": \"Integer to Roman\", \"titleSlug\": \"integer-to-roman\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"541.4K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 541374, \"totalSubmissionRaw\": 1577941, \"acRate\": \"34.3%\"}",
    "title_pt": "Inteiro para Palavras em Inglês",
    "description_pt": "<p>Converta um inteiro não negativo <code>num</code> para sua representação por palavras em inglês.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 123\n<strong>Saída:</strong> &quot;One Hundred Twenty Three&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 12345\n<strong>Saída:</strong> &quot;Twelve Thousand Three Hundred Forty Five&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 1234567\n<strong>Saída:</strong> &quot;One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Você percebeu um padrão ao dividir o número em blocos de palavras? Por exemplo, 123 e 123000.",
      "Dica 2: Agrupe o número por milhares (3 dígitos). Você pode লিখ?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "274",
    "paidOnly": false,
    "title": "H-Index",
    "titleSlug": "h-index",
    "url": "https://leetcode.com/problems/h-index",
    "description_url": "https://leetcode.com/problems/h-index/description/",
    "description": "<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper, return <em>the researcher&#39;s h-index</em>.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/H-index\" target=\"_blank\">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> citations = [3,0,6,1,5]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> citations = [1,3,1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == citations.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>0 &lt;= citations[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/h-index/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def hIndex(self, citations: List[int]) -> int:\n    n = len(citations)\n    accumulate = 0\n    count = [0] * (n + 1)\n\n    for citation in citations:\n      count[min(citation, n)] += 1\n\n    # To find the largeset h-index, loop from back to front\n    # I is the candidate h-index\n    for i, c in reversed(list(enumerate(count))):\n      accumulate += c\n      if accumulate >= i:\n        return i",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int hIndex(int[] citations) {\n    final int n = citations.length;\n    int accumulate = 0;\n    int[] count = new int[n + 1];\n\n    for (final int citation : citations)\n      ++count[Math.min(citation, n)];\n\n    // To find the largeset h-index, loop from back to front\n    // I is the candidate h-index\n    for (int i = n; i >= 0; --i) {\n      accumulate += count[i];\n      if (accumulate >= i)\n        return i;\n    }\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int hIndex(vector<int>& citations) {\n    const int n = citations.size();\n    int accumulate = 0;\n    vector<int> count(n + 1);\n\n    for (const int citation : citations)\n      ++count[min(citation, n)];\n\n    // To find the largeset h-index, loop from back to front\n    // I is the candidate h-index\n    for (int i = n; i >= 0; --i) {\n      accumulate += count[i];\n      if (accumulate >= i)\n        return i;\n    }\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/274.html",
    "category": "Algorithms",
    "acceptance_rate": 40.17701043399621,
    "topics": [
      "Array",
      "Sorting",
      "Counting Sort"
    ],
    "hints": [
      "An easy approach is to sort the array first.",
      "What are the possible values of h-index?",
      "A faster approach is to use extra space."
    ],
    "likes": 1643,
    "dislikes": 785,
    "similar_questions": "[{\"title\": \"H-Index II\", \"titleSlug\": \"h-index-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"711.7K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 711702, \"totalSubmissionRaw\": 1771412, \"acRate\": \"40.2%\"}",
    "title_pt": "Índice h",
    "description_pt": "<p>Dado um array de inteiros <code>citations</code> em que <code>citations[i]</code> é o número de citações que um pesquisador recebeu por seu <code>i<sup>th</sup></code> artigo, retorne <em>o índice h do pesquisador</em>.</p>\n\n<p>De acordo com a <a href=\"https://en.wikipedia.org/wiki/H-index\" target=\"_blank\">definição de índice h na Wikipedia</a>: o índice h é definido como o valor máximo de <code>h</code> tal que o pesquisador dado publicou pelo menos <code>h</code> artigos que foram citados pelo menos <code>h</code> vezes cada um.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> citations = [3,0,6,1,5]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> [3,0,6,1,5] significa que o pesquisador tem 5 artigos no total e cada um deles recebeu, respectivamente, 3, 0, 6, 1, 5 citações.\nComo o pesquisador tem 3 artigos com pelo menos 3 citações cada e os dois restantes com no máximo 3 citações cada, seu índice h é 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> citations = [1,3,1]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == citations.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 5000</code></li>\n\t<li><code>0 &lt;= citations[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Uma abordagem fácil é ordenar o array primeiro.",
      "Dica 2: Quais são os possíveis valores do índice h?",
      "Dica 3: Uma abordagem mais rápida é usar espaço extra."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "275",
    "paidOnly": false,
    "title": "H-Index II",
    "titleSlug": "h-index-ii",
    "url": "https://leetcode.com/problems/h-index-ii",
    "description_url": "https://leetcode.com/problems/h-index-ii/description/",
    "description": "<p>Given an array of integers <code>citations</code> where <code>citations[i]</code> is the number of citations a researcher received for their <code>i<sup>th</sup></code> paper and <code>citations</code> is sorted in <strong>non-descending order</strong>, return <em>the researcher&#39;s h-index</em>.</p>\n\n<p>According to the <a href=\"https://en.wikipedia.org/wiki/H-index\" target=\"_blank\">definition of h-index on Wikipedia</a>: The h-index is defined as the maximum value of <code>h</code> such that the given researcher has published at least <code>h</code> papers that have each been cited at least <code>h</code> times.</p>\n\n<p>You must write an algorithm that runs in logarithmic time.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> citations = [0,1,3,5,6]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> citations = [1,2,100]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == citations.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= citations[i] &lt;= 1000</code></li>\n\t<li><code>citations</code> is sorted in <strong>ascending order</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/h-index-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def hIndex(self, citations: List[int]) -> int:\n    l = 0\n    r = len(citations)\n\n    while l < r:\n      m = (l + r) // 2\n      if citations[m] >= len(citations) - m:\n        r = m\n      else:\n        l = m + 1\n\n    return len(citations) - l",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int hIndex(int[] citations) {\n    int l = 0;\n    int r = citations.length;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (citations[m] >= citations.length - m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return citations.length - l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int hIndex(vector<int>& citations) {\n    int l = 0;\n    int r = citations.size();\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (citations[m] >= citations.size() - m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return citations.size() - l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/275.html",
    "category": "Algorithms",
    "acceptance_rate": 38.7823366149979,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [
      "Expected runtime complexity is in <i>O</i>(log <i>n</i>) and the input is sorted."
    ],
    "likes": 444,
    "dislikes": 128,
    "similar_questions": "[{\"title\": \"H-Index\", \"titleSlug\": \"h-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"237K\", \"totalSubmission\": \"611.1K\", \"totalAcceptedRaw\": 236982, \"totalSubmissionRaw\": 611063, \"acRate\": \"38.8%\"}",
    "title_pt": "H-Index II",
    "description_pt": "<p>Dado um array de inteiros <code>citations</code> em que <code>citations[i]</code> é o número de citações que um pesquisador recebeu por seu <code>i<sup>th</sup></code> artigo e <code>citations</code> está ordenado em <strong>ordem não decrescente</strong>, retorne <em>o h-index do pesquisador</em>.</p>\n\n<p>De acordo com a <a href=\"https://en.wikipedia.org/wiki/H-index\" target=\"_blank\">definição de h-index na Wikipedia</a>: o h-index é definido como o valor máximo de <code>h</code> tal que o pesquisador dado publicou pelo menos <code>h</code> artigos, sendo que cada um deles foi citado pelo menos <code>h</code> vezes.</p>\n\n<p>Você deve escrever um algoritmo que execute em tempo logarítmico.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> citations = [0,1,3,5,6]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> [0,1,3,5,6] significa que o pesquisador tem 5 artigos no total e cada um deles recebeu, respectivamente, 0, 1, 3, 5, 6 citações.\nComo o pesquisador tem 3 artigos com pelo menos 3 citações cada e os dois restantes com no máximo 3 citações cada, seu h-index é 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> citations = [1,2,100]\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == citations.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= citations[i] &lt;= 1000</code></li>\n\t<li><code>citations</code> está ordenado em <strong>ordem crescente</strong>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: A complexidade de tempo esperada é <i>O</i>(log <i>n</i>) e a entrada está ordenada."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "278",
    "paidOnly": false,
    "title": "First Bad Version",
    "titleSlug": "first-bad-version",
    "url": "https://leetcode.com/problems/first-bad-version",
    "description_url": "https://leetcode.com/problems/first-bad-version/description/",
    "description": "<p>You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.</p>\n\n<p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p>\n\n<p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 5, bad = 4\n<strong>Output:</strong> 4\n<strong>Explanation:</strong>\ncall isBadVersion(3) -&gt; false\ncall isBadVersion(5)&nbsp;-&gt; true\ncall isBadVersion(4)&nbsp;-&gt; true\nThen 4 is the first bad version.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, bad = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/first-bad-version/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def firstBadVersion(self, n: int) -> int:\n    l = 1\n    r = n\n\n    while l < r:\n      m = (l + r) >> 1\n      if isBadVersion(m):\n        r = m\n      else:\n        l = m + 1\n\n    return l",
    "solution_code_java": "\t\t\t\n\npublic class Solution extends VersionControl {\n  public int firstBadVersion(int n) {\n    int l = 1;\n    int r = n;\n\n    while (l < r) {\n      final int m = l + (r - l) / 2;\n      if (isBadVersion(m))\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nbool isBadVersion(int version);\n\nclass Solution {\n public:\n  int firstBadVersion(int n) {\n    int l = 1;\n    int r = n;\n\n    while (l < r) {\n      const int m = l + (r - l) / 2;\n      if (isBadVersion(m))\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/278.html",
    "category": "Algorithms",
    "acceptance_rate": 45.799417473000446,
    "topics": [
      "Binary Search",
      "Interactive"
    ],
    "hints": [],
    "likes": 8678,
    "dislikes": 3373,
    "similar_questions": "[{\"title\": \"Find First and Last Position of Element in Sorted Array\", \"titleSlug\": \"find-first-and-last-position-of-element-in-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Search Insert Position\", \"titleSlug\": \"search-insert-position\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Guess Number Higher or Lower\", \"titleSlug\": \"guess-number-higher-or-lower\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 1923565, \"totalSubmissionRaw\": 4199977, \"acRate\": \"45.8%\"}",
    "title_pt": "Primeira Versão Ruim",
    "description_pt": "<p>Você é um gerente de produto e atualmente lidera uma equipe para desenvolver um novo produto. Infelizmente, a versão mais recente do seu produto falha na verificação de qualidade. Como cada versão é desenvolvida com base na versão anterior, todas as versões após uma versão ruim também são ruins.</p>\n\n<p>Suponha que você tenha <code>n</code> versões <code>[1, 2, ..., n]</code> e queira descobrir qual é a primeira ruim, que faz com que todas as seguintes também sejam ruins.</p>\n\n<p>Você recebe uma API <code>bool isBadVersion(version)</code> que retorna se a <code>version</code> é ruim. Implemente uma função para encontrar a primeira versão ruim. Você deve minimizar o número de chamadas à API.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 5, bad = 4\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong>\ncall isBadVersion(3) -&gt; false\ncall isBadVersion(5)&nbsp;-&gt; true\ncall isBadVersion(4)&nbsp;-&gt; true\nThen 4 is the first bad version.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, bad = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "279",
    "paidOnly": false,
    "title": "Perfect Squares",
    "titleSlug": "perfect-squares",
    "url": "https://leetcode.com/problems/perfect-squares",
    "description_url": "https://leetcode.com/problems/perfect-squares/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p>\n\n<p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 12\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 12 = 4 + 4 + 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 13\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> 13 = 4 + 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/perfect-squares/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numSquares(self, n: int) -> int:\n    dp = [n] * (n + 1)\n\n    dp[0] = 0\n    dp[1] = 1\n\n    for i in range(2, n + 1):\n      j = 1\n      while j * j <= i:\n        dp[i] = min(dp[i], dp[i - j * j] + 1)\n        j += 1\n\n    return dp[n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numSquares(int n) {\n    int[] dp = new int[n + 1];\n    Arrays.fill(dp, n); // 1^2 x n\n\n    dp[0] = 0; // No way\n    dp[1] = 1; // 1^2\n\n    for (int i = 2; i <= n; ++i)\n      for (int j = 1; j * j <= i; ++j)\n        dp[i] = Math.min(dp[i], dp[i - j * j] + 1);\n\n    return dp[n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numSquares(int n) {\n    vector<int> dp(n + 1, n);  // 1^2 x n\n\n    dp[0] = 0;  // No way\n    dp[1] = 1;  // 1^2\n\n    for (int i = 2; i <= n; ++i)\n      for (int j = 1; j * j <= i; ++j)\n        dp[i] = min(dp[i], dp[i - j * j] + 1);\n\n    return dp[n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/279.html",
    "category": "Algorithms",
    "acceptance_rate": 55.58919361354944,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 11506,
    "dislikes": 482,
    "similar_questions": "[{\"title\": \"Count Primes\", \"titleSlug\": \"count-primes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ugly Number II\", \"titleSlug\": \"ugly-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ways to Express an Integer as Sum of Powers\", \"titleSlug\": \"ways-to-express-an-integer-as-sum-of-powers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"953.5K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 953529, \"totalSubmissionRaw\": 1715316, \"acRate\": \"55.6%\"}",
    "title_pt": "Quadrados Perfeitos",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>o menor número de números quadrados perfeitos cuja soma seja</em> <code>n</code>.</p>\n\n<p>Um <strong>quadrado perfeito</strong> é um inteiro que é o quadrado de um inteiro; em outras palavras, é o produto de algum inteiro por ele mesmo. Por exemplo, <code>1</code>, <code>4</code>, <code>9</code> e <code>16</code> são quadrados perfeitos, enquanto <code>3</code> e <code>11</code> não são.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 12\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> 12 = 4 + 4 + 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 13\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> 13 = 4 + 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "282",
    "paidOnly": false,
    "title": "Expression Add Operators",
    "titleSlug": "expression-add-operators",
    "url": "https://leetcode.com/problems/expression-add-operators",
    "description_url": "https://leetcode.com/problems/expression-add-operators/description/",
    "description": "<p>Given a string <code>num</code> that contains only digits and an integer <code>target</code>, return <em><strong>all possibilities</strong> to insert the binary operators </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em>, and/or </em><code>&#39;*&#39;</code><em> between the digits of </em><code>num</code><em> so that the resultant expression evaluates to the </em><code>target</code><em> value</em>.</p>\n\n<p>Note that operands in the returned expressions <strong>should not</strong> contain leading zeros.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;123&quot;, target = 6\n<strong>Output:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;]\n<strong>Explanation:</strong> Both &quot;1*2*3&quot; and &quot;1+2+3&quot; evaluate to 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;232&quot;, target = 8\n<strong>Output:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;]\n<strong>Explanation:</strong> Both &quot;2*3+2&quot; and &quot;2+3*2&quot; evaluate to 8.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;3456237490&quot;, target = 9191\n<strong>Output:</strong> []\n<strong>Explanation:</strong> There are no expressions that can be created from &quot;3456237490&quot; to evaluate to 9191.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num.length &lt;= 10</code></li>\n\t<li><code>num</code> consists of only digits.</li>\n\t<li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/expression-add-operators/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n\n### Approach 1: Backtracking\n\n**Intuition**\n\nLet us first look at what the question asks us to do before getting at the approach to solve it. So, we are given a string of numbers and 3 different operators:\n\n* `+` Addition,\n* `-` Subtraction or\n* `*` Multiplication\n\nWe have to find all possible combinations of binary operators between the digits so that the overall value of the resulting expression becomes equal to a given target value. Let us look at a few possibilities of what it means exactly to *place the operators between digits* so that the question becomes clearer.\n\nLet's say we are given the following set of digits `\"123456789\"` and the target value given to us is `45`. Let us see some of the possible resulting expressions that we can get by placing the operators in different locations.\n\n<pre>\n1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45\n1 + 2 - 3 + 4 - 5 + 6 - 7 + 8 - 9 = -3\n1 + 2 * 3 - 4 + 5 + 6 - 7 * 8 - 9 = -51\n1 + 2 + 3 + 4 + 5 - 6 * 7 + 8 * 9 = 45\n</pre>\n\nThese are just 4 of the many resulting expressions that are possible by using the given string of digits and the three operators.\n\nBy looking at the above examples we can't really figure out any specific pattern among the resulting expressions that tells us which of them will give us the resulting target.\n\nSince the question explicitly states that we are given binary operators, this means that each of the operator would require two operands.\n\n> We can consider each of our digits as an operand.\n\nThis means that between every pair of digits we can have any of the three operators i.e. $$+$$, $$-$$ or $$\\times$$.\n\nIf you've looked at the question's statement and the examples that are given in the question, you would realize that there is an example where the digits are `\"105\"` and the target value is `5`. For this particular example, there are two expressions given to us and they are `1*0+5` and `10-5`.\n\nThe second expression is something that you need to look out for before getting to solve this question because this complicates things a bit.\n\nIt would have been an easier question to solve if we just had to consider those expressions that simply had *digits as operands*.\n\nBut, in this question, we can have all sorts of digits getting together and forming a bigger number that becomes a part of the expression. Let us look at some example expressions for the digits `\"123456\"` and target `30`.\n\n<pre>\n1 * 23 - 4 + 5 + 6 = 30\n12 - 3 * 4 + 5 * 6 = 30\n1 - 23 - 4 + 56 = 30\n</pre>\n\nSo this means that although the number of operators are defined for us i.e. 3 different binary operators, but the number of operands are **not really well defined for us**.\n\nThis is a big portion of the original problem that we need to address in our solution.\n\nSince we are asked to find out all of the valid expressions whose value equals the given target and we don't really know what specific operator between two operands would eventually give us a valid expression,\n\n> We try out all of the options.\n\nThis means once we have defined what the operands are for our given expression, we would have three possible choices of operators between each consecutive pair of operands.\n\nFrom an implementation perspective, what would an operand imply with respect to our original string?\n\n> An operand would be an integer formed from a substring of our original string.\n\nLet's look at two different array partitions for the given string `\"123456789\"`\n\n<center>\n<img src=\"../Figures/282/282_Expression_Add_Operators_Diag_1.png\" height=\"300\"></center>\n\nSince we are required to return all of the valid expressions that evaluate to a given target value, we have to try all possible partitions of the given array thereby considering all of the possible operands that can be formed from the digits.\n\nThere is a very simple way of incorporating this into our algorithm. Right now, at every point in the algorithm, we have three different choices corresponding to the three different operators.\n\n>The way we incorporate these partitions is by considering a 4th operator as well which simply moves one step forward and extends the current operand by one digit. Essentially, going from 12 --> 123 is a NO OP operand in our implementation. (12 * 10) + 3.\n\nNow we have 4 different recursion paths in our algorithm and we have to try out all of them to see which ones lead to a potential solution.\n\nThis `try out everything` hints at a backtracking solution and that is exactly what we are going to look at here.\n\n**Algorithm**\n\nLet's quickly look at the steps involved in our backtracking algorithm before looking at the pseudo-code.\n\n1. As discussed above, we have multiple choices of what operators to use and what the operands can be and hence, we have to look at all the possibilities to find ***all*** valid expressions.\n2. Our recursive call will have an `index` which represents the current digit we're looking at in the original `nums` string and also the expression string built till now.\n3. At every step, we have exactly 4 different recursive calls. The `NO OP` call simply extends the `current_operand` by the current digit and moves ahead. Rest of the recursive calls correspond to `+`, `-`, and `*`.\n4. We keep on building our expression like this and eventually, the entire `nums` string would be processed. At that time we check if the expression we built till now is a valid expression or not and we record it if it is a valid one.\n\n<pre>\n1. procedure recurse(digits, index, expression):\n2.     if we have reached the end of the string:\n3.         if the expression evaluates to the target:\n4.             Valid Expression found!\n5.     else:\n6.         try out operator 'NO OP' and recurse\n7.         try out operator * and recurse\n8.         try out operator + and recurse\n9.         try out operator - and recurse\n</pre>\n\nThe algorithm now looks pretty straightforward. However, the implementation is something that needs more thought and there are some things that we need to address before actually looking at the implementation.\n\nWhen we are done building an expression out of all of the digits in our original string i.e. the base case, then we check if the expression is a valid expression or not. Right ?\n\n> How do we actually check if an expression is a valid one or not if all we have is a string representing the expression and not the integer value for the same?\n\nWell, one way to go about this is to write a custom `eval` function that takes in a string and returns the value of that expression. If you do that (Python people can use the inbuilt function `eval` for this), you will get a TLE i.e. time limit exceeded error.\n\n<br/>\n\n**Can't we keep track of the expression's value on the fly?**\n\nWell yes. That's the idea we will go with. Instead of just keeping track of what the expression string is, we will also keep track of it's value along the way so that when the recursion hits the base case, we can check in $$O(1)$$ time if the expression's value equals the target value or not.\n\nThe implementation would have been straightforward had it just been `+` and `-` operators involved. This is because both these operators have an equal precedence. That means that we can continue to evaluate the expression on the fly without any problems. Have a look at the following example.\n\n<center>\n<img src=\"../Figures/282/282_Expression_Add_Operators_Diag_2.png\" width=\"550\"></center>\n\nSo far so good. Now let us add the `*` operator as well and see how building the expression on the fly like this breaks.\n\n<center>\n<img src=\"../Figures/282/282_Expression_Add_Operators_Diag_3.png\" width=\"550\"></center>\n\nWhat we mean by building the expression on the fly is that we keep track of the expression's value till now and we simply consider that value as one of the two operands for our operators. As we can see from the two examples above, this would have worked had it just been `+` and `-` operators.\n\nBut, this approach is bound to fail because the `*` operator takes precedence over `+` and `-`. The `*` operator would require the ***actual*** previous operand in our expression rather than the current value of the expression. i.e. In the above example, the `*` operator needed `2` rather than `12` to get us the correct value of `18`.\n\n<br/>\n\n**How to handle this?**\n\nThe idea on how to handle this problem springs from the discussion above. We simply need to keep track of the last operand in our expression and how it modified the expression's value overall so that when we consider the `*` operator, we can **reverse** the effects of the previous operand and consider it for multiplication. Let's take a look at the example that was breaking before.\n\n<center>\n<img src=\"../Figures/282/282_Expression_Add_Operators_Diag_4.png\" width=\"550\"></center>\n\nNow we can look at the actual implementation of this algorithm.\n\n<iframe src=\"https://leetcode.com/playground/X7CmRa6U/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"X7CmRa6U\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity:\n    * At every step along the way, we consider exactly 4 different choices or 4 different recursive paths. The base case is when the value of `index` reaches $$N$$ i.e. the length of the `nums` array. Hence, our complexity would be $$O(4^N)$$.\n    * For the base case we use a `StringBuilder::toString` operation in Java and `.join()` operation in Python and that takes $$O(N)$$ time. Here $$N$$ represents the length of our expression. In the worst case, each digit would be an operand and we would have $$N$$ digits and $$N - 1$$ operators. So $$O(N)$$. This is for one expression. In the worst case, we can have $$O(4^N)$$ valid expressions.\n    * Overall time complexity = $$O(N \\times 4^N)$$.\n\n* Space Complexity:\n    * For both Python and Java implementations we have a list data structure that we update on the fly and only for valid expressions do we create a new string and add to our `answers` array. So, the space occupied by the intermediate list would be $$O(N)$$ since in the worst case the expression would be built out of all the digits as operands.\n    * Additionally, the space used up by the recursion stack would also be $$O(N)$$ since the size of recursion stack is determined by the value of `index` and it goes from $$0$$ all the way to $$N$$.\n    * We don't consider the space occupied by the `answers` array since that is a part of the question's requirement and we can't reduce that in any way\n\n**EDIT:**\nThe previous implementation of the algorithm, although correct, lead me to write an incorrect complexity analysis section. I've re-written the algorithm from scratch and corrected the complexity analysis as well. Sorry for the inconvenience to all the readers. The core idea of the algorithm is still the same. That hasn't changed.\n\nSpecial thanks to [@ufarooqi](https://leetcode.com/ufarooqi/), [@vortexwolf](https://leetcode.com/vortexwolf) for providing correct complexity analysis in the discussion forum leading to corrections in the article. Pardon me if I've missed out on any other names :)\n\n<br />",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addOperators(self, num: str, target: int) -> List[str]:\n    ans = []\n\n    # Start index, prev value, current evaluated value\n    def dfs(start: int, prev: int, eval: int, path: List[str]) -> None:\n      if start == len(num):\n        if eval == target:\n          ans.append(''.join(path))\n        return\n\n      for i in range(start, len(num)):\n        if i > start and num[start] == '0':\n          return\n        s = num[start:i + 1]\n        curr = int(s)\n        if start == 0:\n          path.append(s)\n          dfs(i + 1, curr, curr, path)\n          path.pop()\n        else:\n          for op in ['+', '-', '*']:\n            path.append(op + s)\n            if op == '+':\n              dfs(i + 1, curr, eval + curr, path)\n            elif op == '-':\n              dfs(i + 1, -curr, eval - curr, path)\n            else:\n              dfs(i + 1, prev * curr, eval - prev + prev * curr, path)\n            path.pop()\n\n    dfs(0, 0, 0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> addOperators(String num, int target) {\n    List<String> ans = new ArrayList<>();\n    dfs(num, target, 0, 0, 0, new StringBuilder(), ans);\n    return ans;\n  }\n\n  private void dfs(String num, int target, int s, long prev, long eval, StringBuilder sb,\n                   List<String> ans) {\n    if (s == num.length()) {\n      if (eval == target)\n        ans.add(sb.toString());\n      return;\n    }\n\n    for (int i = s; i < num.length(); ++i) {\n      if (i > s && num.charAt(s) == '0')\n        return;\n      final long curr = Long.parseLong(num.substring(s, i + 1));\n      final int length = sb.length();\n      if (s == 0) { // First num\n        dfs(num, target, i + 1, curr, curr, sb.append(curr), ans);\n        sb.setLength(length);\n      } else {\n        dfs(num, target, i + 1, curr, eval + curr, sb.append(\"+\").append(curr), ans);\n        sb.setLength(length);\n        dfs(num, target, i + 1, -curr, eval - curr, sb.append(\"-\").append(curr), ans);\n        sb.setLength(length);\n        dfs(num, target, i + 1, prev * curr, eval - prev + prev * curr, sb.append(\"*\").append(curr),\n            ans);\n        sb.setLength(length);\n      }\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> addOperators(string num, int target) {\n    vector<string> ans;\n    dfs(num, target, 0, 0, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  string join(const vector<string>& path) {\n    string joined;\n    for (const string& s : path)\n      joined += s;\n    return joined;\n  }\n\n  // Start index, prev value, current evaluated value\n  void dfs(const string& num, int target, int start, long prev, long eval,\n           vector<string>&& path, vector<string>& ans) {\n    if (start == num.length()) {\n      if (eval == target)\n        ans.push_back(join(path));\n      return;\n    }\n\n    for (int i = start; i < num.length(); ++i) {\n      if (i > start && num[start] == '0')\n        return;\n      const string& s = num.substr(start, i - start + 1);\n      const long curr = stol(s);\n      if (start == 0) {\n        path.push_back(s);\n        dfs(num, target, i + 1, curr, curr, move(path), ans);\n        path.pop_back();\n      } else {\n        for (const string& op : {\"+\", \"-\", \"*\"}) {\n          path.push_back(op + s);\n          if (op == \"+\")\n            dfs(num, target, i + 1, curr, eval + curr, move(path), ans);\n          else if (op == \"-\")\n            dfs(num, target, i + 1, -curr, eval - curr, move(path), ans);\n          else\n            dfs(num, target, i + 1, prev * curr, eval - prev + prev * curr,\n                move(path), ans);\n          path.pop_back();\n        }\n      }\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/282.html",
    "category": "Algorithms",
    "acceptance_rate": 41.48755823201909,
    "topics": [
      "Math",
      "String",
      "Backtracking"
    ],
    "hints": [
      "Note that a number can contain multiple digits.",
      "Since the question asks us to find <b>all</b> of the valid expressions, we need a way to iterate over all of them. (<b>Hint:</b> Recursion!)",
      "We can keep track of the expression string and evaluate it at the very end. But that would take a lot of time. Can we keep track of the expression's value as well so as to avoid the evaluation at the very end of recursion?",
      "Think carefully about the multiply operator. It has a higher precedence than the addition and subtraction operators. \r\n\r\n<br> 1 + 2 = 3  <br>\r\n1 + 2 - 4 --> 3 - 4 --> -1 <br>\r\n1 + 2 - 4 * 12 --> -1 * 12 --> -12 (WRONG!) <br>\r\n1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRECT!)",
      "We simply need to keep track of the last operand in our expression and reverse it's effect on the expression's value while considering the multiply operator."
    ],
    "likes": 3576,
    "dislikes": 681,
    "similar_questions": "[{\"title\": \"Evaluate Reverse Polish Notation\", \"titleSlug\": \"evaluate-reverse-polish-notation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator\", \"titleSlug\": \"basic-calculator\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Basic Calculator II\", \"titleSlug\": \"basic-calculator-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Different Ways to Add Parentheses\", \"titleSlug\": \"different-ways-to-add-parentheses\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Target Sum\", \"titleSlug\": \"target-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"273.8K\", \"totalSubmission\": \"660.1K\", \"totalAcceptedRaw\": 273848, \"totalSubmissionRaw\": 660074, \"acRate\": \"41.5%\"}",
    "title_pt": "Adicionar Operadores à Expressão",
    "description_pt": "<p>Dada uma string <code>num</code> que contém apenas dígitos e um inteiro <code>target</code>, retorne <em><strong>todas as possibilidades</strong> de inserir os operadores binários </em><code>&#39;+&#39;</code><em>, </em><code>&#39;-&#39;</code><em> e/ou </em><code>&#39;*&#39;</code><em> entre os dígitos de </em><code>num</code><em> de modo que a expressão resultante seja avaliada para o valor de </em><code>target</code><em></em>.</p>\n\n<p>Observe que os operandos nas expressões retornadas <strong>não devem</strong> conter zeros à esquerda.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;123&quot;, target = 6\n<strong>Saída:</strong> [&quot;1*2*3&quot;,&quot;1+2+3&quot;]\n<strong>Explicação:</strong> Tanto &quot;1*2*3&quot; quanto &quot;1+2+3&quot; são avaliadas para 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;232&quot;, target = 8\n<strong>Saída:</strong> [&quot;2*3+2&quot;,&quot;2+3*2&quot;]\n<strong>Explicação:</strong> Tanto &quot;2*3+2&quot; quanto &quot;2+3*2&quot; são avaliadas para 8.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;3456237490&quot;, target = 9191\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> Não há expressões que possam ser criadas a partir de &quot;3456237490&quot; para serem avaliadas para 9191.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num.length &lt;= 10</code></li>\n\t<li><code>num</code> consiste apenas de dígitos.</li>\n\t<li><code>-2<sup>31</sup> &lt;= target &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Observe que um número pode conter vários dígitos.",
      "- Dica 2: Como a questão pede para encontrarmos <b>todas</b> as expressões válidas, precisamos de uma maneira de iterar sobre todas elas. (<b>Dica:</b> Recursão!)",
      "- Dica 3: Podemos manter o controle da string da expressão e avaliá-la apenas no final. Mas isso levaria muito tempo. Podemos manter o controle do valor da expressão também para evitar a avaliação no final da recursão?",
      "- Dica 4: Pense cuidadosamente sobre o operador de multiplicação. Ele tem precedência mais alta do que os operadores de adição e subtração. \n\n<br> 1 + 2 = 3  <br>\n1 + 2 - 4 --> 3 - 4 --> -1 <br>\n1 + 2 - 4 * 12 --> -1 * 12 --> -12 (ERRADO!) <br>\n1 + 2 - 4 * 12 --> -1 - (-4) + (-4 * 12) --> 3 + (-48) --> -45 (CORRETO!)",
      "- Dica 5: Precisamos apenas manter o controle do último operando em nossa expressão e reverter o seu efeito no valor da expressão ao considerar o operador de multiplicação."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "283",
    "paidOnly": false,
    "title": "Move Zeroes",
    "titleSlug": "move-zeroes",
    "url": "https://leetcode.com/problems/move-zeroes",
    "description_url": "https://leetcode.com/problems/move-zeroes/description/",
    "description": "<p>Given an integer array <code>nums</code>, move all <code>0</code>&#39;s to the end of it while maintaining the relative order of the non-zero elements.</p>\n\n<p><strong>Note</strong> that you must do this in-place without making a copy of the array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [0,1,0,3,12]\n<strong>Output:</strong> [1,3,12,0,0]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [0]\n<strong>Output:</strong> [0]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you minimize the total number of operations done?",
    "solution_url": "https://leetcode.com/problems/move-zeroes/solutions/",
    "solution": "[TOC]\n\n\n## Video Solution\n\n---\n <div class='video-preview'></div>\n\n## Solution\n---\n\nThis question comes under a broad category of \"Array Transformation\". This category is the meat of tech interviews. Mostly because arrays are such a simple and easy to use data structure. Traversal or representation doesn't require any boilerplate code and most of your code will look like the Pseudocode itself.\n\nThe 2 requirements of the question are:\n\n1. Move all the 0's to the end of array.\n\n2. All the non-zero elements must retain their original order.\n\nIt's good to realize here that both the requirements are mutually exclusive, i.e., you can solve the individual sub-problems and then combine them for the final solution.\n\n### Approach #1 (Space Sub-Optimal) [Accepted]\n\nTraverse the `nums` list first to count the number of zeroes. Then traverse the `nums` list again to store all non-zero elements in `ans`.\n\n#### Algorithm:\n\n- Determine the size of the `nums` array and store it in `n`.\n\n- Count the number of zeroes in `nums`:\n  - Initialize `numZeroes` to 0.\n  - Iterate through each element in `nums`:\n    - Increment `numZeroes` for each zero encountered.\n\n- Create a new vector `ans` to store non-zero elements in their original order:\n  - Iterate through each element in `nums`:\n    - Add non-zero elements to `ans`.\n\n- Append all zeroes to the end of the `ans` vector:\n  - Append `numZeroes` zeroes to `ans`.\n\n- Update the original `nums` array with the elements from `ans`:\n  - Copy each element from `ans` back to `nums`.\n\n\n<iframe src=\"https://leetcode.com/playground/ZftizFjx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ZftizFjx\"></iframe>\n\n**Complexity Analysis**\n\nSpace Complexity : $$O(n)$$. Since we are creating the \"ans\" array to store results.\n\nTime Complexity: $$O(n)$$. We traverse the nums list first to count the number of zeroes using $O(n)$ time. Then, we traverse the nums list again to store all non-zero elements in ans which also costs $O(n)$ time. Hence, the overall time complexity is $O(2n)$, which is simplified to $O(n)$. However, the total number of operations are sub-optimal. We can achieve the same result in less number of operations.\n\nIf asked in an interview, the above solution would be a good start. You can explain the interviewer(not code) the above and build your base for the next Optimal Solution.\n\n---\n### Approach #2 (Space Optimal, Operation Sub-Optimal) [Accepted]\n\nThis approach works the same way as above, i.e. , first fulfills one requirement and then another. The catch? It does it in a clever way. The above problem can also be stated in alternate way, \" Bring all the non 0 elements to the front of array keeping their relative order same\".\n\nThis is a 2 pointer approach. The fast pointer(`nums[i]`) does the job of processing new elements. If the newly found element is not a 0, we record it just after the last found non-0 element. The position of last found non-0 element is denoted by the slow pointer `lastNonZeroFoundAt` variable. As we keep finding new non-0 elements, we just overwrite them at the `lastNonZeroFoundAt + 1` 'th index. This overwrite will not result in any loss of data because we already processed what was there(if it were non-0,it already is now written at it's corresponding index,or if it were 0 it will be handled later in time).\n\nAfter the `nums[i]` reaches the end of array, we now know that all the non-0 elements have been moved to beginning of array in their original order. Now comes the time to fulfil other requirement, \"Move all 0's to the end\". We now simply need to fill all the indexes after the `lastNonZeroFoundAt` index with 0.\n\n#### Algorithm:\n\n- Initialize `lastNonZeroFoundAt` to 0:\n  - This variable tracks the position where the next non-zero element should be placed.\n\n- Iterate through each element in `nums`:\n  - If the current element `nums[i]` is not zero:\n    - Place `nums[i]` at index `lastNonZeroFoundAt`.\n    - Increment `lastNonZeroFoundAt` to move to the next position for future non-zero elements.\n\n- After processing all elements:\n  - Fill the remaining positions in the array (from `lastNonZeroFoundAt` to the end) with zeros.\n\n- This ensures that all non-zero elements are moved to the beginning of the array and all zeros are placed at the end.\n\n\n<iframe src=\"https://leetcode.com/playground/Vbpqu24K/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"Vbpqu24K\"></iframe>\n\n**Complexity Analysis**\n\nSpace Complexity : $$O(1)$$. Only constant space is used.\n\nTime Complexity: $$O(n)$$. We traverse the nums list first to move all non-zero elements to the beginning of array which costs $O(n)$ time. At the worst case when the original array only consists of 0s, we will use $O(n)$ time to fill all remaining elements with 0s. Hence, the overall time complexity is $O(2n)$, which is simplified to $O(n)$. However, the total number of operations are still sub-optimal. The total operations (array writes) that code does is $$n$$ (Total number of elements).\n\n---\n### Approach #3 (Optimal) [Accepted]\n\nThe total number of operations of the previous approach is sub-optimal. For example, the array which has all (except last) leading zeroes: [0, 0, 0, ..., 0, 1].How many write operations to the array? For the previous approach, it writes 0's $$n-1$$ times, which is not necessary. We could have instead written just once. How?\n.....\nBy only fixing the non-0 element,i.e., 1.\n\nThe optimal approach is again a subtle extension of above solution. A simple realization is if the current element is non-0, its' correct position can at best be it's current position or a position earlier. If it's the latter one, the current position will be eventually occupied by a non-0 ,or a 0, which lies at a index greater than 'cur' index. We fill the current position by 0 right away,so that unlike the previous solution, we don't need to come back here in next iteration.\n\nIn other words, the code will maintain the following invariant:\n\n>1. All elements before the slow pointer (lastNonZeroFoundAt) are non-zeroes.\n>\n>2. All elements between the current and slow pointer are zeroes.\n\nTherefore, when we encounter a non-zero element, we need to swap elements pointed by current and slow pointer, then advance both pointers. If it's zero element, we just advance current pointer.\n\nWith this invariant in-place, it's easy to see that the algorithm will work.\n\n#### Algorithm:\n\n- Initialize `lastNonZeroFoundAt` to 0 to track the position of the last non-zero element.\n- Iterate through each element in `nums` using `cur` as the index:\n  - If `nums[cur]` is not zero:\n    - Swap `nums[lastNonZeroFoundAt]` with `nums[cur]` to move the non-zero element to the correct position.\n    - Increment `lastNonZeroFoundAt` to update the position for the next non-zero element.\n\n- Continue iterating until all elements are processed, ensuring all non-zero elements are moved to the front of the array and zeros are pushed to the end.\n\n\n<iframe src=\"https://leetcode.com/playground/4YFvmDiq/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"4YFvmDiq\"></iframe>\n\n**Complexity Analysis**\n\nSpace Complexity : $$O(1)$$. Only constant space is used.\n\nTime Complexity: $$O(n)$$. However, the total number of operations are optimal. The total operations (array writes) that code does is Number of non-0 elements.This gives us a much better best-case (when most of the elements are 0) complexity than last solution. However, the worst-case (when all elements are non-0) complexity for both the algorithms is same.\n\nAnalysis written by: @spandan.pathak",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def moveZeroes(self, nums: List[int]) -> None:\n    j = 0\n    for num in nums:\n      if num != 0:\n        nums[j] = num\n        j += 1\n\n    for i in range(j, len(nums)):\n      nums[i] = 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void moveZeroes(int[] nums) {\n    int i = 0;\n    for (final int num : nums)\n      if (num != 0)\n        nums[i++] = num;\n\n    while (i < nums.length)\n      nums[i++] = 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void moveZeroes(vector<int>& nums) {\n    int i = 0;\n    for (const int num : nums)\n      if (num != 0)\n        nums[i++] = num;\n\n    while (i < nums.size())\n      nums[i++] = 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/283.html",
    "category": "Algorithms",
    "acceptance_rate": 62.72924906863825,
    "topics": [
      "Array",
      "Two Pointers"
    ],
    "hints": [
      "<b>In-place</b> means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually.",
      "A <b>two-pointer</b> approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array."
    ],
    "likes": 17835,
    "dislikes": 521,
    "similar_questions": "[{\"title\": \"Remove Element\", \"titleSlug\": \"remove-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Apply Operations to an Array\", \"titleSlug\": \"apply-operations-to-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"4M\", \"totalSubmission\": \"6.4M\", \"totalAcceptedRaw\": 3995487, \"totalSubmissionRaw\": 6369415, \"acRate\": \"62.7%\"}",
    "title_pt": "Mover Zeros",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, mova todos os <code>0</code>&#39;s para o final dele, mantendo a ordem relativa dos elementos não nulos.</p>\n\n<p><strong>Nota</strong> que você deve fazer isso in-place, sem criar uma cópia do array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [0,1,0,3,12]\n<strong>Saída:</strong> [1,3,12,0,0]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [0]\n<strong>Saída:</strong> [0]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria minimizar o número total de operações realizadas?",
    "hints_pt": [
      "Dica 1: <b>In-place</b> significa que não devemos alocar nenhum espaço para um array extra. Mas temos permissão para modificar o array existente. No entanto, como primeiro passo, tente encontrar uma solução que faça uso de espaço adicional. Para este problema também, primeiro aplique a ideia discutida usando um array adicional e a solução in-place acabará surgindo eventualmente.",
      "Dica 2: Uma abordagem de <b>dois ponteiros</b> pode ser útil aqui. A ideia seria ter um ponteiro para percorrer o array e outro ponteiro que trabalhe apenas sobre os elementos não nulos do array."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "284",
    "paidOnly": false,
    "title": "Peeking Iterator",
    "titleSlug": "peeking-iterator",
    "url": "https://leetcode.com/problems/peeking-iterator",
    "description_url": "https://leetcode.com/problems/peeking-iterator/description/",
    "description": "<p>Design an iterator that supports the <code>peek</code> operation on an existing iterator in addition to the <code>hasNext</code> and the <code>next</code> operations.</p>\n\n<p>Implement the <code>PeekingIterator</code> class:</p>\n\n<ul>\n\t<li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Initializes the object with the given integer iterator <code>iterator</code>.</li>\n\t<li><code>int next()</code> Returns the next element in the array and moves the pointer to the next element.</li>\n\t<li><code>boolean hasNext()</code> Returns <code>true</code> if there are still elements in the array.</li>\n\t<li><code>int peek()</code> Returns the next element in the array <strong>without</strong> moving the pointer.</li>\n</ul>\n\n<p><strong>Note:</strong> Each language may have a different implementation of the constructor and <code>Iterator</code>, but they all support the <code>int next()</code> and <code>boolean hasNext()</code> functions.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;]\n[[[1, 2, 3]], [], [], [], [], []]\n<strong>Output</strong>\n[null, 1, 2, 2, 3, false]\n\n<strong>Explanation</strong>\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3]\npeekingIterator.next();    // return 1, the pointer moves to the next element [1,<u><strong>2</strong></u>,3].\npeekingIterator.peek();    // return 2, the pointer does not move [1,<u><strong>2</strong></u>,3].\npeekingIterator.next();    // return 2, the pointer moves to the next element [1,2,<u><strong>3</strong></u>]\npeekingIterator.next();    // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>All the calls to <code>next</code> and <code>peek</code> are valid.</li>\n\t<li>At most <code>1000</code> calls will be made to <code>next</code>, <code>hasNext</code>, and <code>peek</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> How would you extend your design to be generic and work with all types, not just integer?",
    "solution_url": "https://leetcode.com/problems/peeking-iterator/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass PeekingIterator:\n  def __init__(self, iterator: Iterator):\n    self.iterator = iterator\n    self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n\n  def peek(self) -> int:\n    \"\"\"\n    Returns the next element in the iteration without advancing the iterator.\n    \"\"\"\n    return self.buffer\n\n  def next(self) -> int:\n    next = self.buffer\n    self.buffer = self.iterator.next() if self.iterator.hasNext() else None\n    return next\n\n  def hasNext(self) -> bool:\n    return self.buffer is not None",
    "solution_code_java": "\t\t\t\n\n// Java Iterator interface reference:\n// Https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html\n\nclass PeekingIterator implements Iterator<Integer> {\n  public PeekingIterator(Iterator<Integer> iterator) {\n    this.iterator = iterator;\n    buffer = iterator.hasNext() ? iterator.next() : null;\n  }\n\n  // Returns the next element in the iteration without advancing the iterator.\n  public Integer peek() {\n    return buffer;\n  }\n\n  // hasNext() and next() should behave the same as in the Iterator interface.\n  // Override them if needed.\n  @Override\n  public Integer next() {\n    Integer next = buffer;\n    buffer = iterator.hasNext() ? iterator.next() : null;\n    return next;\n  }\n\n  @Override\n  public boolean hasNext() {\n    return buffer != null;\n  }\n\n  private Iterator<Integer> iterator;\n  private Integer buffer;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass PeekingIterator : public Iterator {\n public:\n  PeekingIterator(const vector<int>& nums) : Iterator(nums) {}\n\n  // Returns the next element in the iteration without advancing the iterator.\n  int peek() {\n    // Iterator(*this) makes a copy of current iterator, then call next on the\n    // Copied iterator to get the next value without affecting current iterator\n    return Iterator(*this).next();\n  }\n\n  // hasNext() and next() should behave the same as in the Iterator interface.\n  // Override them if needed.\n  int next() {\n    return Iterator::next();\n  }\n\n  bool hasNext() const {\n    return Iterator::hasNext();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/284.html",
    "category": "Algorithms",
    "acceptance_rate": 60.25556452660453,
    "topics": [
      "Array",
      "Design",
      "Iterator"
    ],
    "hints": [
      "Think of \"looking ahead\". You want to cache the next element.",
      "Is one variable sufficient? Why or why not?",
      "Test your design with call order of <code>peek()</code> before <code>next()</code> vs <code>next()</code> before <code>peek()</code>.",
      "For a clean implementation, check out <a href=\"https://github.com/google/guava/blob/703ef758b8621cfbab16814f01ddcc5324bdea33/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java#L1125\" target=\"_blank\">Google's guava library source code</a>."
    ],
    "likes": 1882,
    "dislikes": 1043,
    "similar_questions": "[{\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flatten 2D Vector\", \"titleSlug\": \"flatten-2d-vector\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"236.6K\", \"totalSubmission\": \"392.6K\", \"totalAcceptedRaw\": 236576, \"totalSubmissionRaw\": 392621, \"acRate\": \"60.3%\"}",
    "title_pt": "Iterador com Pré-visualização",
    "description_pt": "<p>Projete um iterador que ofereça suporte à operação <code>peek</code> em um iterador existente, além das operações <code>hasNext</code> e <code>next</code>.</p>\n\n<p>Implemente a classe <code>PeekingIterator</code>:</p>\n\n<ul>\n\t<li><code>PeekingIterator(Iterator&lt;int&gt; nums)</code> Inicializa o objeto com o iterador de inteiros <code>iterator</code> fornecido.</li>\n\t<li><code>int next()</code> Retorna o próximo elemento no array e move o ponteiro para o próximo elemento.</li>\n\t<li><code>boolean hasNext()</code> Retorna <code>true</code> se ainda houver elementos no array.</li>\n\t<li><code>int peek()</code> Retorna o próximo elemento no array <strong>sem</strong> mover o ponteiro.</li>\n</ul>\n\n<p><strong>Nota:</strong> Cada linguagem pode ter uma implementação diferente do construtor e de <code>Iterator</code>, mas todas suportam as funções <code>int next()</code> e <code>boolean hasNext()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;PeekingIterator&quot;, &quot;next&quot;, &quot;peek&quot;, &quot;next&quot;, &quot;next&quot;, &quot;hasNext&quot;]\n[[[1, 2, 3]], [], [], [], [], []]\n<strong>Saída</strong>\n[null, 1, 2, 2, 3, false]\n\n<strong>Explicação</strong>\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [<u><strong>1</strong></u>,2,3]\npeekingIterator.next();    // return 1, o ponteiro se move para o próximo elemento [1,<u><strong>2</strong></u>,3].\npeekingIterator.peek();    // return 2, o ponteiro não se move [1,<u><strong>2</strong></u>,3].\npeekingIterator.next();    // return 2, o ponteiro se move para o próximo elemento [1,2,<u><strong>3</strong></u>]\npeekingIterator.next();    // return 3, o ponteiro se move para o próximo elemento [1,2,3]\npeekingIterator.hasNext(); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>Todas as chamadas a <code>next</code> e <code>peek</code> são válidas.</li>\n\t<li>No máximo <code>1000</code> chamadas serão feitas a <code>next</code>, <code>hasNext</code> e <code>peek</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Como você estenderia seu design para ser genérico e funcionar com todos os tipos, não apenas inteiros?",
    "hints_pt": [
      "Dica 1: Pense em \"olhar adiante\". Você quer armazenar em cache o próximo elemento.",
      "Dica 2: Uma variável é suficiente? Por quê ou por quê não?",
      "Dica 3: Teste seu design com a ordem de chamadas de <code>peek()</code> antes de <code>next()</code> versus <code>next()</code> antes de <code>peek()</code>.",
      "Dica 4: Para uma implementação limpa, confira o código-fonte da <a href=\"https://github.com/google/guava/blob/703ef758b8621cfbab16814f01ddcc5324bdea33/guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/Iterators.java#L1125\" target=\"_blank\">biblioteca guava do Google</a>."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "287",
    "paidOnly": false,
    "title": "Find the Duplicate Number",
    "titleSlug": "find-the-duplicate-number",
    "url": "https://leetcode.com/problems/find-the-duplicate-number",
    "description_url": "https://leetcode.com/problems/find-the-duplicate-number/description/",
    "description": "<p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p>\n\n<p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p>\n\n<p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and using only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,4,2,2]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,1,3,4,2]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,3,3,3,3]\n<strong>Output:</strong> 3</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums.length == n + 1</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n\t<li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Follow up:</b></p>\n\n<ul>\n\t<li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li>\n\t<li>Can you solve the problem in linear runtime complexity?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-the-duplicate-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findDuplicate(self, nums: List[int]) -> int:\n    slow = nums[nums[0]]\n    fast = nums[nums[nums[0]]]\n\n    while slow != fast:\n      slow = nums[slow]\n      fast = nums[nums[fast]]\n\n    slow = nums[0]\n\n    while slow != fast:\n      slow = nums[slow]\n      fast = nums[fast]\n\n    return slow",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findDuplicate(int[] nums) {\n    int slow = nums[nums[0]];\n    int fast = nums[nums[nums[0]]];\n\n    while (slow != fast) {\n      slow = nums[slow];\n      fast = nums[nums[fast]];\n    }\n\n    slow = nums[0];\n\n    while (slow != fast) {\n      slow = nums[slow];\n      fast = nums[fast];\n    }\n\n    return slow;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findDuplicate(vector<int>& nums) {\n    int slow = nums[nums[0]];\n    int fast = nums[nums[nums[0]]];\n\n    while (slow != fast) {\n      slow = nums[slow];\n      fast = nums[nums[fast]];\n    }\n\n    slow = nums[0];\n\n    while (slow != fast) {\n      slow = nums[slow];\n      fast = nums[fast];\n    }\n\n    return slow;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/287.html",
    "category": "Algorithms",
    "acceptance_rate": 62.654962267240045,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 24249,
    "dislikes": 5192,
    "similar_questions": "[{\"title\": \"First Missing Positive\", \"titleSlug\": \"first-missing-positive\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Single Number\", \"titleSlug\": \"single-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Linked List Cycle II\", \"titleSlug\": \"linked-list-cycle-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Missing Number\", \"titleSlug\": \"missing-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Set Mismatch\", \"titleSlug\": \"set-mismatch\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"3.4M\", \"totalAcceptedRaw\": 2127747, \"totalSubmissionRaw\": 3395977, \"acRate\": \"62.7%\"}",
    "title_pt": "Encontrar o Número Repetido",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> contendo&nbsp;<code>n + 1</code> inteiros, onde cada inteiro está no intervalo <code>[1, n]</code>, inclusive.</p>\n\n<p>Há apenas <strong>um número repetido</strong> em <code>nums</code>; retorne <em>esse&nbsp;número repetido</em>.</p>\n\n<p>Você deve resolver o problema <strong>sem</strong> modificar o array <code>nums</code>&nbsp;e usando apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,4,2,2]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,1,3,4,2]\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,3,3,3,3]\n<strong>Saída:</strong> 3</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums.length == n + 1</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n\t<li>Todos os inteiros em <code>nums</code> aparecem apenas <strong>uma vez</strong>, exceto por <strong>exatamente um inteiro</strong> que aparece <strong>duas ou mais</strong> vezes.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Desafio extra:</b></p>\n\n<ul>\n\t<li>Como podemos provar que pelo menos um número duplicado deve existir em <code>nums</code>?</li>\n\t<li>Você consegue resolver o problema em complexidade de tempo linear?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "289",
    "paidOnly": false,
    "title": "Game of Life",
    "titleSlug": "game-of-life",
    "url": "https://leetcode.com/problems/game-of-life",
    "description_url": "https://leetcode.com/problems/game-of-life/description/",
    "description": "<p>According to <a href=\"https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\" target=\"_blank\">Wikipedia&#39;s article</a>: &quot;The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.&quot;</p>\n\n<p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href=\"https://en.wikipedia.org/wiki/Moore_neighborhood\" target=\"_blank\">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p>\n\n<ol>\n\t<li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li>\n\t<li>Any live cell with two or three live neighbors lives on to the next generation.</li>\n\t<li>Any live cell with more than three live neighbors dies, as if by over-population.</li>\n\t<li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li>\n</ol>\n\n<p><span>The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the <code>m x n</code> grid <code>board</code>. In this process, births and deaths occur <strong>simultaneously</strong>.</span></p>\n\n<p><span>Given the current state of the <code>board</code>, <strong>update</strong> the <code>board</code> to reflect its next state.</span></p>\n\n<p><strong>Note</strong> that you do not need to return anything.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg\" style=\"width: 562px; height: 322px;\" />\n<pre>\n<strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n<strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg\" style=\"width: 402px; height: 162px;\" />\n<pre>\n<strong>Input:</strong> board = [[1,1],[1,0]]\n<strong>Output:</strong> [[1,1],[1,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 25</code></li>\n\t<li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li>\n\t<li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/game-of-life/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def gameOfLife(self, board: List[List[int]]) -> None:\n    m = len(board)\n    n = len(board[0])\n\n    for i in range(m):\n      for j in range(n):\n        ones = 0\n        for x in range(max(0, i - 1), min(m, i + 2)):\n          for y in range(max(0, j - 1), min(n, j + 2)):\n            ones += board[x][y] & 1\n        # Any live cell with 2 or 3 live neighbors\n        # lives on to the next generation\n        if board[i][j] == 1 and (ones == 3 or ones == 4):\n          board[i][j] |= 0b10\n        # Any dead cell with exactly 3 live neighbors\n        # becomes a live cell, as if by reproduction\n        if board[i][j] == 0 and ones == 3:\n          board[i][j] |= 0b10\n\n    for i in range(m):\n      for j in range(n):\n        board[i][j] >>= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void gameOfLife(int[][] board) {\n    final int m = board.length;\n    final int n = board[0].length;\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        int ones = 0;\n        for (int x = Math.max(0, i - 1); x < Math.min(m, i + 2); ++x)\n          for (int y = Math.max(0, j - 1); y < Math.min(n, j + 2); ++y)\n            ones += board[x][y] & 1;\n        // Any live cell with 2 or 3 live neighbors\n        // lives on to the next generation\n        if (board[i][j] == 1 && (ones == 3 || ones == 4))\n          board[i][j] |= 0b10;\n        // Any dead cell with exactly 3 live neighbors\n        // becomes a live cell, as if by reproduction\n        if (board[i][j] == 0 && ones == 3)\n          board[i][j] |= 0b10;\n      }\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        board[i][j] >>= 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void gameOfLife(vector<vector<int>>& board) {\n    const int m = board.size();\n    const int n = board[0].size();\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        int ones = 0;\n        for (int x = max(0, i - 1); x < min(m, i + 2); ++x)\n          for (int y = max(0, j - 1); y < min(n, j + 2); ++y)\n            ones += board[x][y] & 1;\n        // Any live cell with 2 or 3 live neighbors\n        // lives on to the next generation\n        if (board[i][j] == 1 && (ones == 3 || ones == 4))\n          board[i][j] |= 0b10;\n        // Any dead cell with exactly 3 live neighbors\n        // becomes a live cell, as if by reproduction\n        if (board[i][j] == 0 && ones == 3)\n          board[i][j] |= 0b10;\n      }\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        board[i][j] >>= 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/289.html",
    "category": "Algorithms",
    "acceptance_rate": 71.25993255528054,
    "topics": [
      "Array",
      "Matrix",
      "Simulation"
    ],
    "hints": [],
    "likes": 6589,
    "dislikes": 597,
    "similar_questions": "[{\"title\": \"Set Matrix Zeroes\", \"titleSlug\": \"set-matrix-zeroes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"564K\", \"totalSubmission\": \"791.5K\", \"totalAcceptedRaw\": 563994, \"totalSubmissionRaw\": 791461, \"acRate\": \"71.3%\"}",
    "title_pt": "Jogo da Vida",
    "description_pt": "<p>De acordo com <a href=\"https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\" target=\"_blank\">o artigo da Wikipedia&#39;s</a>: &quot;O <b>Game of Life</b>, também conhecido simplesmente como <b>Life</b>, é um autômato celular idealizado pelo matemático britânico John Horton Conway em 1970.&quot;</p>\n\n<p>O tabuleiro é composto por uma grade <code>m x n</code> de células, onde cada célula tem um estado inicial: <b>viva</b> (representada por um <code>1</code>) ou <b>morta</b> (representada por um <code>0</code>). Cada célula interage com seus <a href=\"https://en.wikipedia.org/wiki/Moore_neighborhood\" target=\"_blank\">oito vizinhos</a> (horizontal, vertical, diagonal) usando as quatro regras a seguir (retiradas do artigo da Wikipedia acima):</p>\n\n<ol>\n\t<li>Qualquer célula viva com menos de dois vizinhos vivos morre, como se fosse causada por subpopulação.</li>\n\t<li>Qualquer célula viva com dois ou três vizinhos vivos continua viva até a próxima geração.</li>\n\t<li>Qualquer célula viva com mais de três vizinhos vivos morre, como se fosse por superpopulação.</li>\n\t<li>Qualquer célula morta com exatamente três vizinhos vivos se torna uma célula viva, como se fosse por reprodução.</li>\n</ol>\n\n<p><span>O próximo estado do tabuleiro é determinado aplicando as regras acima simultaneamente a cada célula no estado atual da grade <code>m x n</code> <code>board</code>. Nesse processo, nascimentos e mortes ocorrem <strong>simultaneamente</strong>.</span></p>\n\n<p><span>Dado o estado atual do <code>board</code>, <strong>atualize</strong> o <code>board</code> para refletir seu próximo estado.</span></p>\n\n<p><strong>Nota</strong> que você não precisa retornar nada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg\" style=\"width: 562px; height: 322px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n<strong>Saída:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg\" style=\"width: 402px; height: 162px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[1,1],[1,0]]\n<strong>Saída:</strong> [[1,1],[1,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 25</code></li>\n\t<li><code>board[i][j]</code> é <code>0</code> ou <code>1</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Você conseguiria resolvê-lo in-place? Lembre-se de que o tabuleiro precisa ser atualizado simultaneamente: você não pode atualizar algumas células primeiro e depois usar seus valores atualizados para atualizar outras células.</li>\n\t<li>Nesta questão, representamos o tabuleiro usando um array 2D. Em princípio, o tabuleiro é infinito, o que causaria problemas quando a área ativa se aproximasse da borda do array (isto é, células vivas alcançassem a borda). Como você lidaria com esses problemas?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "290",
    "paidOnly": false,
    "title": "Word Pattern",
    "titleSlug": "word-pattern",
    "url": "https://leetcode.com/problems/word-pattern",
    "description_url": "https://leetcode.com/problems/word-pattern/description/",
    "description": "<p>Given a <code>pattern</code> and a string <code>s</code>, find if <code>s</code>&nbsp;follows the same pattern.</p>\n\n<p>Here <b>follow</b> means a full match, such that there is a bijection between a letter in <code>pattern</code> and a <b>non-empty</b> word in <code>s</code>. Specifically:</p>\n\n<ul>\n\t<li>Each letter in <code>pattern</code> maps to <strong>exactly</strong> one unique word in <code>s</code>.</li>\n\t<li>Each unique word in <code>s</code> maps to <strong>exactly</strong> one letter in <code>pattern</code>.</li>\n\t<li>No two letters map to the same word, and no two words map to the same letter.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The bijection can be established as:</p>\n\n<ul>\n\t<li><code>&#39;a&#39;</code> maps to <code>&quot;dog&quot;</code>.</li>\n\t<li><code>&#39;b&#39;</code> maps to <code>&quot;cat&quot;</code>.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= pattern.length &lt;= 300</code></li>\n\t<li><code>pattern</code> contains only lower-case English letters.</li>\n\t<li><code>1 &lt;= s.length &lt;= 3000</code></li>\n\t<li><code>s</code> contains only lowercase English letters and spaces <code>&#39; &#39;</code>.</li>\n\t<li><code>s</code> <strong>does not contain</strong> any leading or trailing spaces.</li>\n\t<li>All the words in <code>s</code> are separated by a <strong>single space</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/word-pattern/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def wordPattern(self, pattern: str, str: str) -> bool:\n    t = str.split()\n    return [*map(pattern.index, pattern)] == [*map(t.index, t)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean wordPattern(String pattern, String str) {\n    String[] words = str.split(\" \");\n    if (words.length != pattern.length())\n      return false;\n\n    Map<Character, Integer> charToIndex = new HashMap<>();\n    Map<String, Integer> stringToIndex = new HashMap<>();\n\n    for (Integer i = 0; i < pattern.length(); ++i)\n      if (charToIndex.put(pattern.charAt(i), i) != stringToIndex.put(words[i], i))\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool wordPattern(string pattern, string str) {\n    const int n = pattern.length();\n    istringstream iss(str);\n    vector<int> charToIndex(128);\n    unordered_map<string, int> stringToIndex;\n\n    int i = 0;\n    for (string word; iss >> word; ++i) {\n      if (i == n)  // Out of bound\n        return false;\n      if (charToIndex[pattern[i]] != stringToIndex[word])\n        return false;\n      charToIndex[pattern[i]] = i + 1;\n      stringToIndex[word] = i + 1;\n    }\n\n    return i == n;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/290.html",
    "category": "Algorithms",
    "acceptance_rate": 42.98343204830684,
    "topics": [
      "Hash Table",
      "String"
    ],
    "hints": [],
    "likes": 7614,
    "dislikes": 1093,
    "similar_questions": "[{\"title\": \"Isomorphic Strings\", \"titleSlug\": \"isomorphic-strings\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Word Pattern II\", \"titleSlug\": \"word-pattern-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find and Replace Pattern\", \"titleSlug\": \"find-and-replace-pattern\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"930.7K\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 930722, \"totalSubmissionRaw\": 2165306, \"acRate\": \"43.0%\"}",
    "title_pt": "Padrão de Palavras",
    "description_pt": "<p>Dado um <code>pattern</code> e uma string <code>s</code>, descubra se <code>s</code>&nbsp;segue o mesmo padrão.</p>\n\n<p>Aqui, <b>segue</b> significa uma correspondência completa, de modo que exista uma bijeção entre uma letra em <code>pattern</code> e uma palavra <b>não vazia</b> em <code>s</code>. Especificamente:</p>\n\n<ul>\n\t<li>Cada letra em <code>pattern</code> mapeia para <strong>exatamente</strong> uma palavra única em <code>s</code>.</li>\n\t<li>Cada palavra única em <code>s</code> mapeia para <strong>exatamente</strong> uma letra em <code>pattern</code>.</li>\n\t<li>Nenhuma duas letras mapeiam para a mesma palavra, e nenhuma duas palavras mapeiam para a mesma letra.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">pattern = &quot;abba&quot;, s = &quot;dog cat cat dog&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">true</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>A bijeção pode ser estabelecida como:</p>\n\n<ul>\n\t<li><code>&#39;a&#39;</code> mapeia para <code>&quot;dog&quot;</code>.</li>\n\t<li><code>&#39;b&#39;</code> mapeia para <code>&quot;cat&quot;</code>.</li>\n</ul>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">pattern = &quot;abba&quot;, s = &quot;dog cat cat fish&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">pattern = &quot;aaaa&quot;, s = &quot;dog cat cat dog&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">false</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= pattern.length &lt;= 300</code></li>\n\t<li><code>pattern</code> contém apenas letras minúsculas do alfabeto inglês.</li>\n\t<li><code>1 &lt;= s.length &lt;= 3000</code></li>\n\t<li><code>s</code> contém apenas letras minúsculas do alfabeto inglês e espaços <code>&#39; &#39;</code>.</li>\n\t<li><code>s</code> <strong>não contém</strong> espaços no início ou no fim.</li>\n\t<li>Todas as palavras em <code>s</code> são separadas por um <strong>único espaço</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "292",
    "paidOnly": false,
    "title": "Nim Game",
    "titleSlug": "nim-game",
    "url": "https://leetcode.com/problems/nim-game",
    "description_url": "https://leetcode.com/problems/nim-game/description/",
    "description": "<p>You are playing the following Nim Game with your friend:</p>\n\n<ul>\n\t<li>Initially, there is a heap of stones on the table.</li>\n\t<li>You and your friend will alternate taking turns, and <strong>you go first</strong>.</li>\n\t<li>On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.</li>\n\t<li>The one who removes the last stone is the winner.</li>\n</ul>\n\n<p>Given <code>n</code>, the number of stones in the heap, return <code>true</code><em> if you can win the game assuming both you and your friend play optimally, otherwise return </em><code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 4\n<strong>Output:</strong> false\n<strong>Explanation:</strong> These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/nim-game/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canWinNim(self, n: int) -> bool:\n    return n % 4 != 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canWinNim(int n) {\n    return n % 4 != 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canWinNim(int n) {\n    return n % 4 != 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/292.html",
    "category": "Algorithms",
    "acceptance_rate": 58.021742668695566,
    "topics": [
      "Math",
      "Brainteaser",
      "Game Theory"
    ],
    "hints": [
      "If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?"
    ],
    "likes": 1830,
    "dislikes": 2721,
    "similar_questions": "[{\"title\": \"Flip Game II\", \"titleSlug\": \"flip-game-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"449.2K\", \"totalSubmission\": \"774.1K\", \"totalAcceptedRaw\": 449173, \"totalSubmissionRaw\": 774146, \"acRate\": \"58.0%\"}",
    "title_pt": "Jogo de Nim",
    "description_pt": "<p>Você está jogando o seguinte Jogo de Nim com seu amigo:</p>\n\n<ul>\n\t<li>Inicialmente, há um monte de pedras sobre a mesa.</li>\n\t<li>Você e seu amigo se alternarão nas jogadas, e <strong>você joga primeiro</strong>.</li>\n\t<li>Em cada turno, a pessoa cuja vez for removerá de 1 a 3 pedras do monte.</li>\n\t<li>Aquele que remover a última pedra é o vencedor.</li>\n</ul>\n\n<p>Dado <code>n</code>, o número de pedras no monte, retorne <code>true</code><em> se você puder vencer o jogo assumindo que tanto você quanto seu amigo jogam de forma ótima; caso contrário, retorne </em><code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 4\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Estes são os possíveis resultados:\n1. Você remove 1 pedra. Seu amigo remove 3 pedras, incluindo a última pedra. Seu amigo vence.\n2. Você remove 2 pedras. Seu amigo remove 2 pedras, incluindo a última pedra. Seu amigo vence.\n3. Você remove 3 pedras. Seu amigo remove a última pedra. Seu amigo vence.\nEm todos os resultados, seu amigo vence.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Se houver 5 pedras no monte, você conseguiria descobrir uma maneira de remover as pedras de modo que você sempre seja o vencedor?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "295",
    "paidOnly": false,
    "title": "Find Median from Data Stream",
    "titleSlug": "find-median-from-data-stream",
    "url": "https://leetcode.com/problems/find-median-from-data-stream",
    "description_url": "https://leetcode.com/problems/find-median-from-data-stream/description/",
    "description": "<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.</p>\n\n<ul>\n\t<li>For example, for <code>arr = [2,3,4]</code>, the median is <code>3</code>.</li>\n\t<li>For example, for <code>arr = [2,3]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>\n</ul>\n\n<p>Implement the MedianFinder class:</p>\n\n<ul>\n\t<li><code>MedianFinder()</code> initializes the <code>MedianFinder</code> object.</li>\n\t<li><code>void addNum(int num)</code> adds the integer <code>num</code> from the data stream to the data structure.</li>\n\t<li><code>double findMedian()</code> returns the median of all elements so far. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;]\n[[], [1], [2], [], [3], []]\n<strong>Output</strong>\n[null, null, null, 1.5, null, 2.0]\n\n<strong>Explanation</strong>\nMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1);    // arr = [1]\nmedianFinder.addNum(2);    // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3);    // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li>\n\t<li>There will be at least one element in the data structure before calling <code>findMedian</code>.</li>\n\t<li>At most <code>5 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>findMedian</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>If all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li>\n\t<li>If <code>99%</code> of all integer numbers from the stream are in the range <code>[0, 100]</code>, how would you optimize your solution?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-median-from-data-stream/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass MedianFinder:\n  def __init__(self):\n    self.maxHeap = []\n    self.minHeap = []\n\n  def addNum(self, num: int) -> None:\n    if not self.maxHeap or num <= -self.maxHeap[0]:\n      heapq.heappush(self.maxHeap, -num)\n    else:\n      heapq.heappush(self.minHeap, num)\n\n    # Balance two heaps s.t.\n    # |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1\n    if len(self.maxHeap) < len(self.minHeap):\n      heapq.heappush(self.maxHeap, -heapq.heappop(self.minHeap))\n    elif len(self.maxHeap) - len(self.minHeap) > 1:\n      heapq.heappush(self.minHeap, -heapq.heappop(self.maxHeap))\n\n  def findMedian(self) -> float:\n    if len(self.maxHeap) == len(self.minHeap):\n      return (-self.maxHeap[0] + self.minHeap[0]) / 2.0\n    return -self.maxHeap[0]",
    "solution_code_java": "\t\t\t\n\nclass MedianFinder {\n  public void addNum(int num) {\n    if (maxHeap.isEmpty() || num <= maxHeap.peek())\n      maxHeap.offer(num);\n    else\n      minHeap.offer(num);\n\n    // Balance two heaps s.t.\n    // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1\n    if (maxHeap.size() < minHeap.size())\n      maxHeap.offer(minHeap.poll());\n    else if (maxHeap.size() - minHeap.size() > 1)\n      minHeap.offer(maxHeap.poll());\n  }\n\n  public double findMedian() {\n    if (maxHeap.size() == minHeap.size())\n      return (double) (maxHeap.peek() + minHeap.peek()) / 2.0;\n    return (double) maxHeap.peek();\n  }\n\n  private Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n  private Queue<Integer> minHeap = new PriorityQueue<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MedianFinder {\n public:\n  void addNum(int num) {\n    if (maxHeap.empty() || num <= maxHeap.top())\n      maxHeap.push(num);\n    else\n      minHeap.push(num);\n\n    // Balance two heaps s.t.\n    // |maxHeap| >= |minHeap| and |maxHeap| - |minHeap| <= 1\n    if (maxHeap.size() < minHeap.size())\n      maxHeap.push(minHeap.top()), minHeap.pop();\n    else if (maxHeap.size() - minHeap.size() > 1)\n      minHeap.push(maxHeap.top()), maxHeap.pop();\n  }\n\n  double findMedian() {\n    if (maxHeap.size() == minHeap.size())\n      return (maxHeap.top() + minHeap.top()) / 2.0;\n    return maxHeap.top();\n  }\n\n private:\n  priority_queue<int> maxHeap;\n  priority_queue<int, vector<int>, greater<>> minHeap;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/295.html",
    "category": "Algorithms",
    "acceptance_rate": 53.13144992601192,
    "topics": [
      "Two Pointers",
      "Design",
      "Sorting",
      "Heap (Priority Queue)",
      "Data Stream"
    ],
    "hints": [],
    "likes": 12516,
    "dislikes": 265,
    "similar_questions": "[{\"title\": \"Sliding Window Median\", \"titleSlug\": \"sliding-window-median\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Finding MK Average\", \"titleSlug\": \"finding-mk-average\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sequentially Ordinal Rank Tracker\", \"titleSlug\": \"sequentially-ordinal-rank-tracker\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Median of Array Equal to K\", \"titleSlug\": \"minimum-operations-to-make-median-of-array-equal-to-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Subarray Elements Equal\", \"titleSlug\": \"minimum-operations-to-make-subarray-elements-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Elements Within K Subarrays Equal\", \"titleSlug\": \"minimum-operations-to-make-elements-within-k-subarrays-equal\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"994.9K\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 994939, \"totalSubmissionRaw\": 1872599, \"acRate\": \"53.1%\"}",
    "title_pt": "Encontrar a Mediana de um Fluxo de Dados",
    "description_pt": "<p>A <strong>mediana</strong> é o valor central em uma lista ordenada de inteiros. Se o tamanho da lista for par, não há valor central, e a mediana é a média dos dois valores centrais.</p>\n\n<ul>\n\t<li>Por exemplo, para <code>arr = [2,3,4]</code>, a mediana é <code>3</code>.</li>\n\t<li>Por exemplo, para <code>arr = [2,3]</code>, a mediana é <code>(2 + 3) / 2 = 2.5</code>.</li>\n</ul>\n\n<p>Implemente a classe MedianFinder:</p>\n\n<ul>\n\t<li><code>MedianFinder()</code> inicializa o objeto <code>MedianFinder</code>.</li>\n\t<li><code>void addNum(int num)</code> adiciona o inteiro <code>num</code> do fluxo de dados à estrutura de dados.</li>\n\t<li><code>double findMedian()</code> retorna a mediana de todos os elementos até o momento. Respostas dentro de <code>10<sup>-5</sup></code> da resposta real serão aceitas.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MedianFinder&quot;, &quot;addNum&quot;, &quot;addNum&quot;, &quot;findMedian&quot;, &quot;addNum&quot;, &quot;findMedian&quot;]\n[[], [1], [2], [], [3], []]\n<strong>Saída</strong>\n[null, null, null, 1.5, null, 2.0]\n\n<strong>Explicação</strong>\nMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1);    // arr = [1]\nmedianFinder.addNum(2);    // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3);    // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>5</sup> &lt;= num &lt;= 10<sup>5</sup></code></li>\n\t<li>Haverá pelo menos um elemento na estrutura de dados antes de chamar <code>findMedian</code>.</li>\n\t<li>No máximo <code>5 * 10<sup>4</sup></code> chamadas serão feitas a <code>addNum</code> e <code>findMedian</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Se todos os números inteiros do fluxo estiverem no intervalo <code>[0, 100]</code>, como você otimizaria sua solução?</li>\n\t<li>Se <code>99%</code> de todos os números inteiros do fluxo estiverem no intervalo <code>[0, 100]</code>, como você otimizaria sua solução?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "297",
    "paidOnly": false,
    "title": "Serialize and Deserialize Binary Tree",
    "titleSlug": "serialize-and-deserialize-binary-tree",
    "url": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree",
    "description_url": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/",
    "description": "<p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>\n\n<p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p>\n\n<p><strong>Clarification:</strong> The input/output format is the same as <a href=\"https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A\" target=\"_blank\">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg\" style=\"width: 442px; height: 324px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,null,null,4,5]\n<strong>Output:</strong> [1,2,3,null,null,4,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Codec:\n  def serialize(self, root: 'TreeNode') -> str:\n    \"\"\"Encodes a tree to a single string.\"\"\"\n    if not root:\n      return ''\n\n    s = ''\n    q = deque([root])\n\n    while q:\n      node = q.popleft()\n      if node:\n        s += str(node.val) + ' '\n        q.append(node.left)\n        q.append(node.right)\n      else:\n        s += 'n '\n\n    return s\n\n  def deserialize(self, data: str) -> 'TreeNode':\n    \"\"\"Decodes your encoded data to tree.\"\"\"\n    if not data:\n      return None\n\n    vals = data.split()\n    root = TreeNode(vals[0])\n    q = deque([root])\n\n    for i in range(1, len(vals), 2):\n      node = q.popleft()\n      if vals[i] != 'n':\n        node.left = TreeNode(vals[i])\n        q.append(node.left)\n      if vals[i + 1] != 'n':\n        node.right = TreeNode(vals[i + 1])\n        q.append(node.right)\n\n    return root",
    "solution_code_java": "\t\t\t\n\npublic class Codec {\n  // Encodes a tree to a single string.\n  public String serialize(TreeNode root) {\n    if (root == null)\n      return \"\";\n\n    StringBuilder sb = new StringBuilder();\n    Queue<TreeNode> q = new LinkedList<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      TreeNode node = q.poll();\n      if (node == null) {\n        sb.append(\"n \");\n      } else {\n        sb.append(node.val).append(\" \");\n        q.offer(node.left);\n        q.offer(node.right);\n      }\n    }\n\n    return sb.toString();\n  }\n\n  // Decodes your encoded data to tree.\n  public TreeNode deserialize(String data) {\n    if (data.equals(\"\"))\n      return null;\n\n    final String[] vals = data.split(\" \");\n    TreeNode root = new TreeNode(Integer.parseInt(vals[0]));\n    Queue<TreeNode> q = new LinkedList<>(Arrays.asList(root));\n\n    for (int i = 1; i < vals.length; i += 2) {\n      TreeNode node = q.poll();\n      if (!vals[i].equals(\"n\")) {\n        node.left = new TreeNode(Integer.parseInt(vals[i]));\n        q.offer(node.left);\n      }\n      if (!vals[i + 1].equals(\"n\")) {\n        node.right = new TreeNode(Integer.parseInt(vals[i + 1]));\n        q.offer(node.right);\n      }\n    }\n\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Codec {\n public:\n  // Encodes a tree to a single string.\n  string serialize(TreeNode* root) {\n    if (root == nullptr)\n      return \"\";\n\n    string s;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      TreeNode* node = q.front();\n      q.pop();\n      if (node != nullptr) {\n        s += to_string(node->val) + \" \";\n        q.push(node->left);\n        q.push(node->right);\n      } else {\n        s += \"n \";\n      }\n    }\n\n    return s;\n  }\n\n  // Decodes your encoded data to tree.\n  TreeNode* deserialize(string data) {\n    if (data.empty())\n      return nullptr;\n\n    istringstream iss(data);\n    string word;\n    iss >> word;\n    TreeNode* root = new TreeNode(stoi(word));\n    queue<TreeNode*> q{{root}};\n\n    while (iss >> word) {\n      TreeNode* node = q.front();\n      q.pop();\n      if (word != \"n\") {\n        node->left = new TreeNode(stoi(word));\n        q.push(node->left);\n      }\n      iss >> word;\n      if (word != \"n\") {\n        node->right = new TreeNode(stoi(word));\n        q.push(node->right);\n      }\n    }\n\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/297.html",
    "category": "Algorithms",
    "acceptance_rate": 58.75168251935543,
    "topics": [
      "String",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Design",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 10605,
    "dislikes": 409,
    "similar_questions": "[{\"title\": \"Encode and Decode Strings\", \"titleSlug\": \"encode-and-decode-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Serialize and Deserialize BST\", \"titleSlug\": \"serialize-and-deserialize-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Duplicate Subtrees\", \"titleSlug\": \"find-duplicate-subtrees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Serialize and Deserialize N-ary Tree\", \"titleSlug\": \"serialize-and-deserialize-n-ary-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1023987, \"totalSubmissionRaw\": 1742911, \"acRate\": \"58.8%\"}",
    "title_pt": "Serializar e Desserializar Árvore Binária",
    "description_pt": "<p>Serialização é o processo de converter uma estrutura de dados ou objeto em uma sequência de bits, de modo que possa ser armazenada em um arquivo ou buffer de memória, ou transmitida por um link de conexão de rede para ser reconstruída posteriormente no mesmo ambiente computacional ou em outro.</p>\n\n<p>Projete um algoritmo para serializar e desserializar uma árvore binária. Não há restrição sobre como seu algoritmo de serialização/desserialização deve funcionar. Você só precisa garantir que uma árvore binária possa ser serializada para uma string e que essa string possa ser desserializada para a estrutura de árvore original.</p>\n\n<p><strong>Esclarecimento:</strong> O formato de entrada/saída é o mesmo de <a href=\"https://support.leetcode.com/hc/en-us/articles/32442719377939-How-to-create-test-cases-on-LeetCode#h_01J5EGREAW3NAEJ14XC07GRW1A\" target=\"_blank\">como o LeetCode serializa uma árvore binária</a>. Você não precisa necessariamente seguir esse formato, então seja criativo e pense em abordagens diferentes por conta própria.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg\" style=\"width: 442px; height: 324px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,null,null,4,5]\n<strong>Saída:</strong> [1,2,3,null,null,4,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "299",
    "paidOnly": false,
    "title": "Bulls and Cows",
    "titleSlug": "bulls-and-cows",
    "url": "https://leetcode.com/problems/bulls-and-cows",
    "description_url": "https://leetcode.com/problems/bulls-and-cows/description/",
    "description": "<p>You are playing the <strong><a href=\"https://en.wikipedia.org/wiki/Bulls_and_Cows\" target=\"_blank\">Bulls and Cows</a></strong> game with your friend.</p>\n\n<p>You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:</p>\n\n<ul>\n\t<li>The number of &quot;bulls&quot;, which are digits in the guess that are in the correct position.</li>\n\t<li>The number of &quot;cows&quot;, which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.</li>\n</ul>\n\n<p>Given the secret number <code>secret</code> and your friend&#39;s guess <code>guess</code>, return <em>the hint for your friend&#39;s guess</em>.</p>\n\n<p>The hint should be formatted as <code>&quot;xAyB&quot;</code>, where <code>x</code> is the number of bulls and <code>y</code> is the number of cows. Note that both <code>secret</code> and <code>guess</code> may contain duplicate digits.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot;\n<strong>Output:</strong> &quot;1A3B&quot;\n<strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined:\n&quot;1807&quot;\n  |\n&quot;<u>7</u>8<u>10</u>&quot;</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot;\n<strong>Output:</strong> &quot;1A1B&quot;\n<strong>Explanation:</strong> Bulls are connected with a &#39;|&#39; and cows are underlined:\n&quot;1123&quot;        &quot;1123&quot;\n  |      or     |\n&quot;01<u>1</u>1&quot;        &quot;011<u>1</u>&quot;\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li>\n\t<li><code>secret.length == guess.length</code></li>\n\t<li><code>secret</code> and <code>guess</code> consist of digits only.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/bulls-and-cows/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getHint(self, secret: str, guess: str) -> str:\n    bulls = sum(map(operator.eq, secret, guess))\n    bovine = sum(min(secret.count(x), guess.count(x)) for x in set(guess))\n    return '%dA%dB' % (bulls, bovine - bulls)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String getHint(String secret, String guess) {\n    int A = 0;\n    int B = 0;\n    int[] count1 = new int[10];\n    int[] count2 = new int[10];\n\n    for (int i = 0; i < secret.length(); ++i)\n      if (secret.charAt(i) == guess.charAt(i))\n        ++A;\n      else {\n        ++count1[secret.charAt(i) - '0'];\n        ++count2[guess.charAt(i) - '0'];\n      }\n\n    for (int i = 0; i < 10; ++i)\n      B += Math.min(count1[i], count2[i]);\n\n    return String.valueOf(A) + \"A\" + String.valueOf(B) + \"B\";\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string getHint(string secret, string guess) {\n    int A = 0;\n    int B = 0;\n    vector<int> count1(10);\n    vector<int> count2(10);\n\n    for (int i = 0; i < secret.length(); ++i)\n      if (secret[i] == guess[i])\n        ++A;\n      else {\n        ++count1[secret[i] - '0'];\n        ++count2[guess[i] - '0'];\n      }\n\n    for (int i = 0; i < 10; ++i)\n      B += min(count1[i], count2[i]);\n\n    return to_string(A) + \"A\" + to_string(B) + \"B\";\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/299.html",
    "category": "Algorithms",
    "acceptance_rate": 51.272583459930445,
    "topics": [
      "Hash Table",
      "String",
      "Counting"
    ],
    "hints": [],
    "likes": 2537,
    "dislikes": 1799,
    "similar_questions": "[{\"title\": \"Make Number of Distinct Characters Equal\", \"titleSlug\": \"make-number-of-distinct-characters-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"408.4K\", \"totalSubmission\": \"796.5K\", \"totalAcceptedRaw\": 408381, \"totalSubmissionRaw\": 796489, \"acRate\": \"51.3%\"}",
    "title_pt": "Touros e Vacas",
    "description_pt": "<p>Você está jogando o jogo <strong><a href=\"https://en.wikipedia.org/wiki/Bulls_and_Cows\" target=\"_blank\">Bulls and Cows</a></strong> com seu amigo.</p>\n\n<p>Você escreve um número secreto e pede ao seu amigo que adivinhe qual é o número. Quando seu amigo faz uma tentativa, você fornece uma dica com as seguintes informações:</p>\n\n<ul>\n\t<li>O número de \"touros\", que são dígitos na tentativa que estão na posição correta.</li>\n\t<li>O número de \"vacas\", que são dígitos na tentativa que estão no seu número secreto, mas estão localizados na posição errada. Especificamente, os dígitos não touro na tentativa que poderiam ser rearranjados de forma que se tornem touros.</li>\n</ul>\n\n<p>Dado o número secreto <code>secret</code> e a tentativa do seu amigo <code>guess</code>, retorne <em>a dica para a tentativa do seu amigo</em>.</p>\n\n<p>A dica deve ser formatada como <code>&quot;xAyB&quot;</code>, onde <code>x</code> é o número de touros e <code>y</code> é o número de vacas. Observe que tanto <code>secret</code> quanto <code>guess</code> podem conter dígitos duplicados.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> secret = &quot;1807&quot;, guess = &quot;7810&quot;\n<strong>Saída:</strong> &quot;1A3B&quot;\n<strong>Explicação:</strong> Os touros estão conectados com um &#39;|&#39; e as vacas estão sublinhadas:\n&quot;1807&quot;\n  |\n&quot;<u>7</u>8<u>10</u>&quot;</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> secret = &quot;1123&quot;, guess = &quot;0111&quot;\n<strong>Saída:</strong> &quot;1A1B&quot;\n<strong>Explicação:</strong> Os touros estão conectados com um &#39;|&#39; e as vacas estão sublinhadas:\n&quot;1123&quot;        &quot;1123&quot;\n  |      ou     |\n&quot;01<u>1</u>1&quot;        &quot;011<u>1</u>&quot;\nObserve que apenas um dos dois 1s não correspondidos é contado como uma vaca, já que os dígitos não touro só podem ser rearranjados para permitir que um 1 seja um touro.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= secret.length, guess.length &lt;= 1000</code></li>\n\t<li><code>secret.length == guess.length</code></li>\n\t<li><code>secret</code> e <code>guess</code> consistem apenas de dígitos.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "300",
    "paidOnly": false,
    "title": "Longest Increasing Subsequence",
    "titleSlug": "longest-increasing-subsequence",
    "url": "https://leetcode.com/problems/longest-increasing-subsequence",
    "description_url": "https://leetcode.com/problems/longest-increasing-subsequence/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>strictly increasing </strong></em><span data-keyword=\"subsequence-array\"><em><strong>subsequence</strong></em></span>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [10,9,2,5,3,7,101,18]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,0,3,2,3]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [7,7,7,7,7,7,7]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>\n",
    "solution_url": "https://leetcode.com/problems/longest-increasing-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def lengthOfLIS(self, nums: List[int]) -> int:\n    if not nums:\n      return 0\n\n    # dp[i] := LIS ending at nums[i]\n    dp = [1] * len(nums)\n\n    for i in range(1, len(nums)):\n      for j in range(i):\n        if nums[j] < nums[i]:\n          dp[i] = max(dp[i], dp[j] + 1)\n\n    return max(dp)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int lengthOfLIS(int[] nums) {\n    if (nums.length == 0)\n      return 0;\n\n    // dp[i] := Length of LIS ending at nums[i]\n    int[] dp = new int[nums.length];\n    Arrays.fill(dp, 1);\n\n    for (int i = 1; i < nums.length; ++i)\n      for (int j = 0; j < i; ++j)\n        if (nums[j] < nums[i])\n          dp[i] = Math.max(dp[i], dp[j] + 1);\n\n    return Arrays.stream(dp).max().getAsInt();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int lengthOfLIS(vector<int>& nums) {\n    if (nums.empty())\n      return 0;\n\n    // dp[i] := Length of LIS ending at nums[i]\n    vector<int> dp(nums.size(), 1);\n\n    for (int i = 1; i < nums.size(); ++i)\n      for (int j = 0; j < i; ++j)\n        if (nums[j] < nums[i])\n          dp[i] = max(dp[i], dp[j] + 1);\n\n    return *max_element(begin(dp), end(dp));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/300.html",
    "category": "Algorithms",
    "acceptance_rate": 57.57901324430382,
    "topics": [
      "Array",
      "Binary Search",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 21754,
    "dislikes": 481,
    "similar_questions": "[{\"title\": \"Increasing Triplet Subsequence\", \"titleSlug\": \"increasing-triplet-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Russian Doll Envelopes\", \"titleSlug\": \"russian-doll-envelopes\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Length of Pair Chain\", \"titleSlug\": \"maximum-length-of-pair-chain\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Longest Increasing Subsequence\", \"titleSlug\": \"number-of-longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum ASCII Delete Sum for Two Strings\", \"titleSlug\": \"minimum-ascii-delete-sum-for-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Removals to Make Mountain Array\", \"titleSlug\": \"minimum-number-of-removals-to-make-mountain-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Longest Valid Obstacle Course at Each Position\", \"titleSlug\": \"find-the-longest-valid-obstacle-course-at-each-position\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make the Array K-Increasing\", \"titleSlug\": \"minimum-operations-to-make-the-array-k-increasing\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Ideal Subsequence\", \"titleSlug\": \"longest-ideal-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Books You Can Take\", \"titleSlug\": \"maximum-number-of-books-you-can-take\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Increasing Subsequence II\", \"titleSlug\": \"longest-increasing-subsequence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of a Good Subsequence II\", \"titleSlug\": \"find-the-maximum-length-of-a-good-subsequence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of a Good Subsequence I\", \"titleSlug\": \"find-the-maximum-length-of-a-good-subsequence-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of Valid Subsequence I\", \"titleSlug\": \"find-the-maximum-length-of-valid-subsequence-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of Valid Subsequence II\", \"titleSlug\": \"find-the-maximum-length-of-valid-subsequence-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Subsequence With Decreasing Adjacent Difference\", \"titleSlug\": \"longest-subsequence-with-decreasing-adjacent-difference\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"3.7M\", \"totalAcceptedRaw\": 2143720, \"totalSubmissionRaw\": 3723100, \"acRate\": \"57.6%\"}",
    "title_pt": "Subsequência Crescente Mais Longa",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o comprimento da mais longa </em><span data-keyword=\"subsequence-array\"><em><strong>subsequência</strong></em></span><em> estritamente crescente</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [10,9,2,5,3,7,101,18]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> A mais longa subsequência crescente é [2,3,7,101], portanto o comprimento é 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,0,3,2,3]\n<strong>Saída:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [7,7,7,7,7,7,7]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><b>Desafio extra:</b>&nbsp;Você consegue criar um algoritmo que execute em complexidade de tempo <code>O(n log(n))</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "301",
    "paidOnly": false,
    "title": "Remove Invalid Parentheses",
    "titleSlug": "remove-invalid-parentheses",
    "url": "https://leetcode.com/problems/remove-invalid-parentheses",
    "description_url": "https://leetcode.com/problems/remove-invalid-parentheses/description/",
    "description": "<p>Given a string <code>s</code> that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.</p>\n\n<p>Return <em>a list of <strong>unique strings</strong> that are valid with the minimum number of removals</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;()())()&quot;\n<strong>Output:</strong> [&quot;(())()&quot;,&quot;()()()&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;(a)())()&quot;\n<strong>Output:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;)(&quot;\n<strong>Output:</strong> [&quot;&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 25</code></li>\n\t<li><code>s</code> consists of lowercase English letters and parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code>.</li>\n\t<li>There will be at most <code>20</code> parentheses in <code>s</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-invalid-parentheses/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n### Approach 1: Backtracking\n\n**Intuition**\n\nFor this question, we are given an expression consisting of parentheses and there can be some misplaced or extra brackets in the expression that cause it to be invalid. An expression consisting of parentheses is considered valid only when every closing bracket has a corresponding opening bracket and vice versa.\n\nThis means if we start looking at each of the bracket from left to right, as soon as we encounter a closing bracket, there should be an unmatched opening bracket available to match it. Otherwise the expression would become invalid. The expression can also become invalid if the number of opening parentheses i.e. `(` are more than the number of closing parentheses i.e. `)`.\n\nLet us look at an invalid expression and all the possible valid expressions that can be formed from it by removing some of the brackets. There is no restriction on which parentheses we can remove. We simply have to make the expression valid.\n\n> The only condition is that we should be removing the minimum number of brackets to make an invalid expression, valid. If this condition was not present, we could potentially remove most of the brackets and come down to say 2 brackets in the end which form `()` and that would be a valid expression.\n\n<center>\n<img src=\"../Figures/301/Diag_1.png\" width=\"800\"></center>\n\nAn important thing to observe in the above diagram is that there are multiple ways of reaching the same solution i.e. say the optimal number of parentheses to be removed to make the original expression valid is K. We can remove multiple different sets of K brackets that will eventually give us the same final expression. But, each valid expression should be recorded only once. We have to take care of this in our solution. Note that there are other possible ways of reaching one of the two valid expressions shown above. We have simply shown 3 ways each for the two valid expressions.\n\nComing back to our problem, the question that now arises is, how to decide which of the parentheses to remove?\n\n> Since we don't know which of the brackets can possibly be removed, we try out all the options!\n\nFor every bracket we have two choices:\n\n* Either it can be considered a part of the final expression OR\n* It can be ignored i.e. we can delete it from our final expression.\n\nSuch kind of problems where we have multiple options and we have no strategy or metric of deciding greedily which option to take, we try out all of the options and see which ones lead to an answer. These type of problems are perfect candidates for the programming paradigm, `Recursion`.\n\n**Algorithm**\n\n1. Initialize an array that will store all of our valid expressions finally.\n2. Start with the leftmost bracket in the given sequence and proceed right in the recursion.\n3. The state of recursion is defined by the index which we are currently processing in the original expression. Let this index be represented by the character `i`. Also, we have two different variables `left_count` and `right_count` that represent the number of left and right parentheses we have added to our expression till now. These are the parentheses that were considered.\n4. If the current character i.e. `S[i]` (considering S is the expression string) is neither a closing or an opening parenthesis, then we simply add this character to our final solution string for the current recursion.\n5. However, if the current character is either of the two brackets i.e. `S[i] == '(' or S[i] == ')'`, then we have two options. We can either discard this character by marking it an invalid character or we can consider this bracket to be a part of the final expression.\n6. When all of the parentheses in the original expression have been processed, we simply check if the expression represented by `expr` i.e. the expression formed till now is valid one or not. The way we check if the final expression is valid or not is by looking at the values in `left_count` and `right_count`. For an expression to be valid `left_count == right_count`. If it is indeed valid, then it could be one of our possible solutions.\n    * Even though we have a valid expression, we also need to keep track of the number of removals we did to get this expression. This is done by another variable passed in recursion called `rem_count`.\n    * Once recursion finishes we check if the current value of `rem_count` is < the least number of steps we took to form a valid expression till now i.e. the global minima. If this is not the case, we don't record the new expression, else we record it.\n\nOne small optimization that we can do from an implementation perspective is introducing some sort of pruning in our algorithm. Right now we simply go till the very end i.e. process all of the parentheses and when we are done processing all of them, we check if the expression we have can be considered or not.\n\nWe have to wait till the very end to decide if the expression formed in recursion is a valid expression or not. Is there a way for us to cutoff from some of the recursion paths early on because they wouldn't lead to a solution? The answer to this is Yes! The optimization is based on the following idea.\n\nFor a left bracket encountered during recursion, if we decide to consider it, then it may or may not lead to an invalid final expression. It may lead to an invalid expression eventually if there are no matching closing bracket available afterwards. But, we don't know for sure if this will happen or not.\n\n> However, for a closing bracket, if we decide to keep it as a part of our final expression (remember for every bracket we have two options, either to keep it or to remove it and recurse further) and there is no corresponding opening bracket to match it in the expression till now, then it will definitely lead to an invalid expression no matter what we do afterwards.\n\ne.g.\n\n<pre>\n( (  ) ) )\n</pre>\n\nIn this case the third closing bracket will make the expression invalid. No matter what comes afterwards, this will give us an invalid expression and if such a thing happens, we shouldn't recurse further and simply prune the recursion tree.\n\nThat is why, in addition to having the index in the original string/expression which we are currently processing and the expression string formed till now, we also keep track of the number of left and right parentheses. Whenever we keep a left parenthesis in the expression, we increment its counter. For a right parenthesis, we check if `right_count < left_count`. If this is the case then only we consider that right parenthesis and recurse further. Otherwise we don't as we know it will make the expression invalid. This simple optimization saves a lot of runtime.\n\nNow, let us look at the implementation for this algorithm.\n\n<iframe src=\"https://leetcode.com/playground/ZNSLoChx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ZNSLoChx\"></iframe>\n\n**Complexity analysis**\n\n* Time Complexity : $$O(2^N)$$ since in the worst case we will have only left parentheses in the expression and for every bracket we will have two options i.e. whether to remove it or consider it. Considering that the expression has $$N$$ parentheses, the time complexity will be $$O(2^N)$$.\n* Space Complexity : $$O(N)$$ because we are resorting to a recursive solution and for a recursive solution there is always stack space used as internal function states are saved onto a stack during recursion. The maximum depth of recursion decides the stack space used. Since we process one character at a time and the base case for the recursion is when we have processed all of the characters of the expression string, the size of the stack would be $$O(N)$$. Note that we are not considering the space required to store the valid expressions. We only count the intermediate space here.\n<br />\n<br />\n\n---\n\n### Approach 2: Limited Backtracking!\n\nAlthough the previous solution does get accepted on the platform, it is a very inefficient solution because we try removing each and every possible parentheses from the expression and in the end we check two things:\n\n1. if the expression is valid or not\n2. if the total number of removed parentheses removed in the current recursion is less than the global minimum till now or not.\n\nWe cannot determine which of the parentheses are misplaced because, as the problem statement puts across, we can remove multiple combinations of parentheses and end up with a valid expression. This means there can be multiple valid expressions from a single invalid expression and we have to find all of them.\n\n> The one thing all these valid expressions have in common is that they will all be of the same length i.e. as compared to the original expression, all of these expressions will have the same number of characters removed.\n\nWhat if we could determine this count?\n\nWhat if in addition to determining this count of characters to be removed, we could also determine the number of left parentheses and number of right parentheses to be removed from the original expression to get **any** valid expression?\n\nThis would cut down the computations immensely and the runtime would plummet as a result. The reason for this is, if we knew how many left and right parentheses are to be removed from the original expression to get a valid expression, we would cut down on so many unwanted recursive calls.\n\nImagine the original expression to be 1000 characters with only 3 misplaced `(` parentheses and 2 misplaced `)` parentheses. In our previous solution we would end up trying to remove each one of left and right parentheses and try to reach a valid expression in the end whereas we should only be trying out removing 3 `(` brackets and 2 `)` brackets.\n\n> This is the exact number of `(` and `)` that have to be removed to get a valid expression. No more, no less.\n\nLet us look at how we can find out the number of misplaced left and right parentheses in a given expression first and then we will slightly modify our original algorithm to incorporate these counts as well.\n\n1. We process the expression one bracket at a time starting from the left.\n2. Suppose we encounter an opening bracket i.e. `(`, it may or may not lead to an invalid expression because there can be a matching ending bracket somewhere in the remaining part of the expression. Here, we simply increment the counter keeping track of left parentheses till now. `left += 1`\n3. If we encounter a closing bracket, this has two meanings:\n    * Either there was no matching opening bracket for this closing bracket and in that case we have an invalid expression. This is the case when `left == 0` i.e. when there are no unmatched left brackets available. In such a case we increment another counter say `right += 1` to represent misplaced right parentheses.\n    * Or, we had some unmatched opening bracket available to match this closing bracket. This is the case when `left > 0`. In this case we simply decrement the left counter we had i.e. `left -= 1`\n4. Continue processing the string until all parentheses have been processed.\n5. In the end the values of `left` and `right` would tell us the number of unmatched `(` and `)` parentheses respectively.\n\nNow that we have these two values available that tell us the total number of left i.e. `(` and right i.e. `)` parentheses that have to be removed to make the invalid expression valid, we will modify our original algorithm discussed in the previous session to avoid unwanted recursions.\n\n**Algorithm**\n\nThe overall algorithm remains exactly the same as before. The changes that we will incorporate are listed below:\n\n* The state of the recursion is now defined by five different variables:\n    1. `index` which represents the current character that we have to process in the original string.\n    2. `left_count` which represents the number of left parentheses that have been added to the expression we are building.\n    3. `right_count` which represents the number of right parentheses that have been added to the expression we are building.\n    4. `left_rem` is the number of left parentheses that remain to be removed.\n    5. `right_rem` represents the number of right parentheses that remain to be removed. Overall, for the final expression to be valid, `left_rem == 0` and `right_rem == 0`.\n* When we decide to not consider a parenthesis i.e. delete a parenthesis, be it a left or a right parentheses, we have to consider their corresponding remaining counts as well. This means that we can only discard a left parentheses if `left_rem > 0` and similarly for the right one we will check for `right_rem > 0`.\n* There are no changes to checks for **considering** a parenthesis. Only the conditions change for **discarding** a parenthesis.\n* Condition for an expression being valid in the base case would now become `left_rem == 0 and right_rem == 0`. Note that we don't have to check if `left_count == right_count` anymore because in the case of a valid expression, we would have removed all the misplaced or invalid parenthesis by the time the recursion ends. So, the only check we need if `left_rem == 0 and right_rem == 0`.\n\n> The most important thing here is that we have completely gotten rid of checking if the number of parentheses removed is lesser than the current minimum or not. The reason for this is we always remove the same number of parentheses as defined by `left_rem + right_rem` at the start of recursion.\n\nNow let us look at the implementation for this modified version of algorithm.\n\n<iframe src=\"https://leetcode.com/playground/bjCaADnt/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"bjCaADnt\"></iframe>\n\n**Complexity analysis**\n\n* Time Complexity : The optimization that we have performed is simply a better form of pruning. Pruning here is something that will vary from one test case to another. In the worst case, we can have something like `(((((((((` and the `left_rem = len(S)` and in such a case we can discard all of the characters because all are misplaced. So, in the worst case we **still** have 2 options per parenthesis and that gives us a complexity of $$O(2^N)$$.\n* Space Complexity : The space complexity remains the same i.e. $$O(N)$$ as previous solution. We have to go to a maximum recursion depth of $$N$$ before hitting the base case. Note that we are not considering the space required to store the valid expressions. We only count the intermediate space here.\n\n<br />\n<br />",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeInvalidParentheses(self, s: str) -> List[str]:\n    def getLeftAndRightCounts(s: str) -> tuple:\n      l = 0\n      r = 0\n\n      for c in s:\n        if c == '(':\n          l += 1\n        elif c == ')':\n          if l == 0:\n            r += 1\n          else:\n            l -= 1\n\n      return l, r\n\n    def isValid(s: str):\n      count = 0  # Number of '(' - # Of ')'\n      for c in s:\n        if c == '(':\n          count += 1\n        elif c == ')':\n          count -= 1\n        if count < 0:\n          return False\n      return True  # Count == 0\n\n    ans = []\n\n    def dfs(s: str, start: int, l: int, r: int) -> None:\n      if l == 0 and r == 0 and isValid(s):\n        ans.append(s)\n        return\n\n      for i in range(start, len(s)):\n        if i > start and s[i] == s[i - 1]:\n          continue\n        if r > 0 and s[i] == ')':  # Delete s[i]\n          dfs(s[:i] + s[i + 1:], i, l, r - 1)\n        elif l > 0 and s[i] == '(':  # Delete s[i]\n          dfs(s[:i] + s[i + 1:], i, l - 1, r)\n\n    l, r = getLeftAndRightCounts(s)\n    dfs(s, 0, l, r)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> removeInvalidParentheses(String s) {\n    List<String> ans = new ArrayList<>();\n    final int[] counts = getLeftAndRightCounts(s);\n    dfs(s, 0, counts[0], counts[1], ans);\n    return ans;\n  }\n\n  // Very simliar to 921. Minimum Add to Make Parentheses Valid\n  // Returns how many '(' and ')' need to be deleted\n  private int[] getLeftAndRightCounts(final String s) {\n    int l = 0;\n    int r = 0;\n\n    for (final char c : s.toCharArray())\n      if (c == '(')\n        ++l;\n      else if (c == ')') {\n        if (l == 0)\n          ++r;\n        else\n          --l;\n      }\n\n    return new int[] {l, r};\n  }\n\n  private void dfs(final String s, int start, int l, int r, List<String> ans) {\n    if (l == 0 && r == 0 && isValid(s)) {\n      ans.add(s);\n      return;\n    }\n\n    for (int i = start; i < s.length(); ++i) {\n      if (i > start && s.charAt(i) == s.charAt(i - 1))\n        continue;\n      if (l > 0 && s.charAt(i) == '(') // Delete s[i]\n        dfs(s.substring(0, i) + s.substring(i + 1), i, l - 1, r, ans);\n      else if (r > 0 && s.charAt(i) == ')') // Delete s[i]\n        dfs(s.substring(0, i) + s.substring(i + 1), i, l, r - 1, ans);\n    }\n  }\n\n  private boolean isValid(final String s) {\n    int count = 0; // # of '(' - # of ')'\n\n    for (final char c : s.toCharArray()) {\n      if (c == '(')\n        ++count;\n      else if (c == ')')\n        --count;\n      if (count < 0)\n        return false;\n    }\n\n    return true; // Count == 0\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> removeInvalidParentheses(string s) {\n    vector<string> ans;\n    const auto [l, r] = getLeftAndRightCounts(s);\n    dfs(s, 0, l, r, ans);\n    return ans;\n  }\n\n private:\n  // Very simliar to 921. Minimum Add to Make Parentheses Valid\n  // Returns how many '(' and ')' need to be deleted\n  pair<int, int> getLeftAndRightCounts(const string& s) {\n    int l = 0;\n    int r = 0;\n\n    for (const char c : s)\n      if (c == '(')\n        ++l;\n      else if (c == ')') {\n        if (l == 0)\n          ++r;\n        else\n          --l;\n      }\n\n    return {l, r};\n  }\n\n  void dfs(const string& s, int start, int l, int r, vector<string>& ans) {\n    if (l == 0 && r == 0 && isValid(s)) {\n      ans.push_back(s);\n      return;\n    }\n\n    for (int i = start; i < s.length(); ++i) {\n      if (i > start && s[i] == s[i - 1])\n        continue;\n      if (l > 0 && s[i] == '(')  // Delete s[i]\n        dfs(s.substr(0, i) + s.substr(i + 1), i, l - 1, r, ans);\n      if (r > 0 && s[i] == ')')  // Delete s[i]\n        dfs(s.substr(0, i) + s.substr(i + 1), i, l, r - 1, ans);\n    }\n  }\n\n  bool isValid(const string& s) {\n    int count = 0;  // # of '(' - # of ')'\n\n    for (const char c : s) {\n      if (c == '(')\n        ++count;\n      else if (c == ')')\n        --count;\n      if (count < 0)\n        return false;\n    }\n\n    return true;  // Count == 0\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/301.html",
    "category": "Algorithms",
    "acceptance_rate": 49.11838136938045,
    "topics": [
      "String",
      "Backtracking",
      "Breadth-First Search"
    ],
    "hints": [
      "Since we do not know which brackets can be removed, we try all the options! We can use recursion.",
      "In the recursion, for each bracket, we can either use it or remove it.",
      "Recursion will generate all the valid parentheses strings but we want the ones with the least number of parentheses deleted.",
      "We can count the number of invalid brackets to be deleted and only generate the valid strings in the recusrion."
    ],
    "likes": 5970,
    "dislikes": 297,
    "similar_questions": "[{\"title\": \"Valid Parentheses\", \"titleSlug\": \"valid-parentheses\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Swaps to Make the String Balanced\", \"titleSlug\": \"minimum-number-of-swaps-to-make-the-string-balanced\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"473K\", \"totalSubmission\": \"962.9K\", \"totalAcceptedRaw\": 472954, \"totalSubmissionRaw\": 962886, \"acRate\": \"49.1%\"}",
    "title_pt": "Remover Parênteses Inválidos",
    "description_pt": "<p>Dada uma string <code>s</code> que contém parênteses e letras, remova o número mínimo de parênteses inválidos para tornar a string de entrada válida.</p>\n\n<p>Retorne <em>uma lista de <strong>strings únicas</strong> que sejam válidas com o número mínimo de remoções</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;()())()&quot;\n<strong>Saída:</strong> [&quot;(())()&quot;,&quot;()()()&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;(a)())()&quot;\n<strong>Saída:</strong> [&quot;(a())()&quot;,&quot;(a)()()&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;)(&quot;\n<strong>Saída:</strong> [&quot;&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 25</code></li>\n\t<li><code>s</code> consiste em letras minúsculas do inglês e parênteses <code>&#39;(&#39;</code> e <code>&#39;)&#39;</code>.</li>\n\t<li>Haverá no máximo <code>20</code> parênteses em <code>s</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Como não sabemos quais colchetes podem ser removidos, tentamos todas as opções! Podemos usar recursão.",
      "Dica 2: Na recursão, para cada colchete, podemos usá-lo ou removê-lo.",
      "Dica 3: A recursão gerará todas as strings de parênteses válidas, mas queremos aquelas com a menor quantidade de parênteses removidos.",
      "Dica 4: Podemos contar o número de colchetes inválidos a serem removidos e gerar apenas as strings válidas na recursão."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "303",
    "paidOnly": false,
    "title": "Range Sum Query - Immutable",
    "titleSlug": "range-sum-query-immutable",
    "url": "https://leetcode.com/problems/range-sum-query-immutable",
    "description_url": "https://leetcode.com/problems/range-sum-query-immutable/description/",
    "description": "<p>Given an integer array <code>nums</code>, handle multiple queries of the following type:</p>\n\n<ol>\n\t<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li>\n</ol>\n\n<p>Implement the <code>NumArray</code> class:</p>\n\n<ul>\n\t<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>\n\t<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\n<strong>Output</strong>\n[null, 1, -1, -3]\n\n<strong>Explanation</strong>\nNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRange</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/range-sum-query-immutable/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass NumArray:\n  def __init__(self, nums: List[int]):\n    self.prefix = [0] + list(itertools.accumulate(nums))\n\n  def sumRange(self, left: int, right: int) -> int:\n    return self.prefix[right + 1] - self.prefix[left]",
    "solution_code_java": "\t\t\t\n\nclass NumArray {\n  public NumArray(int[] nums) {\n    prefix = new int[nums.length + 1];\n    for (int i = 0; i < nums.length; ++i)\n      prefix[i + 1] = nums[i] + prefix[i];\n  }\n\n  public int sumRange(int left, int right) {\n    return prefix[right + 1] - prefix[left];\n  }\n\n  private int[] prefix;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass NumArray {\n public:\n  NumArray(vector<int>& nums) : prefix(nums.size() + 1) {\n    partial_sum(begin(nums), end(nums), begin(prefix) + 1);\n  }\n\n  int sumRange(int left, int right) {\n    return prefix[right + 1] - prefix[left];\n  }\n\n private:\n  vector<int> prefix;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/303.html",
    "category": "Algorithms",
    "acceptance_rate": 68.07736694259881,
    "topics": [
      "Array",
      "Design",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 3490,
    "dislikes": 1963,
    "similar_questions": "[{\"title\": \"Range Sum Query 2D - Immutable\", \"titleSlug\": \"range-sum-query-2d-immutable\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Sum Query - Mutable\", \"titleSlug\": \"range-sum-query-mutable\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Size Subarray Sum Equals k\", \"titleSlug\": \"maximum-size-subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Variable Length Subarrays\", \"titleSlug\": \"sum-of-variable-length-subarrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"702.6K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 702554, \"totalSubmissionRaw\": 1031991, \"acRate\": \"68.1%\"}",
    "title_pt": "Consulta de Soma em Intervalo - Imutável",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, trate múltiplas consultas do seguinte tipo:</p>\n\n<ol>\n\t<li>Calcule a <strong>soma</strong> dos elementos de <code>nums</code> entre os índices <code>left</code> e <code>right</code> <strong>inclusive</strong>, onde <code>left &lt;= right</code>.</li>\n</ol>\n\n<p>Implemente a classe <code>NumArray</code>:</p>\n\n<ul>\n\t<li><code>NumArray(int[] nums)</code> Inicializa o objeto com o array de inteiros <code>nums</code>.</li>\n\t<li><code>int sumRange(int left, int right)</code> Retorna a <strong>soma</strong> dos elementos de <code>nums</code> entre os índices <code>left</code> e <code>right</code> <strong>inclusive</strong> (isto é, <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;, &quot;sumRange&quot;]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\n<strong>Saída</strong>\n[null, 1, -1, -3]\n\n<strong>Explicação</strong>\nNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>sumRange</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "304",
    "paidOnly": false,
    "title": "Range Sum Query 2D - Immutable",
    "titleSlug": "range-sum-query-2d-immutable",
    "url": "https://leetcode.com/problems/range-sum-query-2d-immutable",
    "description_url": "https://leetcode.com/problems/range-sum-query-2d-immutable/description/",
    "description": "<p>Given a 2D matrix <code>matrix</code>, handle multiple queries of the following type:</p>\n\n<ul>\n\t<li>Calculate the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>Implement the <code>NumMatrix</code> class:</p>\n\n<ul>\n\t<li><code>NumMatrix(int[][] matrix)</code> Initializes the object with the integer matrix <code>matrix</code>.</li>\n\t<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Returns the <strong>sum</strong> of the elements of <code>matrix</code> inside the rectangle defined by its <strong>upper left corner</strong> <code>(row1, col1)</code> and <strong>lower right corner</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>You must design an algorithm where <code>sumRegion</code> works on <code>O(1)</code> time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg\" style=\"width: 415px; height: 415px;\" />\n<pre>\n<strong>Input</strong>\n[&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\n<strong>Output</strong>\n[null, 8, 11, 12]\n\n<strong>Explanation</strong>\nNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li>\n\t<li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>sumRegion</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/range-sum-query-2d-immutable/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass NumMatrix:\n  def __init__(self, matrix: List[List[int]]):\n    if not matrix:\n      return\n\n    m = len(matrix)\n    n = len(matrix[0])\n    # prefix[i][j] := sum of matrix[0..i)[0..j)\n    self.prefix = [[0] * (n + 1) for _ in range(m + 1)]\n\n    for i in range(m):\n      for j in range(n):\n        self.prefix[i + 1][j + 1] = \\\n            matrix[i][j] + self.prefix[i][j + 1] + \\\n            self.prefix[i + 1][j] - self.prefix[i][j]\n\n  def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n    return self.prefix[row2 + 1][col2 + 1] - self.prefix[row1][col2 + 1] - \\\n        self.prefix[row2 + 1][col1] + self.prefix[row1][col1]",
    "solution_code_java": "\t\t\t\n\nclass NumMatrix {\n  public NumMatrix(int[][] matrix) {\n    if (matrix.length == 0)\n      return;\n\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    // prefix[i][j] := sum of matrix[0..i)[0..j)\n    prefix = new int[m + 1][n + 1];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        prefix[i + 1][j + 1] = matrix[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];\n  }\n\n  public int sumRegion(int row1, int col1, int row2, int col2) {\n    return prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1]\n         - prefix[row2 + 1][col1] + prefix[row1][col1];\n  }\n\n  private int[][] prefix;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass NumMatrix {\n public:\n  NumMatrix(vector<vector<int>>& matrix) {\n    if (matrix.empty())\n      return;\n\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    // prefix[i][j] := sum of matrix[0..i)[0..j)\n    prefix.resize(m + 1, vector<int>(n + 1));\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        prefix[i + 1][j + 1] =\n            matrix[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j];\n  }\n\n  int sumRegion(int row1, int col1, int row2, int col2) {\n    return prefix[row2 + 1][col2 + 1] - prefix[row1][col2 + 1] -\n           prefix[row2 + 1][col1] + prefix[row1][col1];\n  }\n\n private:\n  vector<vector<int>> prefix;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/304.html",
    "category": "Algorithms",
    "acceptance_rate": 56.333719077071066,
    "topics": [
      "Array",
      "Design",
      "Matrix",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 5139,
    "dislikes": 355,
    "similar_questions": "[{\"title\": \"Range Sum Query - Immutable\", \"titleSlug\": \"range-sum-query-immutable\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Range Sum Query 2D - Mutable\", \"titleSlug\": \"range-sum-query-2d-mutable\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Grid of Region Average\", \"titleSlug\": \"find-the-grid-of-region-average\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"418.1K\", \"totalSubmission\": \"742.3K\", \"totalAcceptedRaw\": 418150, \"totalSubmissionRaw\": 742279, \"acRate\": \"56.3%\"}",
    "title_pt": "Consulta de Soma de Intervalo 2D - Imutável",
    "description_pt": "<p>Dada uma matriz 2D <code>matrix</code>, lide com múltiplas consultas do seguinte tipo:</p>\n\n<ul>\n\t<li>Calcule a <strong>soma</strong> dos elementos de <code>matrix</code> dentro do retângulo definido pelo seu <strong>canto superior esquerdo</strong> <code>(row1, col1)</code> e <strong>canto inferior direito</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>Implemente a classe <code>NumMatrix</code>:</p>\n\n<ul>\n\t<li><code>NumMatrix(int[][] matrix)</code> Inicializa o objeto com a matriz inteira <code>matrix</code>.</li>\n\t<li><code>int sumRegion(int row1, int col1, int row2, int col2)</code> Retorna a <strong>soma</strong> dos elementos de <code>matrix</code> dentro do retângulo definido pelo seu <strong>canto superior esquerdo</strong> <code>(row1, col1)</code> e <strong>canto inferior direito</strong> <code>(row2, col2)</code>.</li>\n</ul>\n\n<p>Você deve projetar um algoritmo em que <code>sumRegion</code> funcione com complexidade de tempo <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/sum-grid.jpg\" style=\"width: 415px; height: 415px;\" />\n<pre>\n<strong>Entrada</strong>\n[&quot;NumMatrix&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;, &quot;sumRegion&quot;]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\n<strong>Saída</strong>\n[null, 8, 11, 12]\n\n<strong>Explicação</strong>\nNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= matrix[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= row1 &lt;= row2 &lt; m</code></li>\n\t<li><code>0 &lt;= col1 &lt;= col2 &lt; n</code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>sumRegion</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "306",
    "paidOnly": false,
    "title": "Additive Number",
    "titleSlug": "additive-number",
    "url": "https://leetcode.com/problems/additive-number",
    "description_url": "https://leetcode.com/problems/additive-number/description/",
    "description": "<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>\n\n<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>\n\n<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>\n\n<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> &quot;112358&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> \nThe digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> &quot;199100199&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> \nThe additive sequence is: 1, 99, 100, 199.&nbsp;\n1 + 99 = 100, 99 + 100 = 199\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num.length &lt;= 35</code></li>\n\t<li><code>num</code> consists only of digits.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>\n",
    "solution_url": "https://leetcode.com/problems/additive-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isAdditiveNumber(self, num: str) -> bool:\n    n = len(num)\n\n    def dfs(firstNum: int, secondNum: int, s: int) -> bool:\n      if s == len(num):\n        return True\n\n      thirdNum = firstNum + secondNum\n      thirdNumStr = str(thirdNum)\n\n      return num.find(thirdNumStr, s) == s and dfs(secondNum, thirdNum, s + len(thirdNumStr))\n\n    # num[0..i] = firstNum\n    for i in range(n // 2):\n      if i > 0 and num[0] == '0':\n        return False\n      firstNum = int(num[:i + 1])\n      # num[i + 1..j] = secondNum\n      # Len(thirdNum) >= max(len(firstNum), len(secondNum))\n      j = i + 1\n      while max(i, j - i) < n - j:\n        if j > i + 1 and num[i + 1] == '0':\n          break\n        secondNum = int(num[i + 1:j + 1])\n        if dfs(firstNum, secondNum, j + 1):\n          return True\n        j += 1\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isAdditiveNumber(String num) {\n    final int n = num.length();\n\n    // num[0..i] = firstNum\n    for (int i = 0; i < n / 2; ++i) {\n      if (i > 0 && num.charAt(0) == '0')\n        return false;\n      final long firstNum = Long.parseLong(num.substring(0, i + 1));\n      // num[i + 1..j] = secondNum\n      // Len(thirdNum) >= max(len(firstNum), len(secondNum))\n      for (int j = i + 1; Math.max(i, j - i) < n - j; ++j) {\n        if (j > i + 1 && num.charAt(i + 1) == '0')\n          break;\n        final long secondNum = Long.parseLong(num.substring(i + 1, j + 1));\n        if (dfs(num, firstNum, secondNum, j + 1))\n          return true;\n      }\n    }\n\n    return false;\n  }\n\n  private boolean dfs(final String num, long firstNum, long secondNum, long s) {\n    if (s == num.length())\n      return true;\n\n    final long thirdNum = firstNum + secondNum;\n    final String thirdNumStr = String.valueOf(thirdNum);\n    return num.indexOf(thirdNumStr, (int) s) == s &&\n        dfs(num, secondNum, thirdNum, s + thirdNumStr.length());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isAdditiveNumber(string num) {\n    const int n = num.length();\n\n    // num[0..i] = firstNum\n    for (int i = 0; i < n / 2; ++i) {\n      if (i > 0 && num[0] == '0')\n        return false;\n      const long firstNum = stol(num.substr(0, i + 1));\n      // num[i + 1..j] = secondNum\n      // Len(thirdNum) >= max(len(firstNum), len(secondNum))\n      for (int j = i + 1; max(i, j - i) < n - j; ++j) {\n        if (j > i + 1 && num[i + 1] == '0')\n          break;\n        const long secondNum = stol(num.substr(i + 1, j - i));\n        if (dfs(num, firstNum, secondNum, j + 1))\n          return true;\n      }\n    }\n\n    return false;\n  }\n\n private:\n  bool dfs(const string& num, long firstNum, long secondNum, long s) {\n    if (s == num.length())\n      return true;\n\n    const long thirdNum = firstNum + secondNum;\n    const string& thirdNumStr = to_string(thirdNum);\n    return num.find(thirdNumStr, s) == s &&\n           dfs(num, secondNum, thirdNum, s + thirdNumStr.length());\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/306.html",
    "category": "Algorithms",
    "acceptance_rate": 32.45252917070729,
    "topics": [
      "String",
      "Backtracking"
    ],
    "hints": [],
    "likes": 1215,
    "dislikes": 814,
    "similar_questions": "[{\"title\": \"Split Array into Fibonacci Sequence\", \"titleSlug\": \"split-array-into-fibonacci-sequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"103.7K\", \"totalSubmission\": \"319.7K\", \"totalAcceptedRaw\": 103741, \"totalSubmissionRaw\": 319670, \"acRate\": \"32.5%\"}",
    "title_pt": "Número Aditivo",
    "description_pt": "<p>Um <strong>número aditivo</strong> é uma string cujos dígitos podem formar uma <strong>sequência aditiva</strong>.</p>\n\n<p>Uma <strong>sequência aditiva</strong> válida deve conter <strong>pelo menos</strong> três números. Exceto pelos dois primeiros números, cada número subsequente na sequência deve ser a soma dos dois números anteriores.</p>\n\n<p>Dada uma string contendo apenas dígitos, retorne <code>true</code> se ela for um <strong>número aditivo</strong> ou <code>false</code> caso contrário.</p>\n\n<p><strong>Nota:</strong> Números na sequência aditiva <strong>não podem</strong> ter zeros à esquerda, então a sequência <code>1, 2, 03</code> ou <code>1, 02, 3</code> é inválida.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> &quot;112358&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> \nOs dígitos podem formar uma sequência aditiva: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> &quot;199100199&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> \nA sequência aditiva é: 1, 99, 100, 199.&nbsp;\n1 + 99 = 100, 99 + 100 = 199\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num.length &lt;= 35</code></li>\n\t<li><code>num</code> consiste apenas de dígitos.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Como você lidaria com overflow para inteiros de entrada muito grandes?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "307",
    "paidOnly": false,
    "title": "Range Sum Query - Mutable",
    "titleSlug": "range-sum-query-mutable",
    "url": "https://leetcode.com/problems/range-sum-query-mutable",
    "description_url": "https://leetcode.com/problems/range-sum-query-mutable/description/",
    "description": "<p>Given an integer array <code>nums</code>, handle multiple queries of the following types:</p>\n\n<ol>\n\t<li><strong>Update</strong> the value of an element in <code>nums</code>.</li>\n\t<li>Calculate the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> where <code>left &lt;= right</code>.</li>\n</ol>\n\n<p>Implement the <code>NumArray</code> class:</p>\n\n<ul>\n\t<li><code>NumArray(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>\n\t<li><code>void update(int index, int val)</code> <strong>Updates</strong> the value of <code>nums[index]</code> to be <code>val</code>.</li>\n\t<li><code>int sumRange(int left, int right)</code> Returns the <strong>sum</strong> of the elements of <code>nums</code> between indices <code>left</code> and <code>right</code> <strong>inclusive</strong> (i.e. <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;update&quot;, &quot;sumRange&quot;]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\n<strong>Output</strong>\n[null, 9, null, 8]\n\n<strong>Explanation</strong>\nNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2);   // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>0 &lt;= index &lt; nums.length</code></li>\n\t<li><code>-100 &lt;= val &lt;= 100</code></li>\n\t<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>update</code> and <code>sumRange</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/range-sum-query-mutable/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass FenwickTree:\n  def __init__(self, n: int):\n    self.sums = [0] * (n + 1)\n\n  def update(self, i: int, delta: int) -> None:\n    while i < len(self.sums):\n      self.sums[i] += delta\n      i += self._lowbit(i)\n\n  def get(self, i: int) -> int:\n    summ = 0\n    while i > 0:\n      summ += self.sums[i]\n      i -= self._lowbit(i)\n    return summ\n\n  def _lowbit(self, i) -> int:\n    return i & -i\n\n\nclass NumArray:\n  def __init__(self, nums: List[int]):\n    self.nums = nums\n    self.tree = FenwickTree(len(nums))\n    for i, num in enumerate(nums):\n      self.tree.update(i + 1, num)\n\n  def update(self, index: int, val: int) -> None:\n    self.tree.update(index + 1, val - self.nums[index])\n    self.nums[index] = val\n\n  def sumRange(self, left: int, right: int) -> int:\n    return self.tree.get(right + 1) - self.tree.get(left)",
    "solution_code_java": "\t\t\t\n\nclass FenwickTree {\n  public FenwickTree(int n) {\n    sums = new int[n + 1];\n  }\n\n  public void update(int i, int delta) {\n    while (i < sums.length) {\n      sums[i] += delta;\n      i += lowbit(i);\n    }\n  }\n\n  public int get(int i) {\n    int sum = 0;\n    while (i > 0) {\n      sum += sums[i];\n      i -= lowbit(i);\n    }\n    return sum;\n  }\n\n  private int[] sums;\n\n  private static int lowbit(int i) {\n    return i & -i;\n  }\n}\n\nclass NumArray {\n  public NumArray(int[] nums) {\n    this.nums = nums;\n    tree = new FenwickTree(nums.length);\n    for (int i = 0; i < nums.length; ++i)\n      tree.update(i + 1, nums[i]);\n  }\n\n  public void update(int index, int val) {\n    tree.update(index + 1, val - nums[index]);\n    nums[index] = val;\n  }\n\n  public int sumRange(int left, int right) {\n    return tree.get(right + 1) - tree.get(left);\n  }\n\n  private int[] nums;\n  private FenwickTree tree;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass FenwickTree {\n public:\n  FenwickTree(int n) : sums(n + 1) {}\n\n  void update(int i, int delta) {\n    while (i < sums.size()) {\n      sums[i] += delta;\n      i += lowbit(i);\n    }\n  }\n\n  int get(int i) const {\n    int sum = 0;\n    while (i > 0) {\n      sum += sums[i];\n      i -= lowbit(i);\n    }\n    return sum;\n  }\n\n private:\n  vector<int> sums;\n\n  static inline int lowbit(int i) {\n    return i & -i;\n  }\n};\n\nclass NumArray {\n public:\n  NumArray(vector<int>& nums) : nums(nums), tree(nums.size()) {\n    for (int i = 0; i < nums.size(); ++i)\n      tree.update(i + 1, nums[i]);\n  }\n\n  void update(int index, int val) {\n    tree.update(index + 1, val - nums[index]);\n    nums[index] = val;\n  }\n\n  int sumRange(int left, int right) {\n    return tree.get(right + 1) - tree.get(left);\n  }\n\n private:\n  vector<int> nums;\n  FenwickTree tree;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/307.html",
    "category": "Algorithms",
    "acceptance_rate": 41.643442774639375,
    "topics": [
      "Array",
      "Design",
      "Binary Indexed Tree",
      "Segment Tree"
    ],
    "hints": [],
    "likes": 4923,
    "dislikes": 259,
    "similar_questions": "[{\"title\": \"Range Sum Query - Immutable\", \"titleSlug\": \"range-sum-query-immutable\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Range Sum Query 2D - Mutable\", \"titleSlug\": \"range-sum-query-2d-mutable\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shifting Letters II\", \"titleSlug\": \"shifting-letters-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"303.8K\", \"totalSubmission\": \"729.5K\", \"totalAcceptedRaw\": 303783, \"totalSubmissionRaw\": 729489, \"acRate\": \"41.6%\"}",
    "title_pt": "Consulta de Soma em Intervalo - Mutável",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, trate múltiplas consultas dos seguintes tipos:</p>\n\n<ol>\n\t<li><strong>Atualize</strong> o valor de um elemento em <code>nums</code>.</li>\n\t<li>Calcule a <strong>soma</strong> dos elementos de <code>nums</code> entre os índices <code>left</code> e <code>right</code> <strong>inclusive</strong>, onde <code>left &lt;= right</code>.</li>\n</ol>\n\n<p>Implemente a classe <code>NumArray</code>:</p>\n\n<ul>\n\t<li><code>NumArray(int[] nums)</code> Inicializa o objeto com o array de inteiros <code>nums</code>.</li>\n\t<li><code>void update(int index, int val)</code> <strong>Atualiza</strong> o valor de <code>nums[index]</code> para ser <code>val</code>.</li>\n\t<li><code>int sumRange(int left, int right)</code> Retorna a <strong>soma</strong> dos elementos de <code>nums</code> entre os índices <code>left</code> e <code>right</code> <strong>inclusive</strong> (ou seja <code>nums[left] + nums[left + 1] + ... + nums[right]</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;NumArray&quot;, &quot;sumRange&quot;, &quot;update&quot;, &quot;sumRange&quot;]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\n<strong>Saída</strong>\n[null, 9, null, 8]\n\n<strong>Explicação</strong>\nNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2);   // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n\t<li><code>0 &lt;= index &lt; nums.length</code></li>\n\t<li><code>-100 &lt;= val &lt;= 100</code></li>\n\t<li><code>0 &lt;= left &lt;= right &lt; nums.length</code></li>\n\t<li>No máximo <code>3 * 10<sup>4</sup></code> chamadas serão feitas para <code>update</code> e <code>sumRange</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "309",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock with Cooldown",
    "titleSlug": "best-time-to-buy-and-sell-stock-with-cooldown",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/",
    "description": "<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day.</p>\n\n<p>Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:</p>\n\n<ul>\n\t<li>After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).</li>\n</ul>\n\n<p><strong>Note:</strong> You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1,2,3,0,2]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> transactions = [buy, sell, cooldown, buy, sell]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, prices: List[int]) -> int:\n    sell = 0\n    hold = -math.inf\n    prev = 0\n\n    for price in prices:\n      cache = sell\n      sell = max(sell, hold + price)\n      hold = max(hold, prev - price)\n      prev = cache\n\n    return sell",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int[] prices) {\n    int sell = 0;\n    int hold = Integer.MIN_VALUE;\n    int prev = 0;\n\n    for (final int price : prices) {\n      final int cache = sell;\n      sell = Math.max(sell, hold + price);\n      hold = Math.max(hold, prev - price);\n      prev = cache;\n    }\n\n    return sell;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(vector<int>& prices) {\n    int sell = 0;\n    int hold = INT_MIN;\n    int prev = 0;\n\n    for (const int price : prices) {\n      const int cache = sell;\n      sell = max(sell, hold + price);\n      hold = max(hold, prev - price);\n      prev = cache;\n    }\n\n    return sell;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/309.html",
    "category": "Algorithms",
    "acceptance_rate": 60.14166515457101,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 9701,
    "dislikes": 340,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock\", \"titleSlug\": \"best-time-to-buy-and-sell-stock\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Best Time to Buy and Sell Stock II\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"633.1K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 633061, \"totalSubmissionRaw\": 1052619, \"acRate\": \"60.1%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ações com Cooldown",
    "description_pt": "<p>Você recebe um array <code>prices</code> em que <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia.</p>\n\n<p>Encontre o lucro máximo que você pode obter. Você pode completar quantas transações quiser (isto é, comprar uma ação e vender uma ação múltiplas vezes) com as seguintes restrições:</p>\n\n<ul>\n\t<li>Depois que você vender sua ação, você não pode comprar ação no dia seguinte (isto é, cooldown de um dia).</li>\n</ul>\n\n<p><strong>Nota:</strong> Você não pode participar de múltiplas transações simultaneamente (isto é, você deve vender a ação antes de comprá-la novamente).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1,2,3,0,2]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> transactions = [buy, sell, cooldown, buy, sell]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= prices[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "310",
    "paidOnly": false,
    "title": "Minimum Height Trees",
    "titleSlug": "minimum-height-trees",
    "url": "https://leetcode.com/problems/minimum-height-trees",
    "description_url": "https://leetcode.com/problems/minimum-height-trees/description/",
    "description": "<p>A tree is an undirected graph in which any two vertices are connected by&nbsp;<i>exactly</i>&nbsp;one path. In other words, any connected graph without simple cycles is a tree.</p>\n\n<p>Given a tree of <code>n</code> nodes&nbsp;labelled from <code>0</code> to <code>n - 1</code>, and an array of&nbsp;<code>n - 1</code>&nbsp;<code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between the two nodes&nbsp;<code>a<sub>i</sub></code> and&nbsp;<code>b<sub>i</sub></code> in the tree,&nbsp;you can choose any node of the tree as the root. When you select a node <code>x</code> as the root, the result tree has height <code>h</code>. Among all possible rooted trees, those with minimum height (i.e. <code>min(h)</code>)&nbsp; are called <strong>minimum height trees</strong> (MHTs).</p>\n\n<p>Return <em>a list of all <strong>MHTs&#39;</strong> root labels</em>.&nbsp;You can return the answer in <strong>any order</strong>.</p>\n\n<p>The <strong>height</strong> of a rooted tree is the number of edges on the longest downward path between the root and a leaf.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/e1.jpg\" style=\"width: 800px; height: 213px;\" />\n<pre>\n<strong>Input:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]\n<strong>Output:</strong> [1]\n<strong>Explanation:</strong> As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/e2.jpg\" style=\"width: 800px; height: 321px;\" />\n<pre>\n<strong>Input:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\n<strong>Output:</strong> [3,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>edges.length == n - 1</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>All the pairs <code>(a<sub>i</sub>, b<sub>i</sub>)</code> are distinct.</li>\n\t<li>The given input is <strong>guaranteed</strong> to be a tree and there will be <strong>no repeated</strong> edges.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-height-trees/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n    if n == 1 or not edges:\n      return [0]\n\n    ans = []\n    graph = defaultdict(set)\n\n    for u, v in edges:\n      graph[u].add(v)\n      graph[v].add(u)\n\n    for label, children in graph.items():\n      if len(children) == 1:\n        ans.append(label)\n\n    while n > 2:\n      n -= len(ans)\n      nextLeaves = []\n      for leaf in ans:\n        u = next(iter(graph[leaf]))\n        graph[u].remove(leaf)\n        if len(graph[u]) == 1:\n          nextLeaves.append(u)\n      ans = nextLeaves\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findMinHeightTrees(int n, int[][] edges) {\n    if (n == 0 || edges.length == 0)\n      return new ArrayList<>(Arrays.asList(0));\n\n    List<Integer> ans = new ArrayList<>();\n    Map<Integer, Set<Integer>> graph = new HashMap<>();\n\n    for (int i = 0; i < n; ++i)\n      graph.put(i, new HashSet<>());\n\n    for (int[] e : edges) {\n      final int u = e[0];\n      final int v = e[0];\n      graph.get(u).add(v);\n      graph.get(v).add(u);\n    }\n\n    for (Map.Entry<Integer, Set<Integer>> entry : graph.entrySet()) {\n      final int label = entry.getKey();\n      Set<Integer> children = entry.getValue();\n      if (children.size() == 1)\n        ans.add(label);\n    }\n\n    while (n > 2) {\n      n -= ans.size();\n      List<Integer> nextLeaves = new ArrayList<>();\n      for (final int leaf : ans) {\n        final int u = (int) graph.get(leaf).iterator().next();\n        graph.get(u).remove(leaf);\n        if (graph.get(u).size() == 1)\n          nextLeaves.add(u);\n      }\n      ans = nextLeaves;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {\n    if (n == 1 || edges.empty())\n      return {0};\n\n    vector<int> ans;\n    unordered_map<int, unordered_set<int>> graph;\n\n    for (const vector<int>& e : edges) {\n      const int u = e[0];\n      const int v = e[1];\n      graph[u].insert(v);\n      graph[v].insert(u);\n    }\n\n    for (const vector<int> & [ label, children ] : graph)\n      if (children.size() == 1)\n        ans.push_back(label);\n\n    while (n > 2) {\n      n -= ans.size();\n      vector<int> nextLeaves;\n      for (const int leaf : ans) {\n        const int u = *begin(graph[leaf]);\n        graph[u].erase(leaf);\n        if (graph[u].size() == 1)\n          nextLeaves.push_back(u);\n      }\n      ans = nextLeaves;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/310.html",
    "category": "Algorithms",
    "acceptance_rate": 41.951871263735455,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Graph",
      "Topological Sort"
    ],
    "hints": [
      "How many MHTs can a graph have at most?"
    ],
    "likes": 8583,
    "dislikes": 405,
    "similar_questions": "[{\"title\": \"Course Schedule\", \"titleSlug\": \"course-schedule\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Course Schedule II\", \"titleSlug\": \"course-schedule-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Collect Coins in a Tree\", \"titleSlug\": \"collect-coins-in-a-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Pairs of Connectable Servers in a Weighted Tree Network\", \"titleSlug\": \"count-pairs-of-connectable-servers-in-a-weighted-tree-network\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum Diameter After Merging Two Trees\", \"titleSlug\": \"find-minimum-diameter-after-merging-two-trees\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"427K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 427023, \"totalSubmissionRaw\": 1017890, \"acRate\": \"42.0%\"}",
    "title_pt": "Árvores de Altura Mínima",
    "description_pt": "<p>Uma árvore é um grafo não direcionado em que quaisquer dois vértices estão conectados por&nbsp;<i>exatamente</i>&nbsp;um caminho. Em outras palavras, qualquer grafo conexo sem ciclos simples é uma árvore.</p>\n\n<p>Dada uma árvore de <code>n</code> nós&nbsp;rotulados de <code>0</code> a <code>n - 1</code>, e um array de&nbsp;<code>n - 1</code>&nbsp;<code>edges</code> em que <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indica que há uma aresta não direcionada entre os dois nós&nbsp;<code>a<sub>i</sub></code> e&nbsp;<code>b<sub>i</sub></code> na árvore,&nbsp;você pode escolher qualquer nó da árvore como raiz. Quando você seleciona um nó <code>x</code> como raiz, a árvore resultante tem altura <code>h</code>. Entre todas as árvores enraizadas possíveis, aquelas com altura mínima (isto é, <code>min(h)</code>)&nbsp; são chamadas de <strong>árvores de altura mínima</strong> (MHTs).</p>\n\n<p>Retorne <em>uma lista de todos os rótulos das raízes das <strong>MHTs&#39;</strong></em>.&nbsp;Você pode retornar a პასუხa em <strong>qualquer ordem</strong>.</p>\n\n<p>A <strong>altura</strong> de uma árvore enraizada é o número de arestas no caminho descendente mais longo entre a raiz e uma folha.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/e1.jpg\" style=\"width: 800px; height: 213px;\" />\n<pre>\n<strong>Entrada:</strong> n = 4, edges = [[1,0],[1,2],[1,3]]\n<strong>Saída:</strong> [1]\n<strong>Explicação:</strong> Como mostrado, a altura da árvore é 1 quando a raiz é o nó com rótulo 1, que é a única MHT.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/01/e2.jpg\" style=\"width: 800px; height: 321px;\" />\n<pre>\n<strong>Entrada:</strong> n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\n<strong>Saída:</strong> [3,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>edges.length == n - 1</code></li>\n\t<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>Todos os pares <code>(a<sub>i</sub>, b<sub>i</sub>)</code> são distintos.</li>\n\t<li>A entrada fornecida é <strong>garantidamente</strong> uma árvore e não haverá arestas <strong>repetidas</strong>.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Quantas MHTs um grafo pode ter no máximo?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "312",
    "paidOnly": false,
    "title": "Burst Balloons",
    "titleSlug": "burst-balloons",
    "url": "https://leetcode.com/problems/burst-balloons",
    "description_url": "https://leetcode.com/problems/burst-balloons/description/",
    "description": "<p>You are given <code>n</code> balloons, indexed from <code>0</code> to <code>n - 1</code>. Each balloon is painted with a number on it represented by an array <code>nums</code>. You are asked to burst all the balloons.</p>\n\n<p>If you burst the <code>i<sup>th</sup></code> balloon, you will get <code>nums[i - 1] * nums[i] * nums[i + 1]</code> coins. If <code>i - 1</code> or <code>i + 1</code> goes out of bounds of the array, then treat it as if there is a balloon with a <code>1</code> painted on it.</p>\n\n<p>Return <em>the maximum coins you can collect by bursting the balloons wisely</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,1,5,8]\n<strong>Output:</strong> 167\n<strong>Explanation:</strong>\nnums = [3,1,5,8] --&gt; [3,5,8] --&gt; [3,8] --&gt; [8] --&gt; []\ncoins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5]\n<strong>Output:</strong> 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/burst-balloons/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxCoins(self, nums: List[int]) -> int:\n    A = [1] + nums + [1]\n\n    @functools.lru_cache(None)\n    def dp(i: int, j: int) -> int:\n      if i > j:\n        return 0\n\n      return max(dp(i, k - 1) + dp(k + 1, j) + A[i - 1] * A[k] * A[j + 1]\n                 for k in range(i, j + 1))\n\n    return dp(1, len(nums))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxCoins(int[] nums) {\n    final int n = nums.length;\n\n    A = new int[n + 2];\n\n    System.arraycopy(nums, 0, A, 1, n);\n    A[0] = 1;\n    A[n + 1] = 1;\n\n    // dp[i][j] := maxCoins(A[i..j])\n    dp = new int[n + 2][n + 2];\n    return maxCoins(1, n);\n  }\n\n  private int[][] dp;\n  private int[] A;\n\n  private int maxCoins(int i, int j) {\n    if (i > j)\n      return 0;\n    if (dp[i][j] > 0)\n      return dp[i][j];\n\n    for (int k = i; k <= j; ++k)\n      dp[i][j] = Math.max(dp[i][j],\n                          maxCoins(i, k - 1) +\n                          maxCoins(k + 1, j) +\n                          A[i - 1] * A[k] * A[j + 1]);\n\n    return dp[i][j];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxCoins(vector<int>& nums) {\n    const int n = nums.size();\n\n    nums.insert(begin(nums), 1);\n    nums.insert(end(nums), 1);\n\n    // dp[i][j] := maxCoins(nums[i..j])\n    dp.resize(n + 2, vector<int>(n + 2));\n    return maxCoins(nums, 1, n);\n  }\n\n private:\n  vector<vector<int>> dp;\n\n  int maxCoins(vector<int>& nums, int i, int j) {\n    if (i > j)\n      return 0;\n    if (dp[i][j])\n      return dp[i][j];\n\n    for (int k = i; k <= j; ++k)\n      dp[i][j] = max(dp[i][j],\n                     maxCoins(nums, i, k - 1) +\n                     maxCoins(nums, k + 1, j) +\n                     nums[i - 1] * nums[k] * nums[j + 1]);\n\n    return dp[i][j];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/312.html",
    "category": "Algorithms",
    "acceptance_rate": 61.016336250910484,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 9351,
    "dislikes": 264,
    "similar_questions": "[{\"title\": \"Minimum Cost to Merge Stones\", \"titleSlug\": \"minimum-cost-to-merge-stones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"354.3K\", \"totalSubmission\": \"580.7K\", \"totalAcceptedRaw\": 354337, \"totalSubmissionRaw\": 580728, \"acRate\": \"61.0%\"}",
    "title_pt": "Estourando Balões",
    "description_pt": "<p>Você recebe <code>n</code> balões, indexados de <code>0</code> a <code>n - 1</code>. Cada balão está pintado com um número nele representado por um array <code>nums</code>. Você deve estourar todos os balões.</p>\n\n<p>Se você estourar o balão de índice <code>i<sup>th</sup></code>, você receberá <code>nums[i - 1] * nums[i] * nums[i + 1]</code> moedas. Se <code>i - 1</code> ou <code>i + 1</code> sair dos limites do array, então trate isso como se houvesse um balão com um <code>1</code> pintado nele.</p>\n\n<p>Retorne <em>o número máximo de moedas que você pode coletar ao estourar os balões de maneira inteligente</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,1,5,8]\n<strong>Saída:</strong> 167\n<strong>Explicação:</strong>\nnums = [3,1,5,8] --&gt; [3,5,8] --&gt; [3,8] --&gt; [8] --&gt; []\ncoins =  3*1*5    +   3*5*8   +  1*3*8  + 1*8*1 = 167</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5]\n<strong>Saída:</strong> 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "313",
    "paidOnly": false,
    "title": "Super Ugly Number",
    "titleSlug": "super-ugly-number",
    "url": "https://leetcode.com/problems/super-ugly-number",
    "description_url": "https://leetcode.com/problems/super-ugly-number/description/",
    "description": "<p>A <strong>super ugly number</strong> is a positive integer whose prime factors are in the array <code>primes</code>.</p>\n\n<p>Given an integer <code>n</code> and an array of integers <code>primes</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>super ugly number</strong></em>.</p>\n\n<p>The <code>n<sup>th</sup></code> <strong>super ugly number</strong> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> signed integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 12, primes = [2,7,13,19]\n<strong>Output:</strong> 32\n<strong>Explanation:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, primes = [2,3,5]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= primes.length &lt;= 100</code></li>\n\t<li><code>2 &lt;= primes[i] &lt;= 1000</code></li>\n\t<li><code>primes[i]</code> is <strong>guaranteed</strong> to be a prime number.</li>\n\t<li>All the values of <code>primes</code> are <strong>unique</strong> and sorted in <strong>ascending order</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/super-ugly-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n    k = len(primes)\n    nums = [1]\n    indices = [0] * k\n\n    while len(nums) < n:\n      nexts = [0] * k\n      for i in range(k):\n        nexts[i] = nums[indices[i]] * primes[i]\n      next = min(nexts)\n      for i in range(k):\n        if next == nexts[i]:\n          indices[i] += 1\n      nums.append(next)\n\n    return nums[-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int nthSuperUglyNumber(int n, int[] primes) {\n    final int k = primes.length;\n    int[] indices = new int[k];\n    int[] uglyNums = new int[n];\n    uglyNums[0] = 1;\n\n    for (int i = 1; i < n; ++i) {\n      int[] nexts = new int[k];\n      for (int j = 0; j < k; ++j)\n        nexts[j] = uglyNums[indices[j]] * primes[j];\n      final int next = Arrays.stream(nexts).min().getAsInt();\n      for (int j = 0; j < k; ++j)\n        if (next == nexts[j])\n          ++indices[j];\n      uglyNums[i] = next;\n    }\n\n    return uglyNums[n - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int nthSuperUglyNumber(int n, vector<int>& primes) {\n    const int k = primes.size();\n    vector<int> indices(k);\n    vector<int> uglyNums{1};\n\n    while (uglyNums.size() < n) {\n      vector<int> nexts(k);\n      for (int i = 0; i < k; ++i)\n        nexts[i] = uglyNums[indices[i]] * primes[i];\n      const int next = *min_element(begin(nexts), end(nexts));\n      for (int i = 0; i < k; ++i)\n        if (next == nexts[i])\n          ++indices[i];\n      uglyNums.push_back(next);\n    }\n\n    return uglyNums.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/313.html",
    "category": "Algorithms",
    "acceptance_rate": 45.42999121947495,
    "topics": [
      "Array",
      "Math",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 2226,
    "dislikes": 400,
    "similar_questions": "[{\"title\": \"Ugly Number II\", \"titleSlug\": \"ugly-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"142.8K\", \"totalSubmission\": \"314.3K\", \"totalAcceptedRaw\": 142801, \"totalSubmissionRaw\": 314332, \"acRate\": \"45.4%\"}",
    "title_pt": "Número Super Útil",
    "description_pt": "<p>Um <strong>número super útil</strong> é um inteiro positivo cujos fatores primos estão no array <code>primes</code>.</p>\n\n<p>Dado um inteiro <code>n</code> e um array de inteiros <code>primes</code>, retorne <em>o</em> <code>n<sup>th</sup></code> <em><strong>número super útil</strong></em>.</p>\n\n<p>O <code>n<sup>th</sup></code> <strong>número super útil</strong> tem <strong>garantia</strong> de caber em um inteiro assinado de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 12, primes = [2,7,13,19]\n<strong>Saída:</strong> 32\n<strong>Explicação:</strong> [1,2,4,7,8,13,14,16,19,26,28,32] é a sequência dos primeiros 12 números super úteis dados primes = [2,7,13,19].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, primes = [2,3,5]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> 1 não possui fatores primos, portanto todos os seus fatores primos estão no array primes = [2,3,5].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= primes.length &lt;= 100</code></li>\n\t<li><code>2 &lt;= primes[i] &lt;= 1000</code></li>\n\t<li><code>primes[i]</code> tem <strong>garantia</strong> de ser um número primo.</li>\n\t<li>Todos os valores de <code>primes</code> são <strong>únicos</strong> e ordenados em <strong>ordem crescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "315",
    "paidOnly": false,
    "title": "Count of Smaller Numbers After Self",
    "titleSlug": "count-of-smaller-numbers-after-self",
    "url": "https://leetcode.com/problems/count-of-smaller-numbers-after-self",
    "description_url": "https://leetcode.com/problems/count-of-smaller-numbers-after-self/description/",
    "description": "<p>Given an integer array <code>nums</code>, return<em> an integer array </em><code>counts</code><em> where </em><code>counts[i]</code><em> is the number of smaller elements to the right of </em><code>nums[i]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [5,2,6,1]\n<strong>Output:</strong> [2,1,1,0]\n<strong>Explanation:</strong>\nTo the right of 5 there are <b>2</b> smaller elements (2 and 1).\nTo the right of 2 there is only <b>1</b> smaller element (1).\nTo the right of 6 there is <b>1</b> smaller element (1).\nTo the right of 1 there is <b>0</b> smaller element.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1]\n<strong>Output:</strong> [0]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,-1]\n<strong>Output:</strong> [0,0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-of-smaller-numbers-after-self/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass FenwickTree:\n  def __init__(self, n: int):\n    self.sums = [0] * (n + 1)\n\n  def update(self, i: int, delta: int) -> None:\n    while i < len(self.sums):\n      self.sums[i] += delta\n      i += self._lowbit(i)\n\n  def get(self, i: int) -> int:\n    summ = 0\n    while i > 0:\n      summ += self.sums[i]\n      i -= self._lowbit(i)\n    return summ\n\n  def _lowbit(self, i) -> int:\n    return i & -i\n\n\nclass Solution:\n  def countSmaller(self, nums: List[int]) -> List[int]:\n    ans = []\n    ranks = Counter()\n    self._getRanks(nums, ranks)\n    tree = FenwickTree(len(ranks))\n\n    for num in reversed(nums):\n      ans.append(tree.get(ranks[num] - 1))\n      tree.update(ranks[num], 1)\n\n    return ans[::-1]\n\n  def _getRanks(self, nums: List[int], ranks: Dict[int, int]) -> None:\n    rank = 0\n    for num in sorted(set(nums)):\n      rank += 1\n      ranks[num] = rank",
    "solution_code_java": "\t\t\t\n\nclass FenwickTree {\n  public FenwickTree(int n) {\n    sums = new int[n + 1];\n  }\n\n  public void update(int i, int delta) {\n    while (i < sums.length) {\n      sums[i] += delta;\n      i += lowbit(i);\n    }\n  }\n\n  public int get(int i) {\n    int sum = 0;\n    while (i > 0) {\n      sum += sums[i];\n      i -= lowbit(i);\n    }\n    return sum;\n  }\n\n  private int[] sums;\n\n  private static int lowbit(int i) {\n    return i & -i;\n  }\n}\n\nclass Solution {\n  public List<Integer> countSmaller(int[] nums) {\n    List<Integer> ans = new ArrayList<>();\n    Map<Integer, Integer> ranks = new HashMap<>();\n    getRanks(nums, ranks);\n    FenwickTree tree = new FenwickTree(ranks.size());\n\n    for (int i = nums.length - 1; i >= 0; --i) {\n      final int num = nums[i];\n      ans.add(tree.get(ranks.get(num) - 1));\n      tree.update(ranks.get(num), 1);\n    }\n\n    Collections.reverse(ans);\n    return ans;\n  }\n\n  private void getRanks(int[] nums, Map<Integer, Integer> ranks) {\n    SortedSet<Integer> sorted = new TreeSet<>();\n    for (final int num : nums)\n      sorted.add(num);\n    int rank = 0;\n    for (Iterator<Integer> it = sorted.iterator(); it.hasNext();)\n      ranks.put(it.next(), ++rank);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass FenwickTree {\n public:\n  FenwickTree(int n) : sums(n + 1) {}\n\n  void update(int i, int delta) {\n    while (i < sums.size()) {\n      sums[i] += delta;\n      i += lowbit(i);\n    }\n  }\n\n  int get(int i) const {\n    int sum = 0;\n    while (i > 0) {\n      sum += sums[i];\n      i -= lowbit(i);\n    }\n    return sum;\n  }\n\n private:\n  vector<int> sums;\n\n  static inline int lowbit(int i) {\n    return i & -i;\n  }\n};\n\nclass Solution {\n public:\n  vector<int> countSmaller(vector<int>& nums) {\n    vector<int> ans(nums.size());\n    unordered_map<int, int> ranks;\n    getRanks(nums, ranks);\n    FenwickTree tree(ranks.size());\n\n    for (int i = nums.size() - 1; i >= 0; --i) {\n      const int num = nums[i];\n      ans[i] = tree.get(ranks[num] - 1);\n      tree.update(ranks[num], 1);\n    }\n\n    return ans;\n  }\n\n private:\n  void getRanks(const vector<int>& nums, unordered_map<int, int>& ranks) {\n    set<int> sorted(begin(nums), end(nums));\n    int rank = 0;\n    for (const int num : sorted)\n      ranks[num] = ++rank;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/315.html",
    "category": "Algorithms",
    "acceptance_rate": 42.82759232199707,
    "topics": [
      "Array",
      "Binary Search",
      "Divide and Conquer",
      "Binary Indexed Tree",
      "Segment Tree",
      "Merge Sort",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 9015,
    "dislikes": 247,
    "similar_questions": "[{\"title\": \"Count of Range Sum\", \"titleSlug\": \"count-of-range-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Queue Reconstruction by Height\", \"titleSlug\": \"queue-reconstruction-by-height\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Reverse Pairs\", \"titleSlug\": \"reverse-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"How Many Numbers Are Smaller Than the Current Number\", \"titleSlug\": \"how-many-numbers-are-smaller-than-the-current-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Good Triplets in an Array\", \"titleSlug\": \"count-good-triplets-in-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count the Number of K-Big Indices\", \"titleSlug\": \"count-the-number-of-k-big-indices\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"352.6K\", \"totalSubmission\": \"823.3K\", \"totalAcceptedRaw\": 352594, \"totalSubmissionRaw\": 823287, \"acRate\": \"42.8%\"}",
    "title_pt": "Contagem de Números Menores Após Cada Elemento",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne<em> um array de inteiros </em><code>counts</code><em> no qual </em><code>counts[i]</code><em> é o número de elementos menores à direita de </em><code>nums[i]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [5,2,6,1]\n<strong>Saída:</strong> [2,1,1,0]\n<strong>Explicação:</strong>\nÀ direita de 5 há <b>2</b> elementos menores (2 e 1).\nÀ direita de 2 há apenas <b>1</b> elemento menor (1).\nÀ direita de 6 há <b>1</b> elemento menor (1).\nÀ direita de 1 há <b>0</b> elementos menores.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,-1]\n<strong>Saída:</strong> [0,0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "316",
    "paidOnly": false,
    "title": "Remove Duplicate Letters",
    "titleSlug": "remove-duplicate-letters",
    "url": "https://leetcode.com/problems/remove-duplicate-letters",
    "description_url": "https://leetcode.com/problems/remove-duplicate-letters/description/",
    "description": "<p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <span data-keyword=\"lexicographically-smaller-string\"><strong>the smallest in lexicographical order</strong></span> among all possible results.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;bcabc&quot;\n<strong>Output:</strong> &quot;abc&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cbacdcbc&quot;\n<strong>Output:</strong> &quot;acdb&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1081: <a href=\"https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\" target=\"_blank\">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/remove-duplicate-letters/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeDuplicateLetters(self, s: str) -> str:\n    ans = []\n    count = Counter(s)\n    used = [False] * 26\n\n    for c in s:\n      count[c] -= 1\n      if used[ord(c) - ord('a')]:\n        continue\n      while ans and ans[-1] > c and count[ans[-1]] > 0:\n        used[ord(ans[-1]) - ord('a')] = False\n        ans.pop()\n      ans.append(c)\n      used[ord(ans[-1]) - ord('a')] = True\n\n    return ''.join(ans)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String removeDuplicateLetters(String s) {\n    StringBuilder sb = new StringBuilder();\n    int[] count = new int[128];\n    boolean[] used = new boolean[128];\n\n    for (final char c : s.toCharArray())\n      ++count[c];\n\n    for (final char c : s.toCharArray()) {\n      --count[c];\n      if (used[c])\n        continue;\n      while (sb.length() > 0 && last(sb) > c && count[last(sb)] > 0) {\n        used[last(sb)] = false;\n        sb.setLength(sb.length() - 1);\n      }\n      used[c] = true;\n      sb.append(c);\n    }\n\n    return sb.toString();\n  }\n\n  private char last(StringBuilder sb) {\n    return sb.charAt(sb.length() - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string removeDuplicateLetters(string s) {\n    string ans;\n    vector<int> count(128);\n    vector<bool> used(128);\n\n    for (const char c : s)\n      ++count[c];\n\n    for (const char c : s) {\n      --count[c];\n      if (used[c])\n        continue;\n      while (!ans.empty() && ans.back() > c && count[ans.back()] > 0) {\n        used[ans.back()] = false;\n        ans.pop_back();\n      }\n      used[c] = true;\n      ans.push_back(c);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/316.html",
    "category": "Algorithms",
    "acceptance_rate": 51.1992423568844,
    "topics": [
      "String",
      "Stack",
      "Greedy",
      "Monotonic Stack"
    ],
    "hints": [
      "Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i."
    ],
    "likes": 8915,
    "dislikes": 663,
    "similar_questions": "[{\"title\": \"Smallest K-Length Subsequence With Occurrences of a Letter\", \"titleSlug\": \"smallest-k-length-subsequence-with-occurrences-of-a-letter\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"380.1K\", \"totalSubmission\": \"742.3K\", \"totalAcceptedRaw\": 380052, \"totalSubmissionRaw\": 742301, \"acRate\": \"51.2%\"}",
    "title_pt": "Remover Letras Duplicadas",
    "description_pt": "<p>Dada uma string <code>s</code>, remova letras duplicadas de modo que cada letra apareça uma vez e somente uma vez. Você deve garantir que seu resultado seja <span data-keyword=\"lexicographically-smaller-string\"><strong>o menor em ordem lexicográfica</strong></span> entre todos os resultados possíveis.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;bcabc&quot;\n<strong>Saída:</strong> &quot;abc&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cbacdcbc&quot;\n<strong>Saída:</strong> &quot;acdb&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste de letras minúsculas do alfabeto ইংglês.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Este problema é o mesmo que 1081: <a href=\"https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/\" target=\"_blank\">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>",
    "hints_pt": [
      "- Dica 1: Tente, de forma gulosa, adicionar um caractere ausente. Como verificar se adicionar algum caractere não causará problemas? Use bit masks para verificar se você conseguirá completar a subsequência caso adicione o caractere em algum índice i."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "318",
    "paidOnly": false,
    "title": "Maximum Product of Word Lengths",
    "titleSlug": "maximum-product-of-word-lengths",
    "url": "https://leetcode.com/problems/maximum-product-of-word-lengths",
    "description_url": "https://leetcode.com/problems/maximum-product-of-word-lengths/description/",
    "description": "<p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;abcw&quot;,&quot;baz&quot;,&quot;foo&quot;,&quot;bar&quot;,&quot;xtfn&quot;,&quot;abcdef&quot;]\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> The two words can be &quot;abcw&quot;, &quot;xtfn&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;a&quot;,&quot;ab&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;cd&quot;,&quot;bcd&quot;,&quot;abcd&quot;]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The two words can be &quot;ab&quot;, &quot;cd&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;a&quot;,&quot;aa&quot;,&quot;aaa&quot;,&quot;aaaa&quot;]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> No such pair of words.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 1000</code></li>\n\t<li><code>words[i]</code> consists only of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-product-of-word-lengths/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProduct(self, words: List[str]) -> int:\n    ans = 0\n\n    def getMask(word: str) -> int:\n      mask = 0\n      for c in word:\n        mask |= 1 << ord(c) - ord('a')\n      return mask\n\n    masks = [getMask(word) for word in words]\n\n    for i in range(len(words)):\n      for j in range(i):\n        if not (masks[i] & masks[j]):\n          ans = max(ans, len(words[i]) * len(words[j]))\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProduct(String[] words) {\n    int ans = 0;\n    int[] masks = new int[words.length]; // \"abd\" -> (1011)2\n\n    for (int i = 0; i < words.length; ++i)\n      masks[i] = getMask(words[i]);\n\n    for (int i = 0; i < masks.length; ++i)\n      for (int j = 0; j < i; ++j)\n        if ((masks[i] & masks[j]) == 0)\n          ans = Math.max(ans, words[i].length() * words[j].length());\n\n    return ans;\n  }\n\n  private int getMask(final String word) {\n    int mask = 0;\n    for (final char c : word.toCharArray())\n      mask |= 1 << c - 'a';\n    return mask;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProduct(vector<string>& words) {\n    size_t ans = 0;\n    vector<int> masks;\n\n    for (const string& word : words)\n      masks.push_back(getMask(word));\n\n    for (int i = 0; i < words.size(); ++i)\n      for (int j = 0; j < i; ++j)\n        if ((masks[i] & masks[j]) == 0)\n          ans = max(ans, words[i].length() * words[j].length());\n\n    return ans;\n  }\n\n private:\n  int getMask(const string& word) {\n    int mask = 0;\n    for (const char c : word)\n      mask |= 1 << c - 'a';\n    return mask;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/318.html",
    "category": "Algorithms",
    "acceptance_rate": 60.48272365609755,
    "topics": [
      "Array",
      "String",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 3569,
    "dislikes": 143,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"233.8K\", \"totalSubmission\": \"386.6K\", \"totalAcceptedRaw\": 233825, \"totalSubmissionRaw\": 386598, \"acRate\": \"60.5%\"}",
    "title_pt": "Produto Máximo dos Comprimentos das Palavras",
    "description_pt": "<p>Dado um array de strings <code>words</code>, retorne <em>o valor máximo de</em> <code>length(word[i]) * length(word[j])</code> <em>em que as duas palavras não compartilham letras em comum</em>. Se não existirem duas palavras assim, retorne <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;abcw&quot;,&quot;baz&quot;,&quot;foo&quot;,&quot;bar&quot;,&quot;xtfn&quot;,&quot;abcdef&quot;]\n<strong>Saída:</strong> 16\n<strong>Explicação:</strong> As duas palavras podem ser &quot;abcw&quot;, &quot;xtfn&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;a&quot;,&quot;ab&quot;,&quot;abc&quot;,&quot;d&quot;,&quot;cd&quot;,&quot;bcd&quot;,&quot;abcd&quot;]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> As duas palavras podem ser &quot;ab&quot;, &quot;cd&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;a&quot;,&quot;aa&quot;,&quot;aaa&quot;,&quot;aaaa&quot;]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Nenhum par de palavras assim.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 1000</code></li>\n\t<li><code>words[i]</code> consiste apenas de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "319",
    "paidOnly": false,
    "title": "Bulb Switcher",
    "titleSlug": "bulb-switcher",
    "url": "https://leetcode.com/problems/bulb-switcher",
    "description_url": "https://leetcode.com/problems/bulb-switcher/description/",
    "description": "<p>There are <code>n</code> bulbs that are initially off. You first turn on all the bulbs, then&nbsp;you turn off every second bulb.</p>\n\n<p>On the third round, you toggle every third bulb (turning on if it&#39;s off or turning off if it&#39;s on). For the <code>i<sup>th</sup></code> round, you toggle every <code>i</code> bulb. For the <code>n<sup>th</sup></code> round, you only toggle the last bulb.</p>\n\n<p>Return <em>the number of bulbs that are on after <code>n</code> rounds</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg\" style=\"width: 421px; height: 321px;\" />\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/bulb-switcher/solutions/",
    "solution": "[TOC]\n\n## Solution\n--- \n\n### Approach 1: Math\n\n#### Intuition\n\nThe idea behind this problem is to find the number of bulbs that are on after `n` rounds. In each round, we toggle some of the bulbs.  \n\nAs all the bulbs are initially off, at the end **only bulbs that are toggled an odd number of times will remain on**.    \nNow, whenever we are at a round `i` we know we toggle all bulbs having a factor `i`. Thus, we need to find the bulbs which have an odd number of factors, as those bulbs will be toggled an odd number of times (once by each factor).   \n\nIt might be unintuitive, but with a few examples, we can easily see that a perfect square number has an odd number of factors, since any number's factors come in pairs of two different numbers, but the square root of the number will be paired with itself.\n\n\nLet's take an example to make it more clear. Suppose `n = 10`.   \nSo, the number of rounds is `10`. In each round, we will toggle some of the bulbs.\n\n![slide1](../Figures/319/Slide.PNG)\n\nTrack of rounds in which each bulb is toggled:    \n- **Bulb 1:**   Round 1 **(odd number of toggles)**   \n- **Bulb 2:**   Round 1, Round 2   \n- **Bulb 3:**   Round 1, Round 3   \n- **Bulb 4:**   Round 1, Round 2, Round 4 **(odd number of toggles)**   \n- **Bulb 5:**   Round 1, Round 5   \n- **Bulb 6:**   Round 1, Round 2, Round 3, Round 6   \n- **Bulb 7:**   Round 1, Round 7   \n- **Bulb 8:**   Round 1, Round 2, Round 4, Round 8   \n- **Bulb 9:**   Round 1, Round 3, Round 9 **(odd number of toggles)**   \n- **Bulb 10:** Round 1, Round 2, Round 5, Round10   \n\nSo, the number of bulbs that are on after 10 rounds is 3: Bulb 1, Bulb 4, and Bulb 9.\n\n<br />\n\nNow let's discuss, **why do perfect squares have odd and non-perfect squares have an even number of factors?**  \n\nA factor is a number that can be multiplied by another number to produce a given result. Say for `12`, `1, 2, 3, 4, 6, 12` all are its factors as any factor `x` can be paired with another factor `12 / x` and when multiplied together it will result in `12`.    \n  \nWhen we factorize a number `y`, say we have one factor `x`, then the other factor whose multiplication will result in the original number will be `y / x`.   \nNow comparing `x` and `y / x`, if `y` is a perfect square it means `y = a * a`, thus, here it is a possibility that `x` and `y / x` are same numbers, i.e. `a`.    \nBut if `y` is not a perfect square then for each `x` we will have a unique `y / x`, thus, it's factor pairs will always exist as two different numbers (e.g: for `12` -> `1 x 12`, `2 x 6`, `3 x 4`, (it has three factor pairs, so total `6` factors)), thus the total count of number of factors for non-perfect squares will be even,    \nand for perfect square, all other `x` and `y / x` factor pairs will be two different numbers except for one case, i.e. `a` and `a` (e.g: for `16` -> `1 x 16`, `2 x 8`, `4 x 4` (`4` is paired with itself, it has three factor pairs, but one pair has both numbers same, so total `5` factors)). Thus, it will have odd number of total factors.\n\n<br />\n\nThus we just need to find how many numbers from `1` to `n` are perfect squares.   \nWe can iterate on each number and check if it's a perfect square or not, (i.e. `floor(sqrt(i)) * floor(sqrt(i)) == i`)\n\nOr, we can directly find the square root of `n` and its floor value will be equal to the count of numbers whose squares exist in this range `1` to `n`. \n\nThe floor of the square root of `n` gives us the largest number whose square is less than or equal to `n`. For example, if `n = 26`, then the floor of square root of `n` is `5`, which means the largest number whose square is less than or equal to `26` is `5` thus for each number from `1` to `5`, its respective square will be present in the original range. So, there are `5` perfect squares in the range `1` to `25` `(1, 4, 9, 16, and 25)`. \n\nSo, taking the floor value of the square root of `n` will give us the number of perfect squares in the range `1` to `n`.     \nHence, `sqrt(n)` is our answer to this problem.\n\n> **Note:** You can also implement a function to find the square root of a number on your own, but here will use the in-built STL methods provided by each language.\n\n#### Algorithm\n\n1. Return the square root of `n`.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/nBFXmq9V/shared\" frameBorder=\"0\" width=\"100%\" height=\"157\" name=\"nBFXmq9V\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $n$ is the number of bulbs and rounds.\n\n* Time complexity: $O(1)$          \n  - In general, the [fast inverse square root algorithm](https://en.wikipedia.org/wiki/Fast_inverse_square_root) is used to compute the square root of a number (which is typically represented using 32 bits) in most programming languages. The algorithm performs a series of bitwise and floating-point operations on the input value to compute an approximation of the inverse square root. The number of operations performed by the algorithm is fixed and does not depend on the input size. Thus, it makes each call to this method an $O(1)$ time operation.\n<br />\n\n  > Note: If we want to compute the square root of large numbers (e.g: 10^10000), it would be impractical to use the fast inverse square root algorithm. The fast inverse square root algorithm is designed to compute an approximation of the inverse square root of a 32-bit floating-point number, and it may not be accurate enough for very large numbers.\n  > \n  > Instead, the languages would need to use a different algorithm that is capable of handling very large numbers with high precision. The Newton-Raphson and Babylonina methods are such algorithms that can be used to compute the square root of large numbers with high precision in nearly log-linear time (also called linearithmic time) $O(d \\log d)$, where $d$ is the number of digits of the input number. \n\n* Space complexity: $O(1)$    \n  - The implementation of the `sqrt` method doesn't use any additional space.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def bulbSwitch(self, n: int) -> int:\n    return int(sqrt(n))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int bulbSwitch(int n) {\n    // K-th bulb only be switched when k % i == 0.\n    // So we can reiterate the problem:\n    // To find # of number <= n that have odd factors.\n    // Obviously, only square numbers have odd factor(s).\n    // E.g. n = 10, only 1, 4, and 9 are square numbers that <= 10\n    return (int) Math.sqrt(n);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int bulbSwitch(int n) {\n    // K-th bulb only be switched when k % i == 0.\n    // So we can reiterate the problem:\n    // To find # of number <= n that have odd factors.\n    // Obviously, only square numbers have odd factor(s).\n    // E.g. n = 10, only 1, 4, and 9 are square numbers that <= 10\n    return sqrt(n);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/319.html",
    "category": "Algorithms",
    "acceptance_rate": 53.971477741502795,
    "topics": [
      "Math",
      "Brainteaser"
    ],
    "hints": [],
    "likes": 2786,
    "dislikes": 3190,
    "similar_questions": "[{\"title\": \"Bulb Switcher II\", \"titleSlug\": \"bulb-switcher-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of K Consecutive Bit Flips\", \"titleSlug\": \"minimum-number-of-k-consecutive-bit-flips\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Times Binary String Is Prefix-Aligned\", \"titleSlug\": \"number-of-times-binary-string-is-prefix-aligned\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Pivot Integer\", \"titleSlug\": \"find-the-pivot-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"255.9K\", \"totalSubmission\": \"474.2K\", \"totalAcceptedRaw\": 255908, \"totalSubmissionRaw\": 474154, \"acRate\": \"54.0%\"}",
    "title_pt": "Interruptor de Lâmpadas",
    "description_pt": "<p>Há <code>n</code> lâmpadas que inicialmente estão apagadas. Primeiro, você liga todas as lâmpadas, então&nbsp;você desliga toda segunda lâmpada.</p>\n\n<p>Na terceira rodada, você alterna o estado de cada terceira lâmpada (ligando se estiver apagada ou desligando se estiver ligada). Para a rodada <code>i<sup>th</sup></code>, você alterna o estado de cada lâmpada <code>i</code>. Para a rodada <code>n<sup>th</sup></code>, você alterna somente a última lâmpada.</p>\n\n<p>Retorne <em>o número de lâmpadas que estão ligadas após <code>n</code> rodadas</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/05/bulb.jpg\" style=\"width: 421px; height: 321px;\" />\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> No início, as três lâmpadas estão [off, off, off].\nApós a primeira rodada, as três lâmpadas estão [on, on, on].\nApós a segunda rodada, as três lâmpadas estão [on, off, on].\nApós a terceira rodada, as três lâmpadas estão [on, off, off]. \nEntão você deve retornar 1 porque há apenas uma lâmpada ligada.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "321",
    "paidOnly": false,
    "title": "Create Maximum Number",
    "titleSlug": "create-maximum-number",
    "url": "https://leetcode.com/problems/create-maximum-number",
    "description_url": "https://leetcode.com/problems/create-maximum-number/description/",
    "description": "<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> of lengths <code>m</code> and <code>n</code> respectively. <code>nums1</code> and <code>nums2</code> represent the digits of two numbers. You are also given an integer <code>k</code>.</p>\n\n<p>Create the maximum number of length <code>k &lt;= m + n</code> from digits of the two numbers. The relative order of the digits from the same array must be preserved.</p>\n\n<p>Return an array of the <code>k</code> digits representing the answer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\n<strong>Output:</strong> [9,8,6,5,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5\n<strong>Output:</strong> [6,7,6,0,4]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [3,9], nums2 = [8,9], k = 3\n<strong>Output:</strong> [9,8,9]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == nums1.length</code></li>\n\t<li><code>n == nums2.length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 500</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 9</code></li>\n\t<li><code>1 &lt;= k &lt;= m + n</code></li>\n\t<li><code>nums1</code> and <code>nums2</code> do not have leading zeros.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/create-maximum-number/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {\n    vector<int> ans;\n\n    for (int k1 = 0; k1 <= k; ++k1) {\n      const int k2 = k - k1;\n      if (k1 > nums1.size() || k2 > nums2.size())\n        continue;\n      ans = max(ans, maxNumber(maxNumber(nums1, k1), maxNumber(nums2, k2)));\n    }\n\n    return ans;\n  }\n\n private:\n  vector<int> maxNumber(const vector<int>& nums, int k) {\n    if (k == 0)\n      return {};\n\n    vector<int> ans;\n    int toPop = nums.size() - k;\n\n    for (const int num : nums) {\n      while (!ans.empty() && ans.back() < num && toPop-- > 0)\n        ans.pop_back();\n      ans.push_back(num);\n    }\n\n    return {begin(ans), begin(ans) + k};\n  }\n\n private:\n  vector<int> maxNumber(const vector<int>& nums1, const vector<int>& nums2) {\n    vector<int> ans;\n\n    auto s1 = cbegin(nums1);\n    auto s2 = cbegin(nums2);\n\n    while (s1 != cend(nums1) || s2 != cend(nums2))\n      if (lexicographical_compare(s1, cend(nums1), s2, cend(nums2)))\n        ans.push_back(*s2++);\n      else\n        ans.push_back(*s1++);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/321.html",
    "category": "Algorithms",
    "acceptance_rate": 32.25577505537724,
    "topics": [
      "Array",
      "Two Pointers",
      "Stack",
      "Greedy",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 2019,
    "dislikes": 365,
    "similar_questions": "[{\"title\": \"Remove K Digits\", \"titleSlug\": \"remove-k-digits\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Swap\", \"titleSlug\": \"maximum-swap\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"71.4K\", \"totalSubmission\": \"221.2K\", \"totalAcceptedRaw\": 71352, \"totalSubmissionRaw\": 221209, \"acRate\": \"32.3%\"}",
    "title_pt": "Criar o Maior Número",
    "description_pt": "<p>Você recebe dois arrays de inteiros <code>nums1</code> e <code>nums2</code> de comprimentos <code>m</code> e <code>n</code> respectivamente. <code>nums1</code> e <code>nums2</code> representam os dígitos de dois números. Você também recebe um inteiro <code>k</code>.</p>\n\n<p>Crie o número máximo de comprimento <code>k &lt;= m + n</code> a partir dos dígitos dos dois números. A ordem relativa dos dígitos do mesmo array deve ser preservada.</p>\n\n<p>Retorne um array com os <code>k</code> dígitos representando a resposta.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\n<strong>Saída:</strong> [9,8,6,5,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [6,7], nums2 = [6,0,4], k = 5\n<strong>Saída:</strong> [6,7,6,0,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [3,9], nums2 = [8,9], k = 3\n<strong>Saída:</strong> [9,8,9]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == nums1.length</code></li>\n\t<li><code>n == nums2.length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 500</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 9</code></li>\n\t<li><code>1 &lt;= k &lt;= m + n</code></li>\n\t<li><code>nums1</code> and <code>nums2</code> não possuem zeros à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "322",
    "paidOnly": false,
    "title": "Coin Change",
    "titleSlug": "coin-change",
    "url": "https://leetcode.com/problems/coin-change",
    "description_url": "https://leetcode.com/problems/coin-change/description/",
    "description": "<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>\n\n<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>\n\n<p>You may assume that you have an infinite number of each kind of coin.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> coins = [1,2,5], amount = 11\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 11 = 5 + 5 + 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> coins = [2], amount = 3\n<strong>Output:</strong> -1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> coins = [1], amount = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= coins.length &lt;= 12</code></li>\n\t<li><code>1 &lt;= coins[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>0 &lt;= amount &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/coin-change/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def coinChange(self, coins: List[int], amount: int) -> int:\n    # dp[i] := fewest # Of coins to make up i\n    dp = [0] + [amount + 1] * amount\n\n    for coin in coins:\n      for i in range(coin, amount + 1):\n        dp[i] = min(dp[i], dp[i - coin] + 1)\n\n    return -1 if dp[amount] == amount + 1 else dp[amount]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int coinChange(int[] coins, int amount) {\n    // dp[i] := fewest # of coins to make up i\n    int[] dp = new int[amount + 1];\n    Arrays.fill(dp, 1, dp.length, amount + 1);\n\n    for (final int coin : coins)\n      for (int i = coin; i <= amount; ++i)\n        dp[i] = Math.min(dp[i], dp[i - coin] + 1);\n\n    return dp[amount] == amount + 1 ? -1 : dp[amount];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int coinChange(vector<int>& coins, int amount) {\n    // dp[i] := fewest # of coins to make up i\n    vector<int> dp(amount + 1, amount + 1);\n    dp[0] = 0;\n\n    for (const int coin : coins)\n      for (int i = coin; i <= amount; ++i)\n        dp[i] = min(dp[i], dp[i - coin] + 1);\n\n    return dp[amount] == amount + 1 ? -1 : dp[amount];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/322.html",
    "category": "Algorithms",
    "acceptance_rate": 46.25940462930371,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 19841,
    "dislikes": 498,
    "similar_questions": "[{\"title\": \"Minimum Cost For Tickets\", \"titleSlug\": \"minimum-cost-for-tickets\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Value of K Coins From Piles\", \"titleSlug\": \"maximum-value-of-k-coins-from-piles\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Convert Time\", \"titleSlug\": \"minimum-number-of-operations-to-convert-time\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost to Split an Array\", \"titleSlug\": \"minimum-cost-to-split-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count of Sub-Multisets With Bounded Sum\", \"titleSlug\": \"count-of-sub-multisets-with-bounded-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Length of the Longest Subsequence That Sums to Target\", \"titleSlug\": \"length-of-the-longest-subsequence-that-sums-to-target\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Coins to be Added\", \"titleSlug\": \"minimum-number-of-coins-to-be-added\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Most Expensive Item That Can Not Be Bought\", \"titleSlug\": \"most-expensive-item-that-can-not-be-bought\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"5M\", \"totalAcceptedRaw\": 2302474, \"totalSubmissionRaw\": 4977319, \"acRate\": \"46.3%\"}",
    "title_pt": "Troco de Moedas",
    "description_pt": "<p>Você recebe um array de inteiros <code>coins</code> representando moedas de diferentes denominações e um inteiro <code>amount</code> representando um valor total de dinheiro.</p>\n\n<p>Retorne <em>a menor quantidade de moedas de que você precisa para formar esse valor</em>. Se esse valor de dinheiro não puder ser formado por nenhuma combinação das moedas, retorne <code>-1</code>.</p>\n\n<p>Você pode assumir que possui uma quantidade infinita de cada tipo de moeda.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> coins = [1,2,5], amount = 11\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> 11 = 5 + 5 + 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> coins = [2], amount = 3\n<strong>Saída:</strong> -1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> coins = [1], amount = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= coins.length &lt;= 12</code></li>\n\t<li><code>1 &lt;= coins[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>0 &lt;= amount &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "324",
    "paidOnly": false,
    "title": "Wiggle Sort II",
    "titleSlug": "wiggle-sort-ii",
    "url": "https://leetcode.com/problems/wiggle-sort-ii",
    "description_url": "https://leetcode.com/problems/wiggle-sort-ii/description/",
    "description": "<p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt; nums[1] &gt; nums[2] &lt; nums[3]...</code>.</p>\n\n<p>You may assume the input array always has a valid answer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,1,1,6,4]\n<strong>Output:</strong> [1,6,1,5,1,4]\n<strong>Explanation:</strong> [1,4,1,5,1,6] is also accepted.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,2,2,3,1]\n<strong>Output:</strong> [2,3,1,3,1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow Up:</strong> Can you do it in <code>O(n)</code> time and/or <strong>in-place</strong> with <code>O(1)</code> extra space?",
    "solution_url": "https://leetcode.com/problems/wiggle-sort-ii/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void wiggleSort(vector<int>& nums) {\n    const int n = nums.size();\n    const auto it = begin(nums) + n / 2;\n    nth_element(begin(nums), it, end(nums));\n    const int median = *it;\n\n// Index-rewiring\n#define A(i) nums[(1 + 2 * i) % (n | 1)]\n\n    for (int i = 0, j = 0, k = n - 1; i <= k;)\n      if (A(i) > median)\n        swap(A(i++), A(j++));\n      else if (A(i) < median)\n        swap(A(i), A(k--));\n      else\n        ++i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/324.html",
    "category": "Algorithms",
    "acceptance_rate": 35.52765355806731,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Greedy",
      "Sorting",
      "Quickselect"
    ],
    "hints": [],
    "likes": 3156,
    "dislikes": 975,
    "similar_questions": "[{\"title\": \"Sort Colors\", \"titleSlug\": \"sort-colors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort\", \"titleSlug\": \"wiggle-sort\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Array With Elements Not Equal to Average of Neighbors\", \"titleSlug\": \"array-with-elements-not-equal-to-average-of-neighbors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"178.9K\", \"totalSubmission\": \"503.6K\", \"totalAcceptedRaw\": 178900, \"totalSubmissionRaw\": 503561, \"acRate\": \"35.5%\"}",
    "title_pt": "Ordenação em Zigue-zague II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, reorganize-o de forma que <code>nums[0] &lt; nums[1] &gt; nums[2] &lt; nums[3]...</code>.</p>\n\n<p>Você pode assumir que o array de entrada sempre tem uma resposta válida.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,1,1,6,4]\n<strong>Saída:</strong> [1,6,1,5,1,4]\n<strong>Explicação:</strong> [1,4,1,5,1,6] também é aceito.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,2,2,3,1]\n<strong>Saída:</strong> [2,3,1,3,1,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 5000</code></li>\n\t<li>É garantido que haverá uma resposta para o <code>nums</code> de entrada fornecido.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue fazer isso em tempo <code>O(n)</code> e/ou <strong>in-place</strong> com <code>O(1)</code> de espaço extra?",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "326",
    "paidOnly": false,
    "title": "Power of Three",
    "titleSlug": "power-of-three",
    "url": "https://leetcode.com/problems/power-of-three",
    "description_url": "https://leetcode.com/problems/power-of-three/description/",
    "description": "<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p>\n\n<p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 27\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 27 = 3<sup>3</sup>\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no x where 3<sup>x</sup> = 0.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = -1\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no x where 3<sup>x</sup> = (-1).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without loops/recursion?",
    "solution_url": "https://leetcode.com/problems/power-of-three/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPowerOfThree(self, n: int) -> bool:\n    return n > 0 and 3**19 % n == 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPowerOfThree(int n) {\n    return n > 0 && Math.pow(3, 19) % n == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPowerOfThree(int n) {\n    return n > 0 && static_cast<int>(pow(3, 19)) % n == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/326.html",
    "category": "Algorithms",
    "acceptance_rate": 47.89365200676255,
    "topics": [
      "Math",
      "Recursion"
    ],
    "hints": [],
    "likes": 3252,
    "dislikes": 291,
    "similar_questions": "[{\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Four\", \"titleSlug\": \"power-of-four\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Check if Number is a Sum of Powers of Three\", \"titleSlug\": \"check-if-number-is-a-sum-of-powers-of-three\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1013312, \"totalSubmissionRaw\": 2115760, \"acRate\": \"47.9%\"}",
    "title_pt": "Potência de Três",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em><code>true</code> se ele for uma potência de três. Caso contrário, retorne <code>false</code></em>.</p>\n\n<p>Um inteiro <code>n</code> é uma potência de três se existir um inteiro <code>x</code> tal que <code>n == 3<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 27\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 27 = 3<sup>3</sup>\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Não existe x tal que 3<sup>x</sup> = 0.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = -1\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Não existe x tal que 3<sup>x</sup> = (-1).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue resolver isso sem laços/recursão?",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "327",
    "paidOnly": false,
    "title": "Count of Range Sum",
    "titleSlug": "count-of-range-sum",
    "url": "https://leetcode.com/problems/count-of-range-sum",
    "description_url": "https://leetcode.com/problems/count-of-range-sum/description/",
    "description": "<p>Given an integer array <code>nums</code> and two integers <code>lower</code> and <code>upper</code>, return <em>the number of range sums that lie in</em> <code>[lower, upper]</code> <em>inclusive</em>.</p>\n\n<p>Range sum <code>S(i, j)</code> is defined as the sum of the elements in <code>nums</code> between indices <code>i</code> and <code>j</code> inclusive, where <code>i &lt;= j</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-2,5,-1], lower = -2, upper = 2\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0], lower = 0, upper = 0\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li>\n\t<li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-of-range-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n    n = len(nums)\n    self.ans = 0\n    prefix = [0] + list(itertools.accumulate(nums))\n\n    self._mergeSort(prefix, 0, n, lower, upper)\n    return self.ans\n\n  def _mergeSort(self, prefix: List[int], l: int, r: int, lower: int, upper: int) -> None:\n    if l >= r:\n      return\n\n    m = (l + r) // 2\n    self._mergeSort(prefix, l, m, lower, upper)\n    self._mergeSort(prefix, m + 1, r, lower, upper)\n    self._merge(prefix, l, m, r, lower, upper)\n\n  def _merge(self, prefix: List[int], l: int, m: int, r: int, lower: int, upper: int) -> None:\n    lo = m + 1  # 1st index s.t. prefix[lo] - prefix[i] >= lower\n    hi = m + 1  # 1st index s.t. prefix[hi] - prefix[i] > upper\n\n    # For each index i in range [l, m], add hi - lo to ans\n    for i in range(l, m + 1):\n      while lo <= r and prefix[lo] - prefix[i] < lower:\n        lo += 1\n      while hi <= r and prefix[hi] - prefix[i] <= upper:\n        hi += 1\n      self.ans += hi - lo\n\n    sorted = [0] * (r - l + 1)\n    k = 0      # sorted's index\n    i = l      # left's index\n    j = m + 1  # right's index\n\n    while i <= m and j <= r:\n      if prefix[i] < prefix[j]:\n        sorted[k] = prefix[i]\n        k += 1\n        i += 1\n      else:\n        sorted[k] = prefix[j]\n        k += 1\n        j += 1\n\n    # Put possible remaining left part to the sorted array\n    while i <= m:\n      sorted[k] = prefix[i]\n      k += 1\n      i += 1\n\n    # Put possible remaining right part to the sorted array\n    while j <= r:\n      sorted[k] = prefix[j]\n      k += 1\n      j += 1\n\n    prefix[l:l + len(sorted)] = sorted",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countRangeSum(int[] nums, int lower, int upper) {\n    final int n = nums.length;\n    long[] prefix = new long[n + 1];\n\n    for (int i = 0; i < n; ++i)\n      prefix[i + 1] = (long) nums[i] + prefix[i];\n\n    mergeSort(prefix, 0, n, lower, upper);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  private void mergeSort(long[] prefix, int l, int r, int lower, int upper) {\n    if (l >= r)\n      return;\n\n    final int m = (l + r) / 2;\n    mergeSort(prefix, l, m, lower, upper);\n    mergeSort(prefix, m + 1, r, lower, upper);\n    merge(prefix, l, m, r, lower, upper);\n  }\n\n  private void merge(long[] prefix, int l, int m, int r, int lower, int upper) {\n    int lo = m + 1; // 1st index s.t. prefix[lo] - prefix[i] >= lower\n    int hi = m + 1; // 1st index s.t. prefix[hi] - prefix[i] > upper\n\n    // For each index i in range [l, m], add hi - lo to ans\n    for (int i = l; i <= m; ++i) {\n      while (lo <= r && prefix[lo] - prefix[i] < lower)\n        ++lo;\n      while (hi <= r && prefix[hi] - prefix[i] <= upper)\n        ++hi;\n      ans += hi - lo;\n    }\n\n    long[] sorted = new long[r - l + 1];\n    int k = 0;     // sorted's index\n    int i = l;     // left's index\n    int j = m + 1; // right's index\n\n    while (i <= m && j <= r)\n      if (prefix[i] < prefix[j])\n        sorted[k++] = prefix[i++];\n      else\n        sorted[k++] = prefix[j++];\n\n    // Put possible remaining left part to the sorted array\n    while (i <= m)\n      sorted[k++] = prefix[i++];\n\n    // Put possible remaining right part to the sorted array\n    while (j <= r)\n      sorted[k++] = prefix[j++];\n\n    System.arraycopy(sorted, 0, prefix, l, sorted.length);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countRangeSum(vector<int>& nums, int lower, int upper) {\n    const int n = nums.size();\n    int ans = 0;\n    vector<long> prefix(n + 1);\n\n    for (int i = 0; i < n; ++i)\n      prefix[i + 1] = prefix[i] + nums[i];\n\n    mergeSort(prefix, 0, n, lower, upper, ans);\n    return ans;\n  }\n\n private:\n  void mergeSort(vector<long>& prefix, int l, int r, int lower, int upper,\n                 int& ans) {\n    if (l >= r)\n      return;\n\n    const int m = (l + r) / 2;\n    mergeSort(prefix, l, m, lower, upper, ans);\n    mergeSort(prefix, m + 1, r, lower, upper, ans);\n    merge(prefix, l, m, r, lower, upper, ans);\n  }\n\n  void merge(vector<long>& prefix, int l, int m, int r, int lower, int upper,\n             int& ans) {\n    int lo = m + 1;  // 1st index s.t. prefix[lo] - prefix[i] >= lower\n    int hi = m + 1;  // 1st index s.t. prefix[hi] - prefix[i] > upper\n\n    // For each index i in range [l, m], add hi - lo to ans\n    for (int i = l; i <= m; ++i) {\n      while (lo <= r && prefix[lo] - prefix[i] < lower)\n        ++lo;\n      while (hi <= r && prefix[hi] - prefix[i] <= upper)\n        ++hi;\n      ans += hi - lo;\n    }\n\n    vector<long> sorted(r - l + 1);\n    int k = 0;      // sorted's index\n    int i = l;      // left's index\n    int j = m + 1;  // right's index\n\n    while (i <= m && j <= r)\n      if (prefix[i] < prefix[j])\n        sorted[k++] = prefix[i++];\n      else\n        sorted[k++] = prefix[j++];\n\n    // Put possible remaining left part to the sorted array\n    while (i <= m)\n      sorted[k++] = prefix[i++];\n\n    // Put possible remaining right part to the sorted array\n    while (j <= r)\n      sorted[k++] = prefix[j++];\n\n    copy(begin(sorted), end(sorted), begin(prefix) + l);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/327.html",
    "category": "Algorithms",
    "acceptance_rate": 36.911876156990395,
    "topics": [
      "Array",
      "Binary Search",
      "Divide and Conquer",
      "Binary Indexed Tree",
      "Segment Tree",
      "Merge Sort",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 2412,
    "dislikes": 255,
    "similar_questions": "[{\"title\": \"Count of Smaller Numbers After Self\", \"titleSlug\": \"count-of-smaller-numbers-after-self\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Reverse Pairs\", \"titleSlug\": \"reverse-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Fair Pairs\", \"titleSlug\": \"count-the-number-of-fair-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Number of Copy Arrays\", \"titleSlug\": \"find-the-number-of-copy-arrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"89.1K\", \"totalSubmission\": \"241.5K\", \"totalAcceptedRaw\": 89130, \"totalSubmissionRaw\": 241467, \"acRate\": \"36.9%\"}",
    "title_pt": "Contagem de Soma de Intervalos",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e dois inteiros <code>lower</code> e <code>upper</code>, retorne <em>o número de somas de intervalos que estejam em</em> <code>[lower, upper]</code> <em>inclusive</em>.</p>\n\n<p>A soma de intervalo <code>S(i, j)</code> é definida como a soma dos elementos em <code>nums</code> entre os índices <code>i</code> e <code>j</code> inclusive, onde <code>i &lt;= j</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-2,5,-1], lower = -2, upper = 2\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os três intervalos são: [0,0], [2,2] e [0,2], e suas respectivas somas são: -2, -1, 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0], lower = 0, upper = 0\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= lower &lt;= upper &lt;= 10<sup>5</sup></code></li>\n\t<li>A resposta é <strong>garantida</strong> para caber em um inteiro de <strong>32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "328",
    "paidOnly": false,
    "title": "Odd Even Linked List",
    "titleSlug": "odd-even-linked-list",
    "url": "https://leetcode.com/problems/odd-even-linked-list",
    "description_url": "https://leetcode.com/problems/odd-even-linked-list/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p>\n\n<p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p>\n\n<p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p>\n\n<p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg\" style=\"width: 300px; height: 123px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5]\n<strong>Output:</strong> [1,3,5,2,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> head = [2,1,3,5,6,4,7]\n<strong>Output:</strong> [2,3,6,7,1,5,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/odd-even-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def oddEvenList(self, head: ListNode) -> ListNode:\n    oddHead = ListNode(0)\n    evenHead = ListNode(0)\n    odd = oddHead\n    even = evenHead\n    isOdd = True\n\n    while head:\n      if isOdd:\n        odd.next = head\n        odd = head\n      else:\n        even.next = head\n        even = head\n      head = head.next\n      isOdd = not isOdd\n\n    even.next = None\n    odd.next = evenHead.next\n    return oddHead.next",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode oddEvenList(ListNode head) {\n    ListNode oddHead = new ListNode(0);\n    ListNode evenHead = new ListNode(0);\n    ListNode odd = oddHead;\n    ListNode even = evenHead;\n\n    for (boolean isOdd = true; head != null; head = head.next, isOdd = !isOdd)\n      if (isOdd) {\n        odd.next = head;\n        odd = odd.next;\n      } else {\n        even.next = head;\n        even = even.next;\n      }\n\n    odd.next = evenHead.next;\n    even.next = null;\n    return oddHead.next;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* oddEvenList(ListNode* head) {\n    ListNode oddHead(0);\n    ListNode evenHead(0);\n    ListNode* odd = &oddHead;\n    ListNode* even = &evenHead;\n\n    for (int isOdd = 0; head; head = head->next)\n      if (isOdd ^= 1) {\n        odd->next = head;\n        odd = odd->next;\n      } else {\n        even->next = head;\n        even = even->next;\n      }\n\n    odd->next = evenHead.next;\n    even->next = nullptr;\n    return oddHead.next;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/328.html",
    "category": "Algorithms",
    "acceptance_rate": 61.95256437450494,
    "topics": [
      "Linked List"
    ],
    "hints": [],
    "likes": 10698,
    "dislikes": 558,
    "similar_questions": "[{\"title\": \"Split Linked List in Parts\", \"titleSlug\": \"split-linked-list-in-parts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Transform Array by Parity\", \"titleSlug\": \"transform-array-by-parity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1209152, \"totalSubmissionRaw\": 1951741, \"acRate\": \"62.0%\"}",
    "title_pt": "Lista Encadeada Ímpar e Par",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada simplesmente, agrupe todos os nós com índices ímpares juntos, seguidos pelos nós com índices pares, e retorne <em>a lista reordenada</em>.</p>\n\n<p>O <strong>primeiro</strong> nó é considerado <strong>ímpar</strong>, e o <strong>segundo</strong> nó é <strong>par</strong>, e assim por diante.</p>\n\n<p>Observe que a ordem relativa dentro dos grupos par e ímpar deve permanecer como estava na entrada.</p>\n\n<p>Você deve resolver o problema&nbsp;com complexidade de espaço extra de <code>O(1)</code>&nbsp;e complexidade de tempo de <code>O(n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg\" style=\"width: 300px; height: 123px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5]\n<strong>Saída:</strong> [1,3,5,2,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg\" style=\"width: 500px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> head = [2,1,3,5,6,4,7]\n<strong>Saída:</strong> [2,3,6,7,1,5,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista encadeada está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "329",
    "paidOnly": false,
    "title": "Longest Increasing Path in a Matrix",
    "titleSlug": "longest-increasing-path-in-a-matrix",
    "url": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix",
    "description_url": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/description/",
    "description": "<p>Given an <code>m x n</code> integers <code>matrix</code>, return <em>the length of the longest increasing path in </em><code>matrix</code>.</p>\n\n<p>From each cell, you can either move in four directions: left, right, up, or down. You <strong>may not</strong> move <strong>diagonally</strong> or move <strong>outside the boundary</strong> (i.e., wrap-around is not allowed).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]]\n<strong>Output:</strong> 4\n<strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[1]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n    m = len(matrix)\n    n = len(matrix[0])\n\n    @functools.lru_cache(None)\n    def dfs(i: int, j: int, prev: int) -> int:\n      if i < 0 or i == m or j < 0 or j == n:\n        return 0\n      if matrix[i][j] <= prev:\n        return 0\n\n      curr = matrix[i][j]\n      return 1 + max(dfs(i + 1, j, curr),\n                     dfs(i - 1, j, curr),\n                     dfs(i, j + 1, curr),\n                     dfs(i, j - 1, curr))\n\n    return max(dfs(i, j, -math.inf) for i in range(m) for j in range(n))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestIncreasingPath(int[][] matrix) {\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    int ans = 0;\n    // memo[i][j] := the LIP starting from matrix[i][j]\n    int[][] memo = new int[m][n];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        ans = Math.max(ans, dfs(matrix, i, j, Integer.MIN_VALUE, memo));\n\n    return ans;\n  }\n\n  private int dfs(int[][] matrix, int i, int j, int prev, int[][] memo) {\n    if (i < 0 || i == matrix.length || j < 0 || j == matrix[0].length)\n      return 0;\n    if (matrix[i][j] <= prev)\n      return 0;\n    if (memo[i][j] > 0)\n      return memo[i][j];\n\n    final int curr = matrix[i][j];\n    final int a = dfs(matrix, i + 1, j, curr, memo);\n    final int b = dfs(matrix, i - 1, j, curr, memo);\n    final int c = dfs(matrix, i, j + 1, curr, memo);\n    final int d = dfs(matrix, i, j - 1, curr, memo);\n    return memo[i][j] = 1 + Math.max(Math.max(a, b), Math.max(c, d));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestIncreasingPath(vector<vector<int>>& matrix) {\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    int ans = 0;\n    vector<vector<int>> memo(m, vector<int>(n));\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        ans = max(ans, dfs(matrix, i, j, INT_MIN, memo));\n\n    return ans;\n  }\n\n private:\n  // memo[i][j] := the LIP starting from matrix[i][j]\n  int dfs(const vector<vector<int>>& matrix, int i, int j, int prev,\n          vector<vector<int>>& memo) {\n    if (i < 0 || i == matrix.size() || j < 0 || j == matrix[0].size())\n      return 0;\n    if (matrix[i][j] <= prev)\n      return 0;\n    int& ans = memo[i][j];\n    if (ans > 0)\n      return ans;\n\n    const int curr = matrix[i][j];\n    return ans = 1 + max({dfs(matrix, i + 1, j, curr, memo),\n                          dfs(matrix, i - 1, j, curr, memo),\n                          dfs(matrix, i, j + 1, curr, memo),\n                          dfs(matrix, i, j - 1, curr, memo)});\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/329.html",
    "category": "Algorithms",
    "acceptance_rate": 55.195673385975695,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Depth-First Search",
      "Breadth-First Search",
      "Graph",
      "Topological Sort",
      "Memoization",
      "Matrix"
    ],
    "hints": [],
    "likes": 9201,
    "dislikes": 141,
    "similar_questions": "[{\"title\": \"Number of Increasing Paths in a Grid\", \"titleSlug\": \"number-of-increasing-paths-in-a-grid\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"623.4K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 623368, \"totalSubmissionRaw\": 1129380, \"acRate\": \"55.2%\"}",
    "title_pt": "Caminho Crescente Mais Longo em uma Matriz",
    "description_pt": "<p>Dada uma <code>m x n</code> de inteiros <code>matrix</code>, retorne <em>o comprimento do caminho crescente mais longo em </em><code>matrix</code>.</p>\n\n<p>De cada célula, você pode mover-se em quatro direções: esquerda, direita, cima ou baixo. Você <strong>não pode</strong> mover-se <strong>diagonalmente</strong> nem mover-se <strong>fora do limite</strong> (isto é, não é permitido wrap-around).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/05/grid1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[9,9,4],[6,6,8],[2,1,1]]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> O caminho crescente mais longo é <code>[1, 2, 6, 9]</code>.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/27/tmp-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[3,4,5],[3,2,6],[2,2,1]]\n<strong>Saída:</strong> 4\n<strong>Explicação: </strong>O caminho crescente mais longo é <code>[3, 4, 5, 6]</code>. Mover-se diagonalmente não é permitido.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[1]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= matrix[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "330",
    "paidOnly": false,
    "title": "Patching Array",
    "titleSlug": "patching-array",
    "url": "https://leetcode.com/problems/patching-array",
    "description_url": "https://leetcode.com/problems/patching-array/description/",
    "description": "<p>Given a sorted integer array <code>nums</code> and an integer <code>n</code>, add/patch elements to the array such that any number in the range <code>[1, n]</code> inclusive can be formed by the sum of some elements in the array.</p>\n\n<p>Return <em>the minimum number of patches required</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3], n = 6\n<strong>Output:</strong> 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,10], n = 20\n<strong>Output:</strong> 2\nExplanation: The two patches can be [2, 4].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,2], n = 5\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> is sorted in <strong>ascending order</strong>.</li>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/patching-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minPatches(self, nums: List[int], n: int) -> int:\n    ans = 0\n    i = 0     # Point to nums\n    miss = 1  # Min sum in [1, n] we might miss\n\n    while miss <= n:\n      if i < len(nums) and nums[i] <= miss:\n        miss += nums[i]\n        i += 1\n      else:\n        # Greedily add miss itself to increase the range\n        # From [1, miss) to [1, 2 * miss)\n        miss += miss\n        ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minPatches(int[] nums, int n) {\n    int ans = 0;\n    int i = 0;     // Point to nums\n    long miss = 1; // Min sum in [1, n] we might miss\n\n    while (miss <= n)\n      if (i < nums.length && nums[i] <= miss) {\n        miss += nums[i++];\n      } else {\n        // Greedily add miss itself to increase the range\n        // From [1, miss) to [1, 2 * miss)\n        miss += miss;\n        ++ans;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minPatches(vector<int>& nums, int n) {\n    int ans = 0;\n    int i = 0;      // Point to nums\n    long miss = 1;  // Min sum in [1, n] we might miss\n\n    while (miss <= n)\n      if (i < nums.size() && nums[i] <= miss) {\n        miss += nums[i++];\n      } else {\n        // Greedily add miss itself to increase the range\n        // From [1, miss) to [1, 2 * miss)\n        miss += miss;\n        ++ans;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/330.html",
    "category": "Algorithms",
    "acceptance_rate": 53.44955171548622,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 2359,
    "dislikes": 198,
    "similar_questions": "[{\"title\": \"Maximum Number of Consecutive Values You Can Make\", \"titleSlug\": \"maximum-number-of-consecutive-values-you-can-make\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"168.3K\", \"totalSubmission\": \"314.9K\", \"totalAcceptedRaw\": 168295, \"totalSubmissionRaw\": 314867, \"acRate\": \"53.4%\"}",
    "title_pt": "Correção de Array",
    "description_pt": "<p>Dado um array inteiro ordenado <code>nums</code> e um inteiro <code>n</code>, adicione/complete elementos ao array de forma que qualquer número no intervalo <code>[1, n]</code>, inclusive, possa ser formado pela soma de alguns elementos no array.</p>\n\n<p>Retorne <em>o número mínimo de correções necessárias</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3], n = 6\n<strong>Saída:</strong> 1\nExplicação:\nAs combinações de nums são [1], [3], [1,3], que formam somas possíveis de: 1, 3, 4.\nAgora, se adicionarmos/corrigirmos 2 em nums, as combinações são: [1], [2], [3], [1,3], [2,3], [1,2,3].\nAs somas possíveis são 1, 2, 3, 4, 5, 6, que agora cobrem o intervalo [1, 6].\nPortanto, precisamos apenas de 1 correção.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,10], n = 20\n<strong>Saída:</strong> 2\nExplicação: As duas correções podem ser [2, 4].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,2], n = 5\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums</code> está ordenado em <strong>ordem crescente</strong>.</li>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "331",
    "paidOnly": false,
    "title": "Verify Preorder Serialization of a Binary Tree",
    "titleSlug": "verify-preorder-serialization-of-a-binary-tree",
    "url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree",
    "description_url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/description/",
    "description": "<p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node&#39;s value. If it is a null node, we record using a sentinel value such as <code>&#39;#&#39;</code>.</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/12/pre-tree.jpg\" style=\"width: 362px; height: 293px;\" />\n<p>For example, the above binary tree can be serialized to the string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, where <code>&#39;#&#39;</code> represents a null node.</p>\n\n<p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p>\n\n<p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>&#39;#&#39;</code> representing null pointer.</p>\n\n<p>You may assume that the input format is always valid.</p>\n\n<ul>\n\t<li>For example, it could never contain two consecutive commas, such as <code>&quot;1,,3&quot;</code>.</li>\n</ul>\n\n<p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> preorder = \"1,#\"\n<strong>Output:</strong> false\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> preorder = \"9,#,#,1\"\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>&#39;#&#39;</code> separated by commas <code>&#39;,&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isValidSerialization(self, preorder: str) -> bool:\n    degree = 1  # OutDegree (children) - inDegree (parent)\n\n    for node in preorder.split(','):\n      degree -= 1\n      if degree < 0:\n        return False\n      if node != '#':\n        degree += 2\n\n    return degree == 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isValidSerialization(String preorder) {\n    int degree = 1; // OutDegree (children) - inDegree (parent)\n\n    for (final String node : preorder.split(\",\")) {\n      if (--degree < 0) // One parent\n        return false;\n      if (!node.equals(\"#\"))\n        degree += 2; // Two children\n    }\n\n    return degree == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isValidSerialization(string preorder) {\n    int degree = 1;  // OutDegree (children) - inDegree (parent)\n    istringstream iss(preorder);\n\n    for (string node; getline(iss, node, ',');) {\n      if (--degree < 0)\n        return false;\n      if (node != \"#\")\n        degree += 2;\n    }\n\n    return degree == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/331.html",
    "category": "Algorithms",
    "acceptance_rate": 46.06963830106559,
    "topics": [
      "String",
      "Stack",
      "Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 2392,
    "dislikes": 126,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"153.5K\", \"totalSubmission\": \"333.1K\", \"totalAcceptedRaw\": 153481, \"totalSubmissionRaw\": 333150, \"acRate\": \"46.1%\"}",
    "title_pt": "Verificar Serialização em Pré-Ordem de uma Árvore Binária",
    "description_pt": "<p>Uma forma de serializar uma árvore binária é usar <strong>travessia em pré-ordem</strong>. Quando encontramos um nó não nulo, registramos o valor do nó. Se for um nó nulo, registramos usando um valor sentinela como <code>&#39;#&#39;</code>.</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/12/pre-tree.jpg\" style=\"width: 362px; height: 293px;\" />\n<p>Por exemplo, a árvore binária acima pode ser serializada para a string <code>&quot;9,3,4,#,#,1,#,#,2,#,6,#,#&quot;</code>, onde <code>&#39;#&#39;</code> representa um nó nulo.</p>\n\n<p>Dada uma string de valores separados por vírgulas <code>preorder</code>, retorne <code>true</code> se ela for uma serialização correta de travessia em pré-ordem de uma árvore binária.</p>\n\n<p>É <strong>garantido</strong> que cada valor separado por vírgula na string deve ser ou um inteiro ou um caractere <code>&#39;#&#39;</code> representando um ponteiro nulo.</p>\n\n<p>Você pode assumir que o formato de entrada é sempre válido.</p>\n\n<ul>\n\t<li>Por exemplo, ele nunca poderia conter duas vírgulas consecutivas, como <code>&quot;1,,3&quot;</code>.</li>\n</ul>\n\n<p><strong>Nota:&nbsp;</strong>Você não tem permissão para reconstruir a árvore.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> preorder = \"1,#\"\n<strong>Saída:</strong> false\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> preorder = \"9,#,#,1\"\n<strong>Saída:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>preorder</code> consiste em inteiros no intervalo <code>[0, 100]</code> e <code>&#39;#&#39;</code> separados por vírgulas <code>&#39;,&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "332",
    "paidOnly": false,
    "title": "Reconstruct Itinerary",
    "titleSlug": "reconstruct-itinerary",
    "url": "https://leetcode.com/problems/reconstruct-itinerary",
    "description_url": "https://leetcode.com/problems/reconstruct-itinerary/description/",
    "description": "<p>You are given a list of airline <code>tickets</code> where <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.</p>\n\n<p>All of the tickets belong to a man who departs from <code>&quot;JFK&quot;</code>, thus, the itinerary must begin with <code>&quot;JFK&quot;</code>. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.</p>\n\n<ul>\n\t<li>For example, the itinerary <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> has a smaller lexical order than <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li>\n</ul>\n\n<p>You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg\" style=\"width: 382px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]]\n<strong>Output:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg\" style=\"width: 222px; height: 230px;\" />\n<pre>\n<strong>Input:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]]\n<strong>Output:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;]\n<strong>Explanation:</strong> Another possible reconstruction is [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;] but it is larger in lexical order.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tickets.length &lt;= 300</code></li>\n\t<li><code>tickets[i].length == 2</code></li>\n\t<li><code>from<sub>i</sub>.length == 3</code></li>\n\t<li><code>to<sub>i</sub>.length == 3</code></li>\n\t<li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li>\n\t<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reconstruct-itinerary/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n    ans = []\n    graph = defaultdict(list)\n\n    for a, b in reversed(sorted(tickets)):\n      graph[a].append(b)\n\n    def dfs(u: str) -> None:\n      while u in graph and graph[u]:\n        dfs(graph[u].pop())\n      ans.append(u)\n\n    dfs('JFK')\n    return ans[::-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> findItinerary(List<List<String>> tickets) {\n    LinkedList<String> ans = new LinkedList<>();\n    Map<String, Queue<String>> graph = new HashMap<>();\n\n    for (final List<String> ticket : tickets) {\n      graph.putIfAbsent(ticket.get(0), new PriorityQueue<>());\n      graph.get(ticket.get(0)).offer(ticket.get(1));\n    }\n\n    dfs(graph, \"JFK\", ans);\n    return ans;\n  }\n\n  private void dfs(Map<String, Queue<String>> graph, final String u, LinkedList<String> ans) {\n    final Queue<String> arrivals = graph.get(u);\n    while (arrivals != null && !arrivals.isEmpty())\n      dfs(graph, arrivals.poll(), ans);\n    ans.addFirst(u);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findItinerary(vector<vector<string>>& tickets) {\n    vector<string> ans;\n    unordered_map<string, multiset<string>> graph;\n\n    for (const vector<string>& ticket : tickets)\n      graph[ticket[0]].insert(ticket[1]);\n\n    dfs(graph, \"JFK\", ans);\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n\n private:\n  void dfs(unordered_map<string, multiset<string>>& graph, const string& u,\n           vector<string>& ans) {\n    while (graph.count(u) && !graph[u].empty()) {\n      const string v = *begin(graph[u]);\n      graph[u].erase(begin(graph[u]));\n      dfs(graph, v, ans);\n    }\n    ans.push_back(u);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/332.html",
    "category": "Algorithms",
    "acceptance_rate": 43.534397616840145,
    "topics": [
      "Depth-First Search",
      "Graph",
      "Eulerian Circuit"
    ],
    "hints": [],
    "likes": 6109,
    "dislikes": 1905,
    "similar_questions": "[{\"title\": \"Longest Common Subpath\", \"titleSlug\": \"longest-common-subpath\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Valid Arrangement of Pairs\", \"titleSlug\": \"valid-arrangement-of-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"489.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 489276, \"totalSubmissionRaw\": 1123876, \"acRate\": \"43.5%\"}",
    "title_pt": "Reconstruir Itinerário",
    "description_pt": "<p>Você recebe uma lista de <code>tickets</code> de companhias aéreas em que <code>tickets[i] = [from<sub>i</sub>, to<sub>i</sub>]</code> representam os aeroportos de partida e de chegada de um voo. Reconstrua o itinerário em ordem e retorne-o.</p>\n\n<p>Todos os tickets pertencem a um homem que parte de <code>&quot;JFK&quot;</code>; portanto, o itinerário deve começar com <code>&quot;JFK&quot;</code>. Se houver múltiplos itinerários válidos, você deve retornar o itinerário que tiver a menor ordem lexicográfica quando lido como uma única string.</p>\n\n<ul>\n\t<li>Por exemplo, o itinerário <code>[&quot;JFK&quot;, &quot;LGA&quot;]</code> tem uma ordem lexicográfica menor do que <code>[&quot;JFK&quot;, &quot;LGB&quot;]</code>.</li>\n</ul>\n\n<p>Você pode assumir que todos os tickets formam pelo menos um itinerário válido. Você deve usar todos os tickets uma vez e somente uma vez.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/itinerary1-graph.jpg\" style=\"width: 382px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> tickets = [[&quot;MUC&quot;,&quot;LHR&quot;],[&quot;JFK&quot;,&quot;MUC&quot;],[&quot;SFO&quot;,&quot;SJC&quot;],[&quot;LHR&quot;,&quot;SFO&quot;]]\n<strong>Saída:</strong> [&quot;JFK&quot;,&quot;MUC&quot;,&quot;LHR&quot;,&quot;SFO&quot;,&quot;SJC&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/14/itinerary2-graph.jpg\" style=\"width: 222px; height: 230px;\" />\n<pre>\n<strong>Entrada:</strong> tickets = [[&quot;JFK&quot;,&quot;SFO&quot;],[&quot;JFK&quot;,&quot;ATL&quot;],[&quot;SFO&quot;,&quot;ATL&quot;],[&quot;ATL&quot;,&quot;JFK&quot;],[&quot;ATL&quot;,&quot;SFO&quot;]]\n<strong>Saída:</strong> [&quot;JFK&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;SFO&quot;]\n<strong>Explicação:</strong> Outra reconstrução possível é [&quot;JFK&quot;,&quot;SFO&quot;,&quot;ATL&quot;,&quot;JFK&quot;,&quot;ATL&quot;,&quot;SFO&quot;], mas ela é maior em ordem lexicográfica.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tickets.length &lt;= 300</code></li>\n\t<li><code>tickets[i].length == 2</code></li>\n\t<li><code>from<sub>i</sub>.length == 3</code></li>\n\t<li><code>to<sub>i</sub>.length == 3</code></li>\n\t<li><code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> consist of uppercase English letters.</li>\n\t<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "334",
    "paidOnly": false,
    "title": "Increasing Triplet Subsequence",
    "titleSlug": "increasing-triplet-subsequence",
    "url": "https://leetcode.com/problems/increasing-triplet-subsequence",
    "description_url": "https://leetcode.com/problems/increasing-triplet-subsequence/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [5,4,3,2,1]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> No triplet exists.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,1,5,0,4,6]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?",
    "solution_url": "https://leetcode.com/problems/increasing-triplet-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def increasingTriplet(self, nums: List[int]) -> bool:\n    first = math.inf\n    second = math.inf\n\n    for num in nums:\n      if num <= first:\n        first = num\n      elif num <= second:  # First < num <= second\n        second = num\n      else:\n        return True  # First < second < num (third)\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean increasingTriplet(int[] nums) {\n    int first = Integer.MAX_VALUE;\n    int second = Integer.MAX_VALUE;\n\n    for (final int num : nums)\n      if (num <= first)\n        first = num;\n      else if (num <= second) // First < num <= second\n        second = num;\n      else // First < second < num (third)\n        return true;\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool increasingTriplet(vector<int>& nums) {\n    int first = INT_MAX;\n    int second = INT_MAX;\n\n    for (const int num : nums)\n      if (num <= first)\n        first = num;\n      else if (num <= second)  // First < num <= second\n        second = num;\n      else\n        return true;  // First < second < num (third)\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/334.html",
    "category": "Algorithms",
    "acceptance_rate": 39.135162249139476,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 8523,
    "dislikes": 650,
    "similar_questions": "[{\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Special Quadruplets\", \"titleSlug\": \"count-special-quadruplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Good Triplets in an Array\", \"titleSlug\": \"count-good-triplets-in-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Increasing Quadruplets\", \"titleSlug\": \"count-increasing-quadruplets\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"786.4K\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 786434, \"totalSubmissionRaw\": 2009533, \"acRate\": \"39.1%\"}",
    "title_pt": "Subsequência Crescente de Três Elementos",
    "description_pt": "<p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,5]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Any triplet where i &lt; j &lt; k is valid.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [5,4,3,2,1]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> No triplet exists.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,1,5,0,4,6]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "335",
    "paidOnly": false,
    "title": "Self Crossing",
    "titleSlug": "self-crossing",
    "url": "https://leetcode.com/problems/self-crossing",
    "description_url": "https://leetcode.com/problems/self-crossing/description/",
    "description": "<p>You are given an array of integers <code>distance</code>.</p>\n\n<p>You start at the point <code>(0, 0)</code> on an <strong>X-Y plane,</strong> and you move <code>distance[0]</code> meters to the north, then <code>distance[1]</code> meters to the west, <code>distance[2]</code> meters to the south, <code>distance[3]</code> meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.</p>\n\n<p>Return <code>true</code> <em>if your path crosses itself or </em><code>false</code><em> if it does not</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/11.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Input:</strong> distance = [2,1,1,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The path crosses itself at the point (0, 1).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/22.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Input:</strong> distance = [1,2,3,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The path does not cross itself at any point.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/33.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Input:</strong> distance = [1,1,1,2,1]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The path crosses itself at the point (0, 0).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/self-crossing/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isSelfCrossing(self, x: List[int]) -> bool:\n    if len(x) <= 3:\n      return False\n\n    for i in range(3, len(x)):\n      if x[i - 2] <= x[i] and x[i - 1] <= x[i - 3]:\n        return True\n      if i >= 4 and x[i - 1] == x[i - 3] and x[i - 2] <= x[i] + x[i - 4]:\n        return True\n      if i >= 5 and x[i - 4] <= x[i - 2] and x[i - 2] <= x[i] + x[i - 4] and x[i - 1] <= x[i - 3] and x[i - 3] <= x[i - 1] + x[i - 5]:\n        return True\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isSelfCrossing(int[] x) {\n    if (x.length <= 3)\n      return false;\n\n    for (int i = 3; i < x.length; ++i) {\n      if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3])\n        return true;\n      if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4])\n        return true;\n      if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && x[i - 1] <= x[i - 3] &&\n          x[i - 3] <= x[i - 1] + x[i - 5])\n        return true;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isSelfCrossing(vector<int>& x) {\n    if (x.size() <= 3)\n      return false;\n\n    for (int i = 3; i < x.size(); ++i) {\n      if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3])\n        return true;\n      if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4])\n        return true;\n      if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] &&\n          x[i - 1] <= x[i - 3] && x[i - 3] <= x[i - 1] + x[i - 5])\n        return true;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/335.html",
    "category": "Algorithms",
    "acceptance_rate": 31.934119456549602,
    "topics": [
      "Array",
      "Math",
      "Geometry"
    ],
    "hints": [],
    "likes": 404,
    "dislikes": 518,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"39.9K\", \"totalSubmission\": \"124.8K\", \"totalAcceptedRaw\": 39864, \"totalSubmissionRaw\": 124832, \"acRate\": \"31.9%\"}",
    "title_pt": "Auto-interseção",
    "description_pt": "<p>Você recebe um array de inteiros <code>distance</code>.</p>\n\n<p>Você começa no ponto <code>(0, 0)</code> em um <strong>plano X-Y,</strong> e se move <code>distance[0]</code> metros para o norte, depois <code>distance[1]</code> metros para o oeste, <code>distance[2]</code> metros para o sul, <code>distance[3]</code> metros para o leste, e assim por diante. Em outras palavras, após cada movimento, sua direção muda no sentido anti-horário.</p>\n\n<p>Retorne <code>true</code> <em>se seu caminho cruzar a si mesmo ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/11.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Entrada:</strong> distance = [2,1,1,2]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O caminho cruza a si mesmo no ponto (0, 1).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/22.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Entrada:</strong> distance = [1,2,3,4]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> O caminho não cruza a si mesmo em nenhum ponto.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/12/21/33.jpg\" style=\"width: 400px; height: 413px;\" />\n<pre>\n<strong>Entrada:</strong> distance = [1,1,1,2,1]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O caminho cruza a si mesmo no ponto (0, 0).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;distance.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;=&nbsp;distance[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "336",
    "paidOnly": false,
    "title": "Palindrome Pairs",
    "titleSlug": "palindrome-pairs",
    "url": "https://leetcode.com/problems/palindrome-pairs",
    "description_url": "https://leetcode.com/problems/palindrome-pairs/description/",
    "description": "<p>You are given a <strong>0-indexed</strong> array of <strong>unique</strong> strings <code>words</code>.</p>\n\n<p>A <strong>palindrome pair</strong> is a pair of integers <code>(i, j)</code> such that:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j &lt; words.length</code>,</li>\n\t<li><code>i != j</code>, and</li>\n\t<li><code>words[i] + words[j]</code> (the concatenation of the two strings) is a <span data-keyword=\"palindrome-string\">palindrome</span>.</li>\n</ul>\n\n<p>Return <em>an array of all the <strong>palindrome pairs</strong> of </em><code>words</code>.</p>\n\n<p>You must write an algorithm with&nbsp;<code>O(sum of words[i].length)</code>&nbsp;runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;]\n<strong>Output:</strong> [[0,1],[1,0],[3,2],[2,4]]\n<strong>Explanation:</strong> The palindromes are [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;]\n<strong>Output:</strong> [[0,1],[1,0]]\n<strong>Explanation:</strong> The palindromes are [&quot;battab&quot;,&quot;tabbat&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;a&quot;,&quot;&quot;]\n<strong>Output:</strong> [[0,1],[1,0]]\n<strong>Explanation:</strong> The palindromes are [&quot;a&quot;,&quot;a&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= words[i].length &lt;= 300</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/palindrome-pairs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def palindromePairs(self, words: List[str]) -> List[List[int]]:\n    ans = []\n    dict = {word[::-1]: i for i, word in enumerate(words)}\n\n    for i, word in enumerate(words):\n      if \"\" in dict and dict[\"\"] != i and word == word[::-1]:\n        ans.append([i, dict[\"\"]])\n\n      for j in range(1, len(word) + 1):\n        l = word[:j]\n        r = word[j:]\n        if l in dict and dict[l] != i and r == r[::-1]:\n          ans.append([i, dict[l]])\n        if r in dict and dict[r] != i and l == l[::-1]:\n          ans.append([dict[r], i])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> palindromePairs(String[] words) {\n    List<List<Integer>> ans = new ArrayList<>();\n    Map<String, Integer> map = new HashMap<>(); // {reversed word: its index}\n\n    for (int i = 0; i < words.length; ++i)\n      map.put(new StringBuilder(words[i]).reverse().toString(), i);\n\n    for (int i = 0; i < words.length; ++i) {\n      final String word = words[i];\n      // Special case to prevent duplicate calculation\n      if (map.containsKey(\"\") && map.get(\"\") != i && isPalindrome(word))\n        ans.add(Arrays.asList(i, map.get(\"\")));\n      for (int j = 1; j <= word.length(); ++j) {\n        final String l = word.substring(0, j);\n        final String r = word.substring(j);\n        if (map.containsKey(l) && map.get(l) != i && isPalindrome(r))\n          ans.add(Arrays.asList(i, map.get(l)));\n        if (map.containsKey(r) && map.get(r) != i && isPalindrome(l))\n          ans.add(Arrays.asList(map.get(r), i));\n      }\n    }\n\n    return ans;\n  }\n\n  private boolean isPalindrome(final String word) {\n    int l = 0;\n    int r = word.length() - 1;\n    while (l < r)\n      if (word.charAt(l++) != word.charAt(r--))\n        return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> palindromePairs(vector<string>& words) {\n    vector<vector<int>> ans;\n    unordered_map<string, int> map;  // {reversed word: its index}\n\n    for (int i = 0; i < words.size(); ++i) {\n      string word = words[i];\n      reverse(begin(word), end(word));\n      map[word] = i;\n    }\n\n    for (int i = 0; i < words.size(); ++i) {\n      const string& word = words[i];\n      // Special case to prevent duplicate calculation\n      if (map.count(\"\") && map[\"\"] != i && isPalindrome(word))\n        ans.push_back({i, map[\"\"]});\n      for (int j = 1; j <= word.length(); ++j) {\n        const string& l = word.substr(0, j);\n        const string& r = word.substr(j);\n        if (map.count(l) && map[l] != i && isPalindrome(r))\n          ans.push_back({i, map[l]});\n        if (map.count(r) && map[r] != i && isPalindrome(l))\n          ans.push_back({map[r], i});\n      }\n    }\n\n    return ans;\n  }\n\n private:\n  bool isPalindrome(const string& word) {\n    int l = 0;\n    int r = word.length() - 1;\n    while (l < r)\n      if (word[l++] != word[r--])\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/336.html",
    "category": "Algorithms",
    "acceptance_rate": 36.15826064727401,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Trie"
    ],
    "hints": [
      "Checking every two pairs will exceed the time limit. It will be O(n^2 * k). We need a faster way.",
      "If we hash every string in the array, how can we check if two pairs form a palindrome after the concatenation?",
      "We can check every string in words and consider it as words[j] (i.e., the suffix of the target palindrome). We can check if there is a hash of string that can be the prefix to make it a palindrome."
    ],
    "likes": 4552,
    "dislikes": 467,
    "similar_questions": "[{\"title\": \"Longest Palindromic Substring\", \"titleSlug\": \"longest-palindromic-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Palindrome\", \"titleSlug\": \"shortest-palindrome\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Palindrome by Concatenating Two Letter Words\", \"titleSlug\": \"longest-palindrome-by-concatenating-two-letter-words\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Maximum Number of String Pairs\", \"titleSlug\": \"find-maximum-number-of-string-pairs\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"223.5K\", \"totalSubmission\": \"618.1K\", \"totalAcceptedRaw\": 223482, \"totalSubmissionRaw\": 618068, \"acRate\": \"36.2%\"}",
    "title_pt": "Pares de Palíndromo",
    "description_pt": "<p>Você recebe um array <strong>indexado em 0</strong> de strings <strong>únicas</strong> <code>words</code>.</p>\n\n<p>Um <strong>par de palíndromo</strong> é um par de inteiros <code>(i, j)</code> tal que:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j &lt; words.length</code>,</li>\n\t<li><code>i != j</code>, e</li>\n\t<li><code>words[i] + words[j]</code> (a concatenação das duas strings) é um <span data-keyword=\"palindrome-string\">palíndromo</span>.</li>\n</ul>\n\n<p>Retorne <em>um array com todos os <strong>pares de palíndromo</strong> de </em><code>words</code>.</p>\n\n<p>Você deve escrever um algoritmo com complexidade de tempo <code>O(sum of words[i].length)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;abcd&quot;,&quot;dcba&quot;,&quot;lls&quot;,&quot;s&quot;,&quot;sssll&quot;]\n<strong>Saída:</strong> [[0,1],[1,0],[3,2],[2,4]]\n<strong>Explicação:</strong> Os palíndromos são [&quot;abcddcba&quot;,&quot;dcbaabcd&quot;,&quot;slls&quot;,&quot;llssssll&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;bat&quot;,&quot;tab&quot;,&quot;cat&quot;]\n<strong>Saída:</strong> [[0,1],[1,0]]\n<strong>Explicação:</strong> Os palíndromos são [&quot;battab&quot;,&quot;tabbat&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;a&quot;,&quot;&quot;]\n<strong>Saída:</strong> [[0,1],[1,0]]\n<strong>Explicação:</strong> Os palíndromos são [&quot;a&quot;,&quot;a&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 5000</code></li>\n\t<li><code>0 &lt;= words[i].length &lt;= 300</code></li>\n\t<li><code>words[i]</code> consiste em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Verificar todos os pares de duas palavras excederá o limite de tempo. Isso será O(n^2 * k). Precisamos de uma maneira mais rápida.",
      "Dica 2: Se fizermos hash de cada string no array, como podemos verificar se duas palavras formam um palíndromo após a concatenação?",
      "Dica 3: Podemos verificar cada string em words e considerá-la como words[j] (isto é, o sufixo do palíndromo alvo). Podemos verificar se existe um hash de string que possa ser o prefixo para torná-lo um palíndromo."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "337",
    "paidOnly": false,
    "title": "House Robber III",
    "titleSlug": "house-robber-iii",
    "url": "https://leetcode.com/problems/house-robber-iii",
    "description_url": "https://leetcode.com/problems/house-robber-iii/description/",
    "description": "<p>The thief has found himself a new place for his thievery again. There is only one entrance to this area, called <code>root</code>.</p>\n\n<p>Besides the <code>root</code>, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if <strong>two directly-linked houses were broken into on the same night</strong>.</p>\n\n<p>Given the <code>root</code> of the binary tree, return <em>the maximum amount of money the thief can rob <strong>without alerting the police</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg\" style=\"width: 277px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> root = [3,2,3,null,3,null,1]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg\" style=\"width: 357px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> root = [3,4,5,1,3,null,1]\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> Maximum amount of money the thief can rob = 4 + 5 = 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/house-robber-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def rob(self, root: Optional[TreeNode]) -> int:\n    def robOrNot(root: Optional[TreeNode]) -> tuple:\n      if not root:\n        return (0, 0)\n\n      robLeft, notRobLeft = robOrNot(root.left)\n      robRight, notRobRight = robOrNot(root.right)\n\n      return (root.val + notRobLeft + notRobRight,\n              max(robLeft, notRobLeft) + max(robRight, notRobRight))\n\n    return max(robOrNot(root))",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int robRoot;\n  public int notRobRoot;\n\n  public T(int robRoot, int notRobRoot) {\n    this.robRoot = robRoot;\n    this.notRobRoot = notRobRoot;\n  }\n}\n\nclass Solution {\n  public int rob(TreeNode root) {\n    T t = robOrNotRob(root);\n    return Math.max(t.robRoot, t.notRobRoot);\n  }\n\n  private T robOrNotRob(TreeNode root) {\n    if (root == null)\n      return new T(0, 0);\n\n    T l = robOrNotRob(root.left);\n    T r = robOrNotRob(root.right);\n\n    return new T(root.val + l.notRobRoot + r.notRobRoot,\n                 Math.max(l.robRoot, l.notRobRoot) + Math.max(r.robRoot, r.notRobRoot));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int robRoot;\n  int notRobRoot;\n};\n\nclass Solution {\n public:\n  int rob(TreeNode* root) {\n    const auto& [robRoot, notRobRoot] = robOrNotRob(root);\n    return max(robRoot, notRobRoot);\n  }\n\n private:\n  T robOrNotRob(TreeNode* root) {\n    if (root == nullptr)\n      return {0, 0};\n    const T l = robOrNotRob(root->left);\n    const T r = robOrNotRob(root->right);\n    return {root->val + l.notRobRoot + r.notRobRoot,\n            max(l.robRoot, l.notRobRoot) + max(r.robRoot, r.notRobRoot)};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/337.html",
    "category": "Algorithms",
    "acceptance_rate": 54.86296352604592,
    "topics": [
      "Dynamic Programming",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8798,
    "dislikes": 151,
    "similar_questions": "[{\"title\": \"House Robber\", \"titleSlug\": \"house-robber\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber II\", \"titleSlug\": \"house-robber-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"436.6K\", \"totalSubmission\": \"795.9K\", \"totalAcceptedRaw\": 436645, \"totalSubmissionRaw\": 795883, \"acRate\": \"54.9%\"}",
    "title_pt": "Ladrão da Casa III",
    "description_pt": "<p>O ladrão encontrou novamente um novo lugar para seu roubo. Há apenas uma entrada para esta área, chamada <code>root</code>.</p>\n\n<p>Além da <code>root</code>, cada casa tem uma e somente uma casa-pai. Após uma inspeção, o ladrão inteligente percebeu que todas as casas neste lugar formam uma árvore binária. A polícia será automaticamente acionada se <strong>duas casas diretamente ligadas forem arrombadas na mesma noite</strong>.</p>\n\n<p>Dada a <code>root</code> da árvore binária, retorne <em>a quantidade máxima de dinheiro que o ladrão pode roubar <strong>sem alertar a polícia</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg\" style=\"width: 277px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,2,3,null,3,null,1]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> A quantidade máxima de dinheiro que o ladrão pode roubar = 3 + 3 + 1 = 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg\" style=\"width: 357px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,4,5,1,3,null,1]\n<strong>Saída:</strong> 9\n<strong>Explicação:</strong> A quantidade máxima de dinheiro que o ladrão pode roubar = 4 + 5 = 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "338",
    "paidOnly": false,
    "title": "Counting Bits",
    "titleSlug": "counting-bits",
    "url": "https://leetcode.com/problems/counting-bits",
    "description_url": "https://leetcode.com/problems/counting-bits/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>&#39;s</strong> in the binary representation of </em><code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> [0,1,1]\n<strong>Explanation:</strong>\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 5\n<strong>Output:</strong> [0,1,1,2,1,2]\n<strong>Explanation:</strong>\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n3 --&gt; 11\n4 --&gt; 100\n5 --&gt; 101\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li>\n\t<li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/counting-bits/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countBits(self, n: int) -> List[int]:\n    # Let f(i) := i's # Of 1's in bitmask\n    # F(i) = f(i / 2) + i % 2\n    ans = [0] * (n + 1)\n\n    for i in range(1, n + 1):\n      ans[i] = ans[i // 2] + (i & 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] countBits(int n) {\n    // Let f(i) := i's # of 1's in bitmask\n    // F(i) = f(i / 2) + i % 2\n    int[] ans = new int[n + 1];\n\n    for (int i = 1; i <= n; ++i)\n      ans[i] = ans[i / 2] + (i % 2 == 0 ? 0 : 1);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> countBits(int n) {\n    // Let f(i) := i's # of 1's in bitmask\n    // F(i) = f(i / 2) + i % 2\n    vector<int> ans(n + 1);\n\n    for (int i = 1; i <= n; ++i)\n      ans[i] = ans[i / 2] + (i & 1);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/338.html",
    "category": "Algorithms",
    "acceptance_rate": 79.61651962329091,
    "topics": [
      "Dynamic Programming",
      "Bit Manipulation"
    ],
    "hints": [
      "You should make use of what you have produced already.",
      "Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.",
      "Or does the odd/even status of the number help you in calculating the number of 1s?"
    ],
    "likes": 11506,
    "dislikes": 576,
    "similar_questions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Values at Indices With K Set Bits\", \"titleSlug\": \"sum-of-values-at-indices-with-k-set-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the K-or of an Array\", \"titleSlug\": \"find-the-k-or-of-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1359209, \"totalSubmissionRaw\": 1707197, \"acRate\": \"79.6%\"}",
    "title_pt": "Contagem de Bits",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>um array </em><code>ans</code><em> de tamanho </em><code>n + 1</code><em> tal que, para cada </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> seja o <strong>número de </strong></em><code>1</code><em><strong>&#39;s</strong> na representação binária de </em><code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> [0,1,1]\n<strong>Explicação:</strong>\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> [0,1,1,2,1,2]\n<strong>Explicação:</strong>\n0 --&gt; 0\n1 --&gt; 1\n2 --&gt; 10\n3 --&gt; 11\n4 --&gt; 100\n5 --&gt; 101\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>É muito fácil chegar a uma solução com tempo de execução de <code>O(n log n)</code>. Você consegue fazê-lo em tempo linear <code>O(n)</code> e, possivelmente, em uma única passada?</li>\n\t<li>Você consegue fazê-lo sem usar nenhuma função embutida (isto é, como <code>__builtin_popcount</code> em C++)?</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Você deve fazer uso do que já produziu.",
      "Dica 2: Divida os números em intervalos como [2-3], [4-7], [8-15] e assim por diante. E tente gerar um novo intervalo a partir do anterior.",
      "Dica 3: Ou será que o fato de o número ser ímpar/par ajuda você a calcular o número de 1s?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "341",
    "paidOnly": false,
    "title": "Flatten Nested List Iterator",
    "titleSlug": "flatten-nested-list-iterator",
    "url": "https://leetcode.com/problems/flatten-nested-list-iterator",
    "description_url": "https://leetcode.com/problems/flatten-nested-list-iterator/description/",
    "description": "<p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p>\n\n<p>Implement the <code>NestedIterator</code> class:</p>\n\n<ul>\n\t<li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li>\n\t<li><code>int next()</code> Returns the next integer in the nested list.</li>\n\t<li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li>\n</ul>\n\n<p>Your code will be tested with the following pseudocode:</p>\n\n<pre>\ninitialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n    append iterator.next() to the end of res\nreturn res\n</pre>\n\n<p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nestedList = [[1,1],2,[1,1]]\n<strong>Output:</strong> [1,1,2,1,1]\n<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nestedList = [1,[4,[6]]]\n<strong>Output:</strong> [1,4,6]\n<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nestedList.length &lt;= 500</code></li>\n\t<li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/flatten-nested-list-iterator/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass NestedIterator:\n  def __init__(self, nestedList: List[NestedInteger]):\n    self.q = deque()\n    self.addInteger(nestedList)\n\n  def next(self) -> int:\n    return self.q.popleft()\n\n  def hasNext(self) -> bool:\n    return self.q\n\n  def addInteger(self, nestedList: List[NestedInteger]) -> None:\n    for ni in nestedList:\n      if ni.isInteger():\n        self.q.append(ni.getInteger())\n      else:\n        self.addInteger(ni.getList())",
    "solution_code_java": "\t\t\t\n\npublic class NestedIterator implements Iterator<Integer> {\n  public NestedIterator(List<NestedInteger> nestedList) {\n    addInteger(nestedList);\n  }\n\n  @Override\n  public Integer next() {\n    return q.poll();\n  }\n\n  @Override\n  public boolean hasNext() {\n    return !q.isEmpty();\n  }\n\n  private Queue<Integer> q = new ArrayDeque<>();\n\n  private void addInteger(final List<NestedInteger> nestedList) {\n    for (final NestedInteger ni : nestedList)\n      if (ni.isInteger())\n        q.offer(ni.getInteger());\n      else\n        addInteger(ni.getList());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass NestedIterator {\n public:\n  NestedIterator(vector<NestedInteger>& nestedList) {\n    addInteger(nestedList);\n  }\n\n  int next() {\n    const int num = q.front();\n    q.pop();\n    return num;\n  }\n\n  bool hasNext() {\n    return !q.empty();\n  }\n\n private:\n  queue<int> q;\n\n  void addInteger(const vector<NestedInteger>& nestedList) {\n    for (const NestedInteger& ni : nestedList)\n      if (ni.isInteger())\n        q.push(ni.getInteger());\n      else\n        addInteger(ni.getList());\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/341.html",
    "category": "Algorithms",
    "acceptance_rate": 65.17913873961574,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search",
      "Design",
      "Queue",
      "Iterator"
    ],
    "hints": [],
    "likes": 4973,
    "dislikes": 1782,
    "similar_questions": "[{\"title\": \"Flatten 2D Vector\", \"titleSlug\": \"flatten-2d-vector\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Mini Parser\", \"titleSlug\": \"mini-parser\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Array Nesting\", \"titleSlug\": \"array-nesting\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"495.5K\", \"totalSubmission\": \"760.2K\", \"totalAcceptedRaw\": 495467, \"totalSubmissionRaw\": 760163, \"acRate\": \"65.2%\"}",
    "title_pt": "Iterador de Lista Aninhada Achatada",
    "description_pt": "<p>Você recebe uma lista aninhada de inteiros <code>nestedList</code>. Cada elemento é ou um inteiro ou uma lista cujos elementos também podem ser inteiros ou outras listas. Implemente um iterador para achatá-la.</p>\n\n<p>Implemente a classe <code>NestedIterator</code>:</p>\n\n<ul>\n\t<li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Inicializa o iterador com a lista aninhada <code>nestedList</code>.</li>\n\t<li><code>int next()</code> Retorna o próximo inteiro na lista aninhada.</li>\n\t<li><code>boolean hasNext()</code> Retorna <code>true</code> se ainda houver alguns inteiros na lista aninhada e <code>false</code> caso contrário.</li>\n</ul>\n\n<p>Seu código será testado com o seguinte pseudocódigo:</p>\n\n<pre>\ninitialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n    append iterator.next() to the end of res\nreturn res\n</pre>\n\n<p>Se <code>res</code> corresponder à lista achatada esperada, então seu código será julgado como correto.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nestedList = [[1,1],2,[1,1]]\n<strong>Saída:</strong> [1,1,2,1,1]\n<strong>Explicação:</strong> Chamando next repetidamente até hasNext retornar false, a ordem dos elementos retornados por next deve ser: [1,1,2,1,1].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nestedList = [1,[4,[6]]]\n<strong>Saída:</strong> [1,4,6]\n<strong>Explicação:</strong> Chamando next repetidamente até hasNext retornar false, a ordem dos elementos retornados por next deve ser: [1,4,6].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nestedList.length &lt;= 500</code></li>\n\t<li>Os valores dos inteiros na lista aninhada estão no intervalo <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "342",
    "paidOnly": false,
    "title": "Power of Four",
    "titleSlug": "power-of-four",
    "url": "https://leetcode.com/problems/power-of-four",
    "description_url": "https://leetcode.com/problems/power-of-four/description/",
    "description": "<p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of four. Otherwise, return <code>false</code></em>.</p>\n\n<p>An integer <code>n</code> is a power of four, if there exists an integer <code>x</code> such that <code>n == 4<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 16\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 5\n<strong>Output:</strong> false\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you solve it without loops/recursion?",
    "solution_url": "https://leetcode.com/problems/power-of-four/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPowerOfFour(self, n: int) -> bool:\n    # Why (4^n - 1) % 3 == 0?\n    # (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are\n    # Three consecutive numbers among one of them, there must be a multiple\n    # Of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1.\n    # Therefore, 4^n - 1 is a multiple of 3.\n    return n > 0 and bin(n).count('1') == 1 and (n - 1) % 3 == 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPowerOfFour(int n) {\n    // Why (4^n - 1) % 3 == 0?\n    // (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are\n    // Three consecutive numbers; among one of them, there must be a multiple\n    // Of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1.\n    // Therefore, 4^n - 1 is a multiple of 3\n    return n > 0 && Integer.bitCount(n) == 1 && (n - 1) % 3 == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPowerOfFour(int n) {\n    // Why (4^n - 1) % 3 == 0?\n    // (4^n - 1) = (2^n - 1)(2^n + 1) and 2^n - 1, 2^n, 2^n + 1 are\n    // Three consecutive numbers; among one of them, there must be a multiple\n    // Of 3, and that can't be 2^n, so it must be either 2^n - 1 or 2^n + 1.\n    // Therefore, 4^n - 1 is a multiple of 3.\n    return n > 0 && __builtin_popcountll(n) == 1 && (n - 1) % 3 == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/342.html",
    "category": "Algorithms",
    "acceptance_rate": 49.34496652946287,
    "topics": [
      "Math",
      "Bit Manipulation",
      "Recursion"
    ],
    "hints": [],
    "likes": 4041,
    "dislikes": 402,
    "similar_questions": "[{\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Three\", \"titleSlug\": \"power-of-three\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"796.3K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 796255, \"totalSubmissionRaw\": 1613651, \"acRate\": \"49.3%\"}",
    "title_pt": "Potência de Quatro",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em><code>true</code> se ele for uma potência de quatro. Caso contrário, retorne <code>false</code></em>.</p>\n\n<p>Um inteiro <code>n</code> é uma potência de quatro se existir um inteiro <code>x</code> tal que <code>n == 4<sup>x</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 16\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> false\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria resolver isso sem loops/recursão?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "343",
    "paidOnly": false,
    "title": "Integer Break",
    "titleSlug": "integer-break",
    "url": "https://leetcode.com/problems/integer-break",
    "description_url": "https://leetcode.com/problems/integer-break/description/",
    "description": "<p>Given an integer <code>n</code>, break it into the sum of <code>k</code> <strong>positive integers</strong>, where <code>k &gt;= 2</code>, and maximize the product of those integers.</p>\n\n<p>Return <em>the maximum product you can get</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> 2 = 1 + 1, 1 &times; 1 = 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 10\n<strong>Output:</strong> 36\n<strong>Explanation:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= n &lt;= 58</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/integer-break/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def integerBreak(self, n: int) -> int:\n    if n == 2:\n      return 1\n    if n == 3:\n      return 2\n\n    ans = 1\n\n    while n > 4:\n      n -= 3\n      ans *= 3\n    ans *= n\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int integerBreak(int n) {\n    // If an optimal product contains a factor f >= 4, then we can replace it\n    // With 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f,\n    // We never need a factor >= 4, meaning we only need factors 1, 2, and 3\n    // (and 1 is wasteful).\n    // Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice.\n    if (n == 2)\n      return 1; // 1 * 1\n    if (n == 3)\n      return 2; // 1 * 2\n\n    int ans = 1;\n\n    while (n > 4) {\n      n -= 3;\n      ans *= 3;\n    }\n    ans *= n;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int integerBreak(int n) {\n    // If an optimal product contains a factor f >= 4, then we can replace it\n    // With 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f,\n    // We never need a factor >= 4, meaning we only need factors 1, 2, and 3\n    // (and 1 is wasteful).\n    // Also, 3 * 3 is better than 2 * 2 * 2, so we never use 2 more than twice.\n    if (n == 2)  // 1 * 1\n      return 1;\n    if (n == 3)  // 1 * 2\n      return 2;\n\n    int ans = 1;\n\n    while (n > 4) {\n      n -= 3;\n      ans *= 3;\n    }\n    ans *= n;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/343.html",
    "category": "Algorithms",
    "acceptance_rate": 61.06932605344774,
    "topics": [
      "Math",
      "Dynamic Programming"
    ],
    "hints": [
      "There is a simple O(n) solution to this problem.",
      "You may check the breaking results of <i>n</i> ranging from 7 to 10 to discover the regularities."
    ],
    "likes": 5242,
    "dislikes": 458,
    "similar_questions": "[{\"title\": \"Maximize Number of Nice Divisors\", \"titleSlug\": \"maximize-number-of-nice-divisors\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"394.6K\", \"totalSubmission\": \"646.2K\", \"totalAcceptedRaw\": 394608, \"totalSubmissionRaw\": 646164, \"acRate\": \"61.1%\"}",
    "title_pt": "Quebra de Inteiro",
    "description_pt": "<p>Dado um inteiro <code>n</code>, quebre-o na soma de <code>k</code> <strong>inteiros positivos</strong>, onde <code>k &gt;= 2</code>, e maximize o produto desses inteiros.</p>\n\n<p>Retorne <em>o produto máximo que você pode obter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> 2 = 1 + 1, 1 &times; 1 = 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 10\n<strong>Saída:</strong> 36\n<strong>Explicação:</strong> 10 = 3 + 3 + 4, 3 &times; 3 &times; 4 = 36.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= n &lt;= 58</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Há uma solução simples de O(n) para este problema.",
      "Dica 2: Você pode verificar os resultados da decomposição de <i>n</i> variando de 7 a 10 para descobrir as regularidades."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "344",
    "paidOnly": false,
    "title": "Reverse String",
    "titleSlug": "reverse-string",
    "url": "https://leetcode.com/problems/reverse-string",
    "description_url": "https://leetcode.com/problems/reverse-string/description/",
    "description": "<p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p>\n\n<p>You must do this by modifying the input array <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> with <code>O(1)</code> extra memory.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n<strong>Output:</strong> [\"o\",\"l\",\"l\",\"e\",\"h\"]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n<strong>Output:</strong> [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is a <a href=\"https://en.wikipedia.org/wiki/ASCII#Printable_characters\" target=\"_blank\">printable ascii character</a>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseString(self, s: List[str]) -> None:\n    l = 0\n    r = len(s) - 1\n\n    while l < r:\n      s[l], s[r] = s[r], s[l]\n      l += 1\n      r -= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public void reverseString(char[] s) {\n    int l = 0;\n    int r = s.length - 1;\n\n    while (l < r) {\n      char temp = s[l];\n      s[l++] = s[r];\n      s[r--] = temp;\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  void reverseString(vector<char>& s) {\n    int l = 0;\n    int r = s.size() - 1;\n\n    while (l < r)\n      swap(s[l++], s[r--]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/344.html",
    "category": "Algorithms",
    "acceptance_rate": 79.6637784214768,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [
      "The entire logic for reversing a string is based on using the opposite directional two-pointer approach!"
    ],
    "likes": 8979,
    "dislikes": 1192,
    "similar_questions": "[{\"title\": \"Reverse Vowels of a String\", \"titleSlug\": \"reverse-vowels-of-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse String II\", \"titleSlug\": \"reverse-string-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.2M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 3161082, \"totalSubmissionRaw\": 3968031, \"acRate\": \"79.7%\"}",
    "title_pt": "Inverter String",
    "description_pt": "<p>Escreva uma função que inverta uma string. A string de entrada é fornecida como um array de caracteres <code>s</code>.</p>\n\n<p>Você deve fazer isso modificando o array de entrada <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" target=\"_blank\">in-place</a> com <code>O(1)</code> de memória extra.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n<strong>Saída:</strong> [\"o\",\"l\",\"l\",\"e\",\"h\"]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n<strong>Saída:</strong> [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> é um <a href=\"https://en.wikipedia.org/wiki/ASCII#Printable_characters\" target=\"_blank\">caractere ascii imprimível</a>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Toda a lógica para inverter uma string é baseada no uso da abordagem de dois ponteiros em direções opostas!"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "345",
    "paidOnly": false,
    "title": "Reverse Vowels of a String",
    "titleSlug": "reverse-vowels-of-a-string",
    "url": "https://leetcode.com/problems/reverse-vowels-of-a-string",
    "description_url": "https://leetcode.com/problems/reverse-vowels-of-a-string/description/",
    "description": "<p>Given a string <code>s</code>, reverse only all the vowels in the string and return it.</p>\n\n<p>The vowels are <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code>, and <code>&#39;u&#39;</code>, and they can appear in both lower and upper cases, more than once.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;IceCreAm&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;AceCreIm&quot;</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The vowels in <code>s</code> are <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. On reversing the vowels, s becomes <code>&quot;AceCreIm&quot;</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;leetcode&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">&quot;leotcede&quot;</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consist of <strong>printable ASCII</strong> characters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-vowels-of-a-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseVowels(self, s: str) -> str:\n    charList = list(s)\n    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}\n    l = 0\n    r = len(s) - 1\n\n    while l < r:\n      while l < r and charList[l] not in vowels:\n        l += 1\n      while l < r and charList[r] not in vowels:\n        r -= 1\n      charList[l], charList[r] = charList[r], charList[l]\n      l += 1\n      r -= 1\n\n    return ''.join(charList)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String reverseVowels(String s) {\n    final String vowels = \"aeiouAEIOU\";\n    StringBuilder sb = new StringBuilder(s);\n    int l = 0;\n    int r = s.length() - 1;\n\n    while (l < r) {\n      while (l < r && !vowels.contains(\"\" + sb.charAt(l)))\n        ++l;\n      while (l < r && !vowels.contains(\"\" + sb.charAt(r)))\n        --r;\n      sb.setCharAt(l, s.charAt(r));\n      sb.setCharAt(r, s.charAt(l));\n      ++l;\n      --r;\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string reverseVowels(string s) {\n    const unordered_set<char> vowels{'a', 'e', 'i', 'o', 'u',\n                                     'A', 'E', 'I', 'O', 'U'};\n    int l = 0;\n    int r = s.length() - 1;\n\n    while (l < r) {\n      while (l < r && !vowels.count(s[l]))\n        ++l;\n      while (l < r && !vowels.count(s[r]))\n        --r;\n      swap(s[l++], s[r--]);\n    }\n\n    return s;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/345.html",
    "category": "Algorithms",
    "acceptance_rate": 57.8314412160862,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 4941,
    "dislikes": 2831,
    "similar_questions": "[{\"title\": \"Reverse String\", \"titleSlug\": \"reverse-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Remove Vowels from a String\", \"titleSlug\": \"remove-vowels-from-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Faulty Keyboard\", \"titleSlug\": \"faulty-keyboard\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sort Vowels in a String\", \"titleSlug\": \"sort-vowels-in-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1256289, \"totalSubmissionRaw\": 2172335, \"acRate\": \"57.8%\"}",
    "title_pt": "Reverter as Vogais de uma String",
    "description_pt": "<p>Dada uma string <code>s</code>, reverta apenas todas as vogais na string e retorne-a.</p>\n\n<p>As vogais são <code>&#39;a&#39;</code>, <code>&#39;e&#39;</code>, <code>&#39;i&#39;</code>, <code>&#39;o&#39;</code> e <code>&#39;u&#39;</code>, e elas podem aparecer tanto em minúsculas quanto em maiúsculas, mais de uma vez.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;IceCreAm&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;AceCreIm&quot;</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>As vogais em <code>s</code> são <code>[&#39;I&#39;, &#39;e&#39;, &#39;e&#39;, &#39;A&#39;]</code>. Ao reverter as vogais, s torna-se <code>&quot;AceCreIm&quot;</code>.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;leetcode&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">&quot;leotcede&quot;</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em caracteres <strong>ASCII imprimíveis</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "347",
    "paidOnly": false,
    "title": "Top K Frequent Elements",
    "titleSlug": "top-k-frequent-elements",
    "url": "https://leetcode.com/problems/top-k-frequent-elements",
    "description_url": "https://leetcode.com/problems/top-k-frequent-elements/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k</code> <em>most frequent elements</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1,1,2,2,3], k = 2\n<strong>Output:</strong> [1,2]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1], k = 1\n<strong>Output:</strong> [1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>k</code> is in the range <code>[1, the number of unique elements in the array]</code>.</li>\n\t<li>It is <strong>guaranteed</strong> that the answer is <strong>unique</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Your algorithm&#39;s time complexity must be better than <code>O(n log n)</code>, where n is the array&#39;s size.</p>\n",
    "solution_url": "https://leetcode.com/problems/top-k-frequent-elements/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Heap\n\nLet's start from the simple [heap](https://en.wikipedia.org/wiki/Heap_(data_structure)) approach with $$\\mathcal{O}(N \\log k)$$ time complexity. To ensure that $$\\mathcal{O}(N \\log k)$$ is always less than $$\\mathcal{O}(N \\log N)$$, the particular case $$k = N$$ could be considered separately and solved in $$\\mathcal{O}(1)$$ time. \n\n**Algorithm**\n\n- The first step is to build a hash map `element -> its frequency`. In Java, we use the data structure `HashMap`. Python provides a dictionary subclass `Counter` to initialize the hash map we need directly from the input array. This step takes $$\\mathcal{O}(N)$$ time where `N` is a number of elements in the list.\n\n- The second step is to build a heap of _size k using N elements_. To add the first `k` elements takes a linear time $$\\mathcal{O}(k)$$ in the average case, and $O(\\log 1 + \\log 2 + ... + \\log k) = O(log k!) = \\mathcal{O}(k \\log k)$ in the worst case. It's equivalent to [heapify implementation in Python](https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l16). After the first `k` elements we start to push and pop at each step, `N - k` steps in total. The time complexity of heap push/pop is $$\\mathcal{O}(\\log k)$$ and we do it `N - k` times which means $$\\mathcal{O}((N - k)\\log k)$$ time complexity. Adding both parts up, we get $$\\mathcal{O}(N \\log k)$$ time complexity for the second step.\n\n- The third and last step is to convert the heap into an output array. That could be done in $$\\mathcal{O}(k \\log k)$$ time.\n \nIn Python, library `heapq` provides a method `nlargest`, which [combines the last two steps under the hood](https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l203) and has the same $$\\mathcal{O}(N \\log k)$$ time complexity.\n\n![diff](../Figures/347_rewrite/summary.png)\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/3WH339tU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3WH339tU\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$\\mathcal{O}(N + N \\log k)$$ if $$k < N$$ and $$\\mathcal{O}(1)$$ in the particular case of $$N = k$$. That ensures time complexity to be better than $$\\mathcal{O}(N \\log N)$$.\n\n* Space complexity : $$\\mathcal{O}(N + k)$$ to store the hash map with not more $$N$$ elements and a heap with $$k$$ elements.\n<br />\n<br />\n\n\n---\n\n### Approach 2: Quickselect (Hoare's selection algorithm)\n\nQuickselect is a [textbook algorithm](https://en.wikipedia.org/wiki/Quickselect) typically used to solve the problems \"find `k`*th* something\": `k`*th* smallest, `k`*th* largest, `k`*th* most frequent, `k`*th* less frequent, etc. Like quicksort, quickselect was developed by [Tony Hoare](https://en.wikipedia.org/wiki/Tony_Hoare) and is also known as _Hoare's selection algorithm_.\n\nIt has $$\\mathcal{O}(N)$$ _average_ time complexity and is widely used in practice. It is worth noting that its worst-case time complexity is $$\\mathcal{O}(N^2)$$, although the probability of this worst-case is negligible.\n\nThe approach is the same as for quicksort.\n\n> One chooses a pivot and defines its position in a sorted array in a linear time using the so-called _partition algorithm_. \n\nAs an output, we have an array where the pivot is in its perfect position in the ascending sorted array, sorted by the frequency. All elements on the left of the pivot are less frequent than the pivot, and all elements on the right are more frequent or have the same frequency.\n\nHence the array is now split into two parts. If by chance our pivot element took `N - k`*th* final position, then $$k$$ elements on the right are these top $$k$$ frequent we're looking for. If not, we can choose one more pivot and place it in its perfect position.\n\n![diff](../Figures/347_rewrite/hoare.png)\n\nIf that were a quicksort algorithm, one would have to process both parts of the array. That would result in $$\\mathcal{O}(N \\log N)$$ time complexity. In this case, there is no need to deal with both parts since one knows in which part to search for `N - k`*th* less frequent element, and that reduces the average time complexity to $$\\mathcal{O}(N)$$.\n\n**Algorithm**\n\nThe algorithm is quite straightforward :\n\n* Build a hash map `element -> its frequency` and convert its keys into the array `unique` of unique elements. Note that elements are unique, but their frequencies are _not_. That means we need a partition algorithm that works fine with _duplicates_. \n\n* Work with `unique` array. \nUse a partition scheme (please check the next section) to place the pivot into its perfect position `pivot_index` in the sorted array, move less frequent elements to the left of the pivot, and more frequent or of the same frequency - to the right.\n\n* Compare `pivot_index` and `N - k`.\n \n    - If `pivot_index == N - k`, the pivot is `N - k`*th* most frequent element, and all elements on the right are more frequent or of the same frequency. Return these top $$k$$ frequent elements.\n    \n    - Otherwise, choose the side of the array to proceed recursively.\n    \n![diff](../Figures/347_rewrite/details.png)\n\n**Lomuto's Partition Scheme**\n\nThere is a zoo of partition algorithms. The most simple one is [Lomuto's Partition Scheme](https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme), and so is what we will use in this article.\n\nHere is how it works:\n\n- Move the pivot at the end of the array using swap. \n\n- Set the pointer at the beginning of the array `store_index = left`.\n    \n- Iterate over the array and move all less frequent elements to the left `swap(store_index, i)`. Move `store_index` one step to the right after each swap.\n\n- Move the pivot to its final place, and return this index.\n\n!?!../Documents/347_RES.json:1000,556!?!\n\n<iframe src=\"https://leetcode.com/playground/56S3UHe5/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"56S3UHe5\"></iframe>\n \n**Implementation**\n\nHere is a total algorithm implementation. \n\n<iframe src=\"https://leetcode.com/playground/eAsoNpLA/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"eAsoNpLA\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$\\mathcal{O}(N)$$ in the average case, \n    $$\\mathcal{O}(N^2)$$ in the worst case. [Please refer to this card for a good detailed explanation of Master Theorem](https://leetcode.com/explore/learn/card/recursion-ii/470/divide-and-conquer/2871/). Master Theorem helps to get an average complexity by writing the algorithm cost as $$T(N) = a T(N / b) + f(N)$$. Here we have an example of Master Theorem case III: $$T(N) = T \\left(\\frac{N}{2}\\right) + N$$, which results in $$\\mathcal{O}(N)$$ time complexity. That's the case with random pivots.\n    \n    In the worst case of constantly badly chosen pivots, the problem is not divided by half at each step, it becomes just one element less, which leads to $$\\mathcal{O}(N^2)$$ time complexity. It happens, for example, if at each step you choose the pivot not randomly, but take the rightmost element. For the random pivot choice, the probability of having such a worst-case is negligibly small. \n\n* Space complexity: up to $$\\mathcal{O}(N)$$ to store hash map and array of unique elements.\n<br />\n<br />\n\n\n---\n### Further Discussion: Could We Do Worst-Case Linear Time? \n\nIn theory, we could, the algorithm is called [Median of Medians](https://en.wikipedia.org/wiki/Median_of_medians).\n\nThis method is never used in practice because of two drawbacks:\n\n- It's _outperformer_. Yes, it works in a linear time $$\\alpha N$$, but the constant $$\\alpha$$ is so large that in practice it often works even slower than $$N^2$$.  \n\n- It doesn't work with duplicates.\n<br />\n<br />\n\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int num;\n  public int freq;\n  public T(int num, int freq) {\n    this.num = num;\n    this.freq = freq;\n  }\n}\n\nclass Solution {\n  public int[] topKFrequent(int[] nums, int k) {\n    final int n = nums.length;\n    int[] ans = new int[k];\n    Map<Integer, Integer> count = new HashMap<>();\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.freq - b.freq);\n\n    for (final int num : nums)\n      count.merge(num, 1, Integer::sum);\n\n    for (Map.Entry<Integer, Integer> entry : count.entrySet()) {\n      final int num = entry.getKey();\n      final int freq = entry.getValue();\n      minHeap.offer(new T(num, freq));\n      if (minHeap.size() > k)\n        minHeap.poll();\n    }\n\n    for (int i = 0; i < k; ++i)\n      ans[i] = minHeap.poll().num;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int num;\n  int freq;\n  T(int num, int freq) : num(num), freq(freq) {}\n};\n\nclass Solution {\n public:\n  vector<int> topKFrequent(vector<int>& nums, int k) {\n    const int n = nums.size();\n    vector<int> ans;\n    unordered_map<int, int> count;\n    auto compare = [](const T& a, const T& b) { return a.freq > b.freq; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n\n    for (const int num : nums)\n      ++count[num];\n\n    for (const auto& [num, freq] : count) {\n      minHeap.emplace(num, freq);\n      if (minHeap.size() > k)\n        minHeap.pop();\n    }\n\n    while (!minHeap.empty())\n      ans.push_back(minHeap.top().num), minHeap.pop();\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/347.html",
    "category": "Algorithms",
    "acceptance_rate": 64.40407286688249,
    "topics": [
      "Array",
      "Hash Table",
      "Divide and Conquer",
      "Sorting",
      "Heap (Priority Queue)",
      "Bucket Sort",
      "Counting",
      "Quickselect"
    ],
    "hints": [],
    "likes": 18234,
    "dislikes": 724,
    "similar_questions": "[{\"title\": \"Word Frequency\", \"titleSlug\": \"word-frequency\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Characters By Frequency\", \"titleSlug\": \"sort-characters-by-frequency\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split Array into Consecutive Subsequences\", \"titleSlug\": \"split-array-into-consecutive-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Top K Frequent Words\", \"titleSlug\": \"top-k-frequent-words\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Closest Points to Origin\", \"titleSlug\": \"k-closest-points-to-origin\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Features by Popularity\", \"titleSlug\": \"sort-features-by-popularity\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sender With Largest Word Count\", \"titleSlug\": \"sender-with-largest-word-count\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Linked List Frequency\", \"titleSlug\": \"linked-list-frequency\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.8M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 2796729, \"totalSubmissionRaw\": 4342475, \"acRate\": \"64.4%\"}",
    "title_pt": "Elementos Mais Frequentes entre os Top K",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>os</em> <code>k</code> <em>elementos mais frequentes</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1,1,2,2,3], k = 2\n<strong>Saída:</strong> [1,2]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1], k = 1\n<strong>Saída:</strong> [1]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>k</code> está no intervalo <code>[1, o número de elementos únicos no array]</code>.</li>\n\t<li>É <strong>garantido</strong> que a resposta é <strong>única</strong>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> A complexidade de tempo do seu algoritmo deve ser melhor do que <code>O(n log n)</code>, onde n é o tamanho do array.</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "349",
    "paidOnly": false,
    "title": "Intersection of Two Arrays",
    "titleSlug": "intersection-of-two-arrays",
    "url": "https://leetcode.com/problems/intersection-of-two-arrays",
    "description_url": "https://leetcode.com/problems/intersection-of-two-arrays/description/",
    "description": "<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their <span data-keyword=\"array-intersection\">intersection</span></em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2]\n<strong>Output:</strong> [2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n<strong>Output:</strong> [9,4]\n<strong>Explanation:</strong> [4,9] is also accepted.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/intersection-of-two-arrays/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Sorting and Two Pointers\n\n#### Intuition\n\nIf `nums1` and `nums2` are sorted, we can use a two pointers approach to find elements that appear in both arrays. Initialize one pointer for each array that starts at the smallest element. \n\nIf the numbers at both pointers are the same, add the number to a set that stores integers that appear in both arrays. Then, increase both pointers by $1$, since this element is already processed.  \n\nOtherwise, if the numbers at both pointers are not equal, the smaller of the two values cannot appear in the other array because both arrays are sorted. Therefore, we can increase the pointer of the smaller value.\n\n#### Algorithm\n\n1. Sort `nums1` and `nums2` arrays.\n2. Create a pointer for each array, initially set to $0$.\n3. Initialize an empty set that stores intersecting integers.\n4. If the integers at both pointers equal the same value, add this value to the intersecting set and increment both pointers.\n5. Otherwise, increment the pointer that points to the smaller integer value.\n6. Repeat steps 4 and 5 until a pointer is out of bounds.\n7. Convert the intersection set into an array.\n8. Return the resulting array.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/esWGp92Z/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"esWGp92Z\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n \\log n + m \\log m)$, where $n$ and $m$ are the arrays' lengths. This dominating term comes from the need to sort both input arrays at the beginning of the solution.\n \n* Space complexity: $O(\\min(m, n))$ in the worst case when all elements in the smaller array are unique and present in the larger array. This space is necessary to store elements in the set `intersection`.  \n\n    - The space used to store the result array is counted in the space complexity, making the worst case $O(\\min(m, n))$.  \n    - Some extra space is used when sorting the arrays in place, and the space complexity depends on the programming language:  \n        - In Python, the `sort()` method uses the Timsort algorithm, which requires O(n) additional space in the worst case.  \n        - In Java, `Arrays.sort()` for primitive types uses a Dual-Pivot QuickSort, which has a worst-case space complexity of O(\\log n) due to recursion.  \n\n---\n\n### Approach 2: Built-in Set Intersection\n\n#### Intuition\n\nThere are built-in intersection facilities, which provide $O(n + m)$ time complexity in the average case and $O(n \\times m)$ time complexity in the worst case. \n\n> In Python it's the [intersection operator](https://wiki.python.org/moin/TimeComplexity#set), and in Java it's the [retainAll() function](https://docs.oracle.com/javase/8/docs/api/java/util/AbstractCollection.html#retainAll-java.util.Collection-).\n\n#### Algorithm\n\n1. Initialize a set `set1` and add all elements of `nums1` to it.\n2. Initialize a set `set2` and add all elements of `nums2` to it.\n3. Call the built-in set intersection method (either `retainAll()` in Java, or `&` operator in Python).\n4. Transform the resulting set into an array and return this result.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/C2TF5Yk6/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"C2TF5Yk6\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n + m)$, where $n$ and $m$ are the arrays' lengths in the average case and $O(n \\times m)$ [in the worst case when the load factor is high enough](https://wiki.python.org/moin/TimeComplexity#set).\n \n* Space complexity: $O(m + n)$ because in the worst case, when all elements in the arrays are unique, $n$ space is used to store `set1` and $m$ space is used to store `set2`. The space used to store the result is not counted in the space complexity.\n\n---\n\n### Approach 3: Two Sets\n\n#### Intuition\n\nThe naive approach would be to iterate through the values in the first array, `nums1`, and check whether each one is in `nums2`. If yes, add the value to the output. Such an approach would result in a less efficient solution.\n\n> To solve the problem in linear time, let's use the data structure `set`, which provides `in/contains` operations in $O(1)$ time in the average case.\n\nThe idea is to convert both arrays into sets and then iterate over the smallest set while checking the presence of each element in the larger set.\n\n!?!../Documents/349_LIS.json:1000,352!?!\n\n#### Algorithm\n\n1. Initialize a set `set1` and add all elements of `nums1` to it.\n2. Initialize a set `set2` and add all elements of `nums2` to it.\n3. If `set1` has more elements than `set2`, swap them.\n4. For each element in `set1`, add it to the result array if it also appears in `set2`.\n5. Result the result array.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/RAoCNPwG/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"RAoCNPwG\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n + m)$, where $n$ and $m$ are the arrays' lengths. $O(n)$ time is used to convert `nums1` into a set, $O(m)$ time is used to convert `nums2`, and `contains/in` operations are $O(1)$ in the average case.\n \n* Space complexity: $O(m + n)$ because in the worst case, when all elements in the arrays are unique, $n$ space is used to store `set1` and $m$ space is used to store `set2`.\n\n---\n\n### Approach 4: One Dictionary\n\n#### Intuition\n\nThis approach uses only one additional data structure and one pass through each of `nums1` and `nums2`. The idea is to use a dictionary/map rather than a set to store information about values that appear in each array. \n\nDefine this dictionary as `seen`, where the key is an element that exists in one or both input arrays, and the value stores either $0$ or $1$. A number `x` appears as a key in this dictionary, indicating it is present in at least one array, and the value of the key indicates if `x` has been observed in both arrays and added to the `result` array.\n\n#### Algorithm\n\n1. Initialize a dictionary/map `seen` and the `result` array.\n2. For each `x` in `nums1`, set `seen[x]` to $1$.\n3. For each `x` in `nums2`, add `x` to `result` if `seen[x]` equals $1$. Then, set `seen[x]` to $0$, as this element has already been included in the result.\n4. Result the result array.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/6m6gWp2U/shared\" frameBorder=\"0\" width=\"100%\" height=\"480\" name=\"6m6gWp2U\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of `nums1` and $m$ be the length of `nums2`.\n\n* Time complexity: $O(n + m)$ in the average case and $O(n \\times m)$ [in the worst case when the load factor is high enough](https://wiki.python.org/moin/TimeComplexity#set).\n \n* Space complexity: $O(n)$ because we use a map of size $n$ store the elements from `nums1`. The `result` array is just used to store the result, so it is not counted in the space complexity.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n    ans = []\n    nums1 = set(nums1)\n\n    for num in nums2:\n      if num in nums1:\n        ans.append(num)\n        nums1.remove(num)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] intersection(int[] nums1, int[] nums2) {\n    List<Integer> ans = new ArrayList<>();\n    Set<Integer> set = Arrays.stream(nums1).boxed().collect(Collectors.toSet());\n\n    for (final int num : nums2)\n      if (set.remove(num))\n        ans.add(num);\n\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n    vector<int> ans;\n    unordered_set<int> set{begin(nums1), end(nums1)};\n\n    for (const int num : nums2)\n      if (set.erase(num))\n        ans.push_back(num);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/349.html",
    "category": "Algorithms",
    "acceptance_rate": 76.3228147137012,
    "topics": [
      "Array",
      "Hash Table",
      "Two Pointers",
      "Binary Search",
      "Sorting"
    ],
    "hints": [],
    "likes": 6420,
    "dislikes": 2319,
    "similar_questions": "[{\"title\": \"Intersection of Two Arrays II\", \"titleSlug\": \"intersection-of-two-arrays-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Intersection of Three Sorted Arrays\", \"titleSlug\": \"intersection-of-three-sorted-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Difference of Two Arrays\", \"titleSlug\": \"find-the-difference-of-two-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Common Words With One Occurrence\", \"titleSlug\": \"count-common-words-with-one-occurrence\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Choose Numbers From Two Arrays in Range\", \"titleSlug\": \"choose-numbers-from-two-arrays-in-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Intersection of Multiple Arrays\", \"titleSlug\": \"intersection-of-multiple-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Common Value\", \"titleSlug\": \"minimum-common-value\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Size of a Set After Removals\", \"titleSlug\": \"maximum-size-of-a-set-after-removals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1501799, \"totalSubmissionRaw\": 1967697, \"acRate\": \"76.3%\"}",
    "title_pt": "Interseção de Dois Arrays",
    "description_pt": "<p>Dado dois arrays de inteiros <code>nums1</code> e <code>nums2</code>, retorne <em>um array de sua <span data-keyword=\"array-intersection\">interseção</span></em>. Cada elemento no resultado deve ser <strong>único</strong> e você pode retornar o resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2,2,1], nums2 = [2,2]\n<strong>Saída:</strong> [2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n<strong>Saída:</strong> [9,4]\n<strong>Explicação:</strong> [4,9] também é aceito.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "350",
    "paidOnly": false,
    "title": "Intersection of Two Arrays II",
    "titleSlug": "intersection-of-two-arrays-ii",
    "url": "https://leetcode.com/problems/intersection-of-two-arrays-ii",
    "description_url": "https://leetcode.com/problems/intersection-of-two-arrays-ii/description/",
    "description": "<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must appear as many times as it shows in both arrays and you may return the result in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2]\n<strong>Output:</strong> [2,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n<strong>Output:</strong> [4,9]\n<strong>Explanation:</strong> [9,4] is also accepted.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>What if the given array is already sorted? How would you optimize your algorithm?</li>\n\t<li>What if <code>nums1</code>&#39;s size is small compared to <code>nums2</code>&#39;s size? Which algorithm is better?</li>\n\t<li>What if elements of <code>nums2</code> are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/intersection-of-two-arrays-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n    if len(nums1) > len(nums2):\n      return self.intersect(nums2, nums1)\n\n    ans = []\n    count = Counter(nums1)\n\n    for num in nums2:\n      if count[num] > 0:\n        ans.append(num)\n        count[num] -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] intersect(int[] nums1, int[] nums2) {\n    if (nums1.length > nums2.length)\n      return intersect(nums2, nums1);\n\n    List<Integer> ans = new ArrayList<>();\n    Map<Integer, Integer> count = new HashMap<>();\n\n    for (final int num : nums1)\n      count.put(num, count.getOrDefault(num, 0) + 1);\n\n    for (final int num : nums2)\n      if (count.containsKey(num) && count.get(num) > 0) {\n        ans.add(num);\n        count.put(num, count.get(num) - 1);\n      }\n\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {\n    if (nums1.size() > nums2.size())\n      return intersect(nums2, nums1);\n\n    vector<int> ans;\n    unordered_map<int, int> count;\n\n    for (const int num : nums1)\n      ++count[num];\n\n    for (const int num : nums2)\n      if (count.count(num) && count[num]-- > 0)\n        ans.push_back(num);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/350.html",
    "category": "Algorithms",
    "acceptance_rate": 59.002053953573764,
    "topics": [
      "Array",
      "Hash Table",
      "Two Pointers",
      "Binary Search",
      "Sorting"
    ],
    "hints": [],
    "likes": 7902,
    "dislikes": 990,
    "similar_questions": "[{\"title\": \"Intersection of Two Arrays\", \"titleSlug\": \"intersection-of-two-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Common Characters\", \"titleSlug\": \"find-common-characters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Difference of Two Arrays\", \"titleSlug\": \"find-the-difference-of-two-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Choose Numbers From Two Arrays in Range\", \"titleSlug\": \"choose-numbers-from-two-arrays-in-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Intersection of Multiple Arrays\", \"titleSlug\": \"intersection-of-multiple-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Common Value\", \"titleSlug\": \"minimum-common-value\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1542586, \"totalSubmissionRaw\": 2614465, \"acRate\": \"59.0%\"}",
    "title_pt": "Interseção de Dois Arrays II",
    "description_pt": "<p>Dados dois arrays de inteiros <code>nums1</code> e <code>nums2</code>, retorne <em>um array de sua interseção</em>. Cada elemento no resultado deve aparecer tantas vezes quanto aparece em ambos os arrays e você pode retornar o resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2,2,1], nums2 = [2,2]\n<strong>Saída:</strong> [2,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n<strong>Saída:</strong> [4,9]\n<strong>Explicação:</strong> [9,4] também é aceito.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>E se o array fornecido já estiver ordenado? Como você otimizaria seu algoritmo?</li>\n\t<li>E se o tamanho de <code>nums1</code> for pequeno em comparação com o tamanho de <code>nums2</code>? Qual algoritmo é melhor?</li>\n\t<li>E se os elementos de <code>nums2</code> estiverem armazenados em disco, e a memória for limitada de modo que você não possa carregar todos os elementos na memória de uma vez?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "352",
    "paidOnly": false,
    "title": "Data Stream as Disjoint Intervals",
    "titleSlug": "data-stream-as-disjoint-intervals",
    "url": "https://leetcode.com/problems/data-stream-as-disjoint-intervals",
    "description_url": "https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/",
    "description": "<p>Given a data stream input of non-negative integers <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code>, summarize the numbers seen so far as a list of disjoint intervals.</p>\n\n<p>Implement the <code>SummaryRanges</code> class:</p>\n\n<ul>\n\t<li><code>SummaryRanges()</code> Initializes the object with an empty stream.</li>\n\t<li><code>void addNum(int value)</code> Adds the integer <code>value</code> to the stream.</li>\n\t<li><code>int[][] getIntervals()</code> Returns a summary of the integers in the stream currently as a list of disjoint intervals <code>[start<sub>i</sub>, end<sub>i</sub>]</code>. The answer should be sorted by <code>start<sub>i</sub></code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;SummaryRanges&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]\n<strong>Output</strong>\n[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n\n<strong>Explanation</strong>\nSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1);      // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3);      // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7);      // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2);      // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= value &lt;= 10<sup>4</sup></code></li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>addNum</code> and <code>getIntervals</code>.</li>\n\t<li>At most <code>10<sup>2</sup></code>&nbsp;calls will be made to&nbsp;<code>getIntervals</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?</p>\n",
    "solution_url": "https://leetcode.com/problems/data-stream-as-disjoint-intervals/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n\n### Approach 1: Save all values in an ordered set\n\n#### Intuition\n\nThe question asks to combine consecutive values into intervals, namely, if we have values of 1, 2, 3, and 4, we can make an interval that starts from 1 and ends at 4. If the data is sorted, we can easily iterate over it to find the intervals. A data structure is needed that allows us to insert elements while maintaining sorted order, otherwise we would need to sort the data every time we call `getIntervals`, which is expensive.\n\nJava's TreeSet can do the work. The reason to use a TreeSet is that we can iterate on the values in it in the increasing order and elements can be added in $O(\\log{}n)$. In Python we can use SortedList and in C++ we can use the standard library's set. To find the intervals, we can look at each value and check whether it is adjacent to the previous one. If it is, we can build an interval, otherwise we need to start a new one.\n\n#### Algorithm\n\nInitialize a TreeSet equivalent data structure `values`.\n\n\n##### addNum(int value)\nSimply add `value` into `values`. If your language's TreeSet equivalent allows duplicate values like Python's SortedList, you will also need to check that `value` does not already exist in `values` as duplicates will break the algorithm.\n\n##### getIntervals\n\n\n* If `values` is empty, return an empty array.\n* Create an empty list of intervals.\n* Set `left = right = -1`. `left` represents the left bound of the current interval and `right` represents the right bound.\n* Iterate over `values`. At each iteration:\n   *  If `left < 0` set `left = right = value` \n   *  else if `value = right + 1`, set `right = value` as we can continue the current interval.\n   *  else, we cannot continue the current interval. Insert `[left, right]` into `intervals` and set `left = right = value` to start a new one.\n* Insert `[left, right]` into `intervals` and return `intervals`\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/GQnYWXuW/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"GQnYWXuW\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the total number of calls of `addNum`.\n\n* Time complexity: $O(log(N))$ for addNum, $O(N)$ for getIntervals.\n\n  For `addNum`, we insert a value into the TreeSet which takes $O(log(N))$ time.\n  For `getIntervals`, we iterate all the values in the TreeSet which is the same as traversing the whole tree, so the time complexity is $O(N)$.\n\n* Space complexity: $O(N)$.\n\n  This is just the space to save all the values in the TreeSet.\n\n\n### Approach 2: Maintain all the intervals in ordered map\n\n#### Intuition\nInstead of storing the values and then building the intervals every time we call `getIntervals`, we can just store the intervals themselves and update them every time we add a number.\n\nIn Java, we can maintain a TreeMap in which each entry represents an interval. The key and value are the left and right bounds of an interval. We still want to maintain the intervals in sorted order so that when we add a number, we can easily find the interval a number is close to and perform merges if necessary. `getIntervals` then returns all the entries in the TreeMap. In Python, SortedDict can be used. In C++, STL map can be used.\n\n\nWhen we insert a `value`, there are 3 non-trivial cases (in all cases, blue represents existing intervals, red is the number being added, and cyan is the result after our operations):\n\n1. There is an interval with a right bound of `value - 1`.\nIn this case, we need to merge the this interval and the `value`, namely change the the interval's right bound into `value`.\n\n<center>\n<img src=\"../Figures/352/352_Data_Stream_as_Disjoint_Intervals_2.png\" width=\"500\"/>\n</center>\n<br>\n\n\n2. There is an interval with a left bound of `value + 1`.\nIn this case, we need to merge this interval and the `value`, namely change the interval's left bound into `value`.\n\n<center>\n<img src=\"../Figures/352/352_Data_Stream_as_Disjoint_Intervals_1.png\" width=\"500\"/>\n</center>\n<br>\n\n3. Both condition 1 and 2 are satisfied.\nThis is the combination of the previous 2 cases. We should make a new interval which \"connects\" the two intervals and replace them with the new one.\n\n<center>\n<img src=\"../Figures/352/352_Data_Stream_as_Disjoint_Intervals_3.png\" width=\"500\"/>\n</center>\n<br>\n\nTo be complete, there are 2 trivial cases as well:\n\n1. The `value` is already in the existing intervals.\nWe do nothing.\n\n2. All other cases.\nWe need to insert a new interval [`value`, `value`].\n\n\n#### Algorithm\n\nInitialize a TreeMap equivalent data structure `intervals`.\n\n\n##### addNum(int value)\n* Set `left = right = value`. These variables will represent the bounds of a new interval to be created.\n* Let `smallEntry` be the entry with the greatest key (left bound) no larger than `value` in `intervals`.\n* If `smallEntry` exists\n   * Let `previous` be the value (right bound) in `smallEntry`, if `previous >= value` then this is the first trivial case, so return. \n   * If `previous == value - 1`, set `left` to the key (left bound) in `smallEntry`. This is the first non trivial case, so we will prepare a merge.\n* Let `maxEntry` be the entry with the smallest key (left bound) larger than `value` in `intervals`.\n* If `maxEntry` exists and the key in it is `value + 1`, then this is the second non trivial case.\n  * Set `right` to the value in `maxEntry`.\n  * Remove the key `value + 1` from `intervals`.\n* Insert `[left, right]` into `intervals`. All cases are covered here. \n\n1. In the first case, we are updating the existing interval's entry since we set `left` to be that interval's key.\n2. In the second case, we removed the old interval and are now adding a new one with the `right` bound set to be the removed interval's old `right` bound and `left` updated to `value`.\n3. In the third case, we have done both of the above. We are replacing the interval on the left and deleting the interval on the right.\n4. For the 2nd trivial case, we didn't modify any intervals and `[left, right] = [value, value]`.\n\n\n\n##### getIntervals\nIterate over all the entries in `intervals` and return them in order.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/c7bDrXgu/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"c7bDrXgu\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the total number of calls of `addNum`.\n\n* Time complexity: $O(log(N))$ for `addNum`, $O(N)$ for `getIntervals`.\n\n  For `addNum`, in the worst case, we remove 2 entries from the TreeMap and add 1 entry, the time complexity for each operation is $O(log(N))$.\n  For `getIntervals`, we iterate all the entries in the TreeMap which is the same as traversing the whole tree, so the time complexity is $O(N)$.\n\n* Space complexity: $O(N)$.\n\n  This is just the space to save all the intervals in the TreeMap.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass SummaryRanges {\n  public void addNum(int val) {\n    if (map.containsKey(val))\n      return;\n\n    final Integer lo = map.lowerKey(val);  // Maximum in map < key\n    final Integer hi = map.higherKey(val); // Minimum in map > key\n\n    // {lo, map.get(lo)[1]} + val + {hi, map.get(hi)[1]} = {lo, map.get(hi)[1]}\n    if (lo != null && hi != null && map.get(lo)[1] + 1 == val && val + 1 == hi) {\n      map.get(lo)[1] = map.get(hi)[1];\n      map.remove(hi);\n      // {lo, map.get(lo)[1]} + val = {lo, val}\n      // (prevent adding duplicate entry by using '>=' instead of '==')\n    } else if (lo != null && map.get(lo)[1] + 1 >= val) {\n      map.get(lo)[1] = Math.max(map.get(lo)[1], val);\n      // Val + {hi, map.get(hi)[1]} = {val, map.get(hi)[1]}\n    } else if (hi != null && val + 1 == hi) {\n      map.put(val, new int[] {val, map.get(hi)[1]});\n      map.remove(hi);\n    } else {\n      map.put(val, new int[] {val, val});\n    }\n  }\n\n  public int[][] getIntervals() {\n    List<int[]> intervals = new ArrayList<>(map.values());\n    return intervals.toArray(new int[intervals.size()][]);\n  }\n\n  // {start: {start, end}}\n  private TreeMap<Integer, int[]> map = new TreeMap<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass SummaryRanges {\n public:\n  void addNum(int val) {\n    if (map.count(val))\n      return;\n\n    const int lo = lowerKey(val);\n    const int hi = higherKey(val);\n\n    // {lo, map[lo][1]} + val + {hi, map[hi][1]} = {lo, map[hi][1]}\n    if (lo >= 0 && hi >= 0 && map[lo][1] + 1 == val && val + 1 == hi) {\n      map[lo][1] = map[hi][1];\n      map.erase(hi);\n      // {lo, map[lo][1]} + val = {lo, val}\n      // (prevent adding duplicate entry by using '>=' instead of '==')\n    } else if (lo >= 0 && map[lo][1] + 1 >= val) {\n      map[lo][1] = max(map[lo][1], val);\n    } else if (hi >= 0 && val + 1 == hi) {\n      // Val + {hi, map[hi][1]} = {val, map[hi][1]}\n      map[val] = {val, map[hi][1]};\n      map.erase(hi);\n    } else {\n      map[val] = {val, val};\n    }\n  }\n\n  vector<vector<int>> getIntervals() {\n    vector<vector<int>> intervals;\n    for (const auto& [_, interval] : map)\n      intervals.push_back(interval);\n    return intervals;\n  }\n\n private:\n  map<int, vector<int>> map;  // {start: {start, end}}\n\n  // Maximum in map < key\n  int lowerKey(int key) {\n    auto it = map.lower_bound(key);  // Minimum in map >= key\n    if (it == begin(map))\n      return -1;\n    return (--it)->first;\n  }\n\n  // Minimum in map > key\n  int higherKey(int key) {\n    const auto it = map.upper_bound(key);  // Minimum in map > key\n    if (it == cend(map))\n      return -1;\n    return it->first;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/352.html",
    "category": "Algorithms",
    "acceptance_rate": 59.46726138271481,
    "topics": [
      "Binary Search",
      "Design",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 1776,
    "dislikes": 368,
    "similar_questions": "[{\"title\": \"Summary Ranges\", \"titleSlug\": \"summary-ranges\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Right Interval\", \"titleSlug\": \"find-right-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Module\", \"titleSlug\": \"range-module\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Integers in Intervals\", \"titleSlug\": \"count-integers-in-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"118.7K\", \"totalSubmission\": \"199.5K\", \"totalAcceptedRaw\": 118658, \"totalSubmissionRaw\": 199535, \"acRate\": \"59.5%\"}",
    "title_pt": "Fluxo de Dados como Intervalos Disjuntos",
    "description_pt": "<p>Dado um fluxo de entrada de dados de inteiros não negativos <code>a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub></code>, resuma os números vistos até agora como uma lista de intervalos disjuntos.</p>\n\n<p>Implemente a classe <code>SummaryRanges</code>:</p>\n\n<ul>\n\t<li><code>SummaryRanges()</code> Inicializa o objeto com um fluxo vazio.</li>\n\t<li><code>void addNum(int value)</code> Adiciona o inteiro <code>value</code> ao fluxo.</li>\n\t<li><code>int[][] getIntervals()</code> Retorna um resumo dos inteiros no fluxo atualmente como uma lista de intervalos disjuntos <code>[start<sub>i</sub>, end<sub>i</sub>]</code>. A resposta deve ser ordenada por <code>start<sub>i</sub></code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;SummaryRanges&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;, &quot;addNum&quot;, &quot;getIntervals&quot;]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]\n<strong>Saída</strong>\n[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n\n<strong>Explicação</strong>\nSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1);      // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3);      // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7);      // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2);      // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6);      // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= value &lt;= 10<sup>4</sup></code></li>\n\t<li>No máximo <code>3 * 10<sup>4</sup></code> chamadas serão feitas para <code>addNum</code> e <code>getIntervals</code>.</li>\n\t<li>No máximo <code>10<sup>2</sup></code>&nbsp;chamadas serão feitas para&nbsp;<code>getIntervals</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> E se houver muitas mesclagens e o número de intervalos disjuntos for pequeno em comparação com o tamanho do fluxo de dados?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "354",
    "paidOnly": false,
    "title": "Russian Doll Envelopes",
    "titleSlug": "russian-doll-envelopes",
    "url": "https://leetcode.com/problems/russian-doll-envelopes",
    "description_url": "https://leetcode.com/problems/russian-doll-envelopes/description/",
    "description": "<p>You are given a 2D array of integers <code>envelopes</code> where <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> represents the width and the height of an envelope.</p>\n\n<p>One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope&#39;s width and height.</p>\n\n<p>Return <em>the maximum number of envelopes you can Russian doll (i.e., put one inside the other)</em>.</p>\n\n<p><strong>Note:</strong> You cannot rotate an envelope.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The maximum number of envelopes you can Russian doll is <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> envelopes = [[1,1],[1,1],[1,1]]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>envelopes[i].length == 2</code></li>\n\t<li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/russian-doll-envelopes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n    envelopes.sort(key=lambda x: (x[0], -x[1]))\n    # Same as 300. Longest Increasing Subsequence\n    ans = 0\n    dp = [0] * len(envelopes)\n\n    for _, h in envelopes:\n      l = 0\n      r = ans\n      while l < r:\n        m = (l + r) // 2\n        if dp[m] >= h:\n          r = m\n        else:\n          l = m + 1\n      dp[l] = h\n      if l == ans:\n        ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxEnvelopes(int[][] envelopes) {\n    Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);\n\n    // Same as 300. Longest Increasing Subsequence\n    int ans = 0;\n    int[] dp = new int[envelopes.length];\n\n    for (int[] e : envelopes) {\n      int i = Arrays.binarySearch(dp, 0, ans, e[1]);\n      if (i < 0)\n        i = -(i + 1);\n      dp[i] = e[1];\n      if (i == ans)\n        ++ans;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxEnvelopes(vector<vector<int>>& envelopes) {\n    sort(begin(envelopes), end(envelopes), [](const auto& a, const auto& b) {\n      return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0];\n    });\n\n    // Same as 300. Longest Increasing Subsequence\n    int ans = 0;\n    vector<int> dp(envelopes.size());\n\n    for (const vector<int>& e : envelopes) {\n      int l = 0;\n      int r = ans;\n      while (l < r) {\n        const int m = (l + r) / 2;\n        if (dp[m] >= e[1])\n          r = m;\n        else\n          l = m + 1;\n      }\n      dp[l] = e[1];\n      if (l == ans)\n        ++ans;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/354.html",
    "category": "Algorithms",
    "acceptance_rate": 37.30080663923877,
    "topics": [
      "Array",
      "Binary Search",
      "Dynamic Programming",
      "Sorting"
    ],
    "hints": [],
    "likes": 6218,
    "dislikes": 158,
    "similar_questions": "[{\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Number of Weak Characters in the Game\", \"titleSlug\": \"the-number-of-weak-characters-in-the-game\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Non-decreasing Subarray From Two Arrays\", \"titleSlug\": \"longest-non-decreasing-subarray-from-two-arrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"253.3K\", \"totalSubmission\": \"679.1K\", \"totalAcceptedRaw\": 253313, \"totalSubmissionRaw\": 679112, \"acRate\": \"37.3%\"}",
    "title_pt": "Envelopes Russos",
    "description_pt": "<p>Você recebe um array bidimensional de inteiros <code>envelopes</code> em que <code>envelopes[i] = [w<sub>i</sub>, h<sub>i</sub>]</code> representa a largura e a altura de um envelope.</p>\n\n<p>Um envelope pode caber dentro de outro se, e somente se, tanto a largura quanto a altura de um envelope forem maiores do que a largura e a altura do outro envelope.</p>\n\n<p>Retorne <em>o número máximo de envelopes que você pode empilhar como envelopes russos (isto é, colocar um dentro do outro)</em>.</p>\n\n<p><strong>Nota:</strong> Você não pode rotacionar um envelope.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> envelopes = [[5,4],[6,4],[6,7],[2,3]]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> O número máximo de envelopes que você pode empilhar como envelopes russos é <code>3</code> ([2,3] =&gt; [5,4] =&gt; [6,7]).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> envelopes = [[1,1],[1,1],[1,1]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= envelopes.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>envelopes[i].length == 2</code></li>\n\t<li><code>1 &lt;= w<sub>i</sub>, h<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "355",
    "paidOnly": false,
    "title": "Design Twitter",
    "titleSlug": "design-twitter",
    "url": "https://leetcode.com/problems/design-twitter",
    "description_url": "https://leetcode.com/problems/design-twitter/description/",
    "description": "<p>Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the <code>10</code> most recent tweets in the user&#39;s news feed.</p>\n\n<p>Implement the <code>Twitter</code> class:</p>\n\n<ul>\n\t<li><code>Twitter()</code> Initializes your twitter object.</li>\n\t<li><code>void postTweet(int userId, int tweetId)</code> Composes a new tweet with ID <code>tweetId</code> by the user <code>userId</code>. Each call to this function will be made with a unique <code>tweetId</code>.</li>\n\t<li><code>List&lt;Integer&gt; getNewsFeed(int userId)</code> Retrieves the <code>10</code> most recent tweet IDs in the user&#39;s news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be <strong>ordered from most recent to least recent</strong>.</li>\n\t<li><code>void follow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started following the user with ID <code>followeeId</code>.</li>\n\t<li><code>void unfollow(int followerId, int followeeId)</code> The user with ID <code>followerId</code> started unfollowing the user with ID <code>followeeId</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Twitter&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;follow&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;unfollow&quot;, &quot;getNewsFeed&quot;]\n[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]\n<strong>Output</strong>\n[null, null, [5], null, null, [6, 5], null, [5]]\n\n<strong>Explanation</strong>\nTwitter twitter = new Twitter();\ntwitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).\ntwitter.getNewsFeed(1);  // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5]. return [5]\ntwitter.follow(1, 2);    // User 1 follows user 2.\ntwitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).\ntwitter.getNewsFeed(1);  // User 1&#39;s news feed should return a list with 2 tweet ids -&gt; [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.\ntwitter.unfollow(1, 2);  // User 1 unfollows user 2.\ntwitter.getNewsFeed(1);  // User 1&#39;s news feed should return a list with 1 tweet id -&gt; [5], since user 1 is no longer following user 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= userId, followerId, followeeId &lt;= 500</code></li>\n\t<li><code>0 &lt;= tweetId &lt;= 10<sup>4</sup></code></li>\n\t<li>All the tweets have <strong>unique</strong> IDs.</li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>postTweet</code>, <code>getNewsFeed</code>, <code>follow</code>, and <code>unfollow</code>.</li>\n\t<li>A user cannot follow himself.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-twitter/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Twitter:\n  def __init__(self):\n    self.timer = itertools.count(step=-1)\n    self.tweets = defaultdict(deque)\n    self.followees = defaultdict(set)\n\n  def postTweet(self, userId: int, tweetId: int) -> None:\n    self.tweets[userId].appendleft((next(self.timer), tweetId))\n    if len(self.tweets[userId]) > 10:\n      self.tweets[userId].pop()\n\n  def getNewsFeed(self, userId: int) -> List[int]:\n    tweets = list(heapq.merge(\n        *(self.tweets[followee] for followee in self.followees[userId] | {userId})))\n    return [tweetId for _, tweetId in tweets[:10]]\n\n  def follow(self, followerId: int, followeeId: int) -> None:\n    self.followees[followerId].add(followeeId)\n\n  def unfollow(self, followerId: int, followeeId: int) -> None:\n    self.followees[followerId].discard(followeeId)",
    "solution_code_java": "\t\t\t\n\nclass Tweet {\n  public int id;\n  public int time;\n  public Tweet next = null;\n  public Tweet(int id, int time) {\n    this.id = id;\n    this.time = time;\n  }\n}\n\nclass User {\n  private int id;\n  public Set<Integer> followeeIds = new HashSet<>();\n  public Tweet tweetHead = null;\n\n  public User(int id) {\n    this.id = id;\n    follow(id); // Follow himself\n  }\n\n  public void follow(int followeeId) {\n    followeeIds.add(followeeId);\n  }\n\n  public void unfollow(int followeeId) {\n    followeeIds.remove(followeeId);\n  }\n\n  public void post(int tweetId, int time) {\n    final Tweet oldTweetHead = tweetHead;\n    tweetHead = new Tweet(tweetId, time);\n    tweetHead.next = oldTweetHead;\n  }\n}\n\nclass Twitter {\n  /** Compose a new tweet. */\n  public void postTweet(int userId, int tweetId) {\n    users.putIfAbsent(userId, new User(userId));\n    users.get(userId).post(tweetId, time++);\n  }\n\n  /**\n   * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in\n   * the news feed must be posted by users who the user followed or by the user\n   * herself. Tweets must be ordered from most recent to least recent.\n   */\n  public List<Integer> getNewsFeed(int userId) {\n    if (!users.containsKey(userId))\n      return new ArrayList<>();\n\n    List<Integer> newsFeed = new ArrayList<>();\n    Queue<Tweet> maxHeap = new PriorityQueue<>((a, b) -> b.time - a.time);\n\n    for (final int followeeId : users.get(userId).followeeIds) {\n      Tweet tweetHead = users.get(followeeId).tweetHead;\n      if (tweetHead != null)\n        maxHeap.offer(tweetHead);\n    }\n\n    int count = 0;\n    while (!maxHeap.isEmpty() && count++ < 10) {\n      Tweet tweet = maxHeap.poll();\n      newsFeed.add(tweet.id);\n      if (tweet.next != null)\n        maxHeap.offer(tweet.next);\n    }\n\n    return newsFeed;\n  }\n\n  /**\n   * Follower follows a followee.\n   * If the operation is invalid, it should be a no-op.\n   */\n  public void follow(int followerId, int followeeId) {\n    if (followerId == followeeId)\n      return;\n    users.putIfAbsent(followerId, new User(followerId));\n    users.putIfAbsent(followeeId, new User(followeeId));\n    users.get(followerId).follow(followeeId);\n  }\n\n  /**\n   * Follower unfollows a followee.\n   * If the operation is invalid, it should be a no-op.\n   */\n  public void unfollow(int followerId, int followeeId) {\n    if (followerId == followeeId)\n      return;\n    if (users.containsKey(followerId) && users.containsKey(followeeId))\n      users.get(followerId).unfollow(followeeId);\n  }\n\n  private int time = 0;\n  private Map<Integer, User> users = new HashMap<>(); // {userId: User}\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Tweet {\n  int id;\n  int time;\n  Tweet* next = nullptr;\n  Tweet(int id, int time) : id(id), time(time) {}\n};\n\nstruct User {\n  int id;\n  unordered_set<int> followeeIds;\n  Tweet* tweetHead = nullptr;\n\n  User() {}\n\n  User(int id) : id(id) {\n    follow(id);  // Follow himself\n  }\n\n  void follow(int followeeId) {\n    followeeIds.insert(followeeId);\n  }\n\n  void unfollow(int followeeId) {\n    followeeIds.erase(followeeId);\n  }\n\n  void post(int tweetId, int time) {\n    Tweet* oldTweetHead = tweetHead;\n    tweetHead = new Tweet(tweetId, time);\n    tweetHead->next = oldTweetHead;\n  }\n};\n\nclass Twitter {\n public:\n  /** Compose a new tweet. */\n  void postTweet(int userId, int tweetId) {\n    if (!users.count(userId))\n      users[userId] = User(userId);\n    users[userId].post(tweetId, time++);\n  }\n\n  /**\n   * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in\n   * the news feed must be posted by users who the user followed or by the user\n   * herself. Tweets must be ordered from most recent to least recent.\n   */\n  vector<int> getNewsFeed(int userId) {\n    if (!users.count(userId))\n      return {};\n\n    vector<int> newsFeed;\n\n    auto compare = [](const Tweet* a, const Tweet* b) {\n      return a->time < b->time;\n    };\n    priority_queue<Tweet*, vector<Tweet*>, decltype(compare)> maxHeap(compare);\n\n    for (const int followeeId : users[userId].followeeIds) {\n      Tweet* tweetHead = users[followeeId].tweetHead;\n      if (tweetHead != nullptr)\n        maxHeap.push(tweetHead);\n    }\n\n    int count = 0;\n    while (!maxHeap.empty() && count++ < 10) {\n      Tweet* tweet = maxHeap.top();\n      maxHeap.pop();\n      newsFeed.push_back(tweet->id);\n      if (tweet->next)\n        maxHeap.push(tweet->next);\n    }\n\n    return newsFeed;\n  }\n\n  /**\n   * Follower follows a followee.\n   * If the operation is invalid, it should be a no-op.\n   */\n  void follow(int followerId, int followeeId) {\n    if (followerId == followeeId)\n      return;\n    if (!users.count(followerId))\n      users[followerId] = User(followerId);\n    if (!users.count(followeeId))\n      users[followeeId] = User(followeeId);\n    users[followerId].follow(followeeId);\n  }\n\n  /**\n   * Follower unfollows a followee.\n   * If the operation is invalid, it should be a no-op.\n   */\n  void unfollow(int followerId, int followeeId) {\n    if (followerId == followeeId)\n      return;\n    if (users.count(followerId) && users.count(followeeId))\n      users[followerId].unfollow(followeeId);\n  }\n\n private:\n  int time = 0;\n  unordered_map<int, User> users;  // {userId: User}\n};",
    "solution_code_url": "https://leetcodehelp.github.io/355.html",
    "category": "Algorithms",
    "acceptance_rate": 42.39444562512655,
    "topics": [
      "Hash Table",
      "Linked List",
      "Design",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 4255,
    "dislikes": 599,
    "similar_questions": "[{\"title\": \"Design a File Sharing System\", \"titleSlug\": \"design-a-file-sharing-system\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"253.3K\", \"totalSubmission\": \"597.6K\", \"totalAcceptedRaw\": 253341, \"totalSubmissionRaw\": 597581, \"acRate\": \"42.4%\"}",
    "title_pt": "Projetar o Twitter",
    "description_pt": "<p>Projete uma versão simplificada do Twitter em que os usuários podem publicar tweets, seguir/deixar de seguir outro usuário e ser capazes de ver os <code>10</code> tweets mais recentes no feed de notícias do usuário.</p>\n\n<p>Implemente a classe <code>Twitter</code>:</p>\n\n<ul>\n\t<li><code>Twitter()</code> Inicializa seu objeto twitter.</li>\n\t<li><code>void postTweet(int userId, int tweetId)</code> Compoõe um novo tweet com ID <code>tweetId</code> pelo usuário <code>userId</code>. Cada chamada a esta função será feita com um <code>tweetId</code> único.</li>\n\t<li><code>List&lt;Integer&gt; getNewsFeed(int userId)</code> Recupera os <code>10</code> IDs de tweet mais recentes no feed de notícias do usuário. Cada item no feed de notícias deve ter sido publicado por usuários que o usuário segue ou pelo próprio usuário. Os tweets devem ser <strong>ordenados do mais recente para o menos recente</strong>.</li>\n\t<li><code>void follow(int followerId, int followeeId)</code> O usuário com ID <code>followerId</code> começou a seguir o usuário com ID <code>followeeId</code>.</li>\n\t<li><code>void unfollow(int followerId, int followeeId)</code> O usuário com ID <code>followerId</code> começou a deixar de seguir o usuário com ID <code>followeeId</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Twitter&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;follow&quot;, &quot;postTweet&quot;, &quot;getNewsFeed&quot;, &quot;unfollow&quot;, &quot;getNewsFeed&quot;]\n[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]\n<strong>Saída</strong>\n[null, null, [5], null, null, [6, 5], null, [5]]\n\n<strong>Explicação</strong>\nTwitter twitter = new Twitter();\ntwitter.postTweet(1, 5); // O usuário 1 publica um novo tweet (id = 5).\ntwitter.getNewsFeed(1);  // O feed de notícias do usuário 1 deve retornar uma lista com 1 id de tweet -&gt; [5]. return [5]\ntwitter.follow(1, 2);    // O usuário 1 segue o usuário 2.\ntwitter.postTweet(2, 6); // O usuário 2 publica um novo tweet (id = 6).\ntwitter.getNewsFeed(1);  // O feed de notícias do usuário 1 deve retornar uma lista com 2 ids de tweet -&gt; [6, 5]. O id do tweet 6 deve preceder o id do tweet 5 porque foi publicado depois do id do tweet 5.\ntwitter.unfollow(1, 2);  // O usuário 1 deixa de seguir o usuário 2.\ntwitter.getNewsFeed(1);  // O feed de notícias do usuário 1 deve retornar uma lista com 1 id de tweet -&gt; [5], já que o usuário 1 não está mais seguindo o usuário 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= userId, followerId, followeeId &lt;= 500</code></li>\n\t<li><code>0 &lt;= tweetId &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os tweets têm IDs <strong>únicos</strong>.</li>\n\t<li>No máximo <code>3 * 10<sup>4</sup></code> chamadas serão feitas a <code>postTweet</code>, <code>getNewsFeed</code>, <code>follow</code> e <code>unfollow</code>.</li>\n\t<li>Um usuário não pode seguir a si mesmo.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "357",
    "paidOnly": false,
    "title": "Count Numbers with Unique Digits",
    "titleSlug": "count-numbers-with-unique-digits",
    "url": "https://leetcode.com/problems/count-numbers-with-unique-digits",
    "description_url": "https://leetcode.com/problems/count-numbers-with-unique-digits/description/",
    "description": "<p>Given an integer <code>n</code>, return the count of all numbers with unique digits, <code>x</code>, where <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 91\n<strong>Explanation:</strong> The answer should be the total numbers in the range of 0 &le; x &lt; 100, excluding 11,22,33,44,55,66,77,88,99\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 0\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 8</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-numbers-with-unique-digits/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countNumbersWithUniqueDigits(self, n: int) -> int:\n    if n == 0:\n      return 1\n\n    ans = 10\n    uniqueDigits = 9\n    availableNum = 9\n\n    while n > 1 and availableNum > 0:\n      uniqueDigits *= availableNum\n      ans += uniqueDigits\n      n -= 1\n      availableNum -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countNumbersWithUniqueDigits(int n) {\n    if (n == 0)\n      return 1;\n\n    int ans = 10;\n    int uniqueDigits = 9;\n\n    for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) {\n      uniqueDigits *= availableNum;\n      ans += uniqueDigits;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countNumbersWithUniqueDigits(int n) {\n    if (n == 0)\n      return 1;\n\n    int ans = 10;\n    int uniqueDigits = 9;\n\n    for (int availableNum = 9; n > 1 && availableNum > 0; --n, --availableNum) {\n      uniqueDigits *= availableNum;\n      ans += uniqueDigits;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/357.html",
    "category": null,
    "acceptance_rate": null,
    "topics": null,
    "hints": null,
    "likes": null,
    "dislikes": null,
    "similar_questions": null,
    "stats": null,
    "title_pt": "Contar Números com Dígitos Únicos",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne a contagem de todos os números com dígitos únicos, <code>x</code>, em que <code>0 &lt;= x &lt; 10<sup>n</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 91\n<strong>Explicação:</strong> A resposta deve ser o total de números no intervalo de 0 &le; x &lt; 100, excluindo 11,22,33,44,55,66,77,88,99\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 0\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 8</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "363",
    "paidOnly": false,
    "title": "Max Sum of Rectangle No Larger Than K",
    "titleSlug": "max-sum-of-rectangle-no-larger-than-k",
    "url": "https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k",
    "description_url": "https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/",
    "description": "<p>Given an <code>m x n</code> matrix <code>matrix</code> and an integer <code>k</code>, return <em>the max sum of a rectangle in the matrix such that its sum is no larger than</em> <code>k</code>.</p>\n\n<p>It is <strong>guaranteed</strong> that there will be a rectangle with a sum no larger than <code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg\" style=\"width: 255px; height: 176px;\" />\n<pre>\n<strong>Input:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[2,2,-1]], k = 3\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if the number of rows is much larger than the number of columns?</p>\n",
    "solution_url": "https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxSumSubmatrix(int[][] matrix, int k) {\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    int ans = Integer.MIN_VALUE;\n\n    for (int baseCol = 0; baseCol < n; ++baseCol) {\n      // sums[i] := sum(matrix[i][baseCol..j])\n      int[] sums = new int[m];\n      for (int j = baseCol; j < n; ++j) {\n        for (int i = 0; i < m; ++i)\n          sums[i] += matrix[i][j];\n        // Find the max subarray no more than k\n        TreeSet<Integer> accumulate = new TreeSet<>(Arrays.asList(0));\n        int prefix = 0;\n        for (final int sum : sums) {\n          prefix += sum;\n          final Integer lo = accumulate.ceiling(prefix - k);\n          if (lo != null)\n            ans = Math.max(ans, prefix - lo);\n          accumulate.add(prefix);\n        }\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    int ans = INT_MIN;\n\n    for (int baseCol = 0; baseCol < n; ++baseCol) {\n      // sums[i] := sum(matrix[i][baseCol..j])\n      vector<int> sums(m, 0);\n      for (int j = baseCol; j < n; ++j) {\n        for (int i = 0; i < m; ++i)\n          sums[i] += matrix[i][j];\n        // Find the max subarray no more than k\n        set<int> accumulate{0};\n        int prefix = 0;\n        for (const int sum : sums) {\n          prefix += sum;\n          const auto it = accumulate.lower_bound(prefix - k);\n          if (it != cend(accumulate))\n            ans = max(ans, prefix - *it);\n          accumulate.insert(prefix);\n        }\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/363.html",
    "category": "Algorithms",
    "acceptance_rate": 44.61745945692696,
    "topics": [
      "Array",
      "Binary Search",
      "Matrix",
      "Prefix Sum",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 3503,
    "dislikes": 175,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"133.3K\", \"totalSubmission\": \"298.8K\", \"totalAcceptedRaw\": 133325, \"totalSubmissionRaw\": 298818, \"acRate\": \"44.6%\"}",
    "title_pt": "Máxima Soma de um Retângulo Não Maior que K",
    "description_pt": "<p>Dada uma matriz <code>m x n</code> <code>matrix</code> e um inteiro <code>k</code>, retorne <em>a soma máxima de um retângulo na matriz tal que sua soma não seja maior que</em> <code>k</code>.</p>\n\n<p>É <strong>garantido</strong> que existirá um retângulo com soma não maior que <code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/18/sum-grid.jpg\" style=\"width: 255px; height: 176px;\" />\n<pre>\n<strong>Entrada:</strong> matrix = [[1,0,1],[0,-2,3]], k = 2\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Porque a soma do retângulo azul [[0, 1], [-2, 3]] é 2, e 2 é o maior número não maior que k (k = 2).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[2,2,-1]], k = 3\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == matrix.length</code></li>\n\t<li><code>n == matrix[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> E se o número de linhas for muito maior que o número de colunas?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "365",
    "paidOnly": false,
    "title": "Water and Jug Problem",
    "titleSlug": "water-and-jug-problem",
    "url": "https://leetcode.com/problems/water-and-jug-problem",
    "description_url": "https://leetcode.com/problems/water-and-jug-problem/description/",
    "description": "<p>You are given two jugs with capacities <code>x</code> liters and <code>y</code> liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach <code>target</code> using the following operations:</p>\n\n<ul>\n\t<li>Fill either jug completely with water.</li>\n\t<li>Completely empty either jug.</li>\n\t<li>Pour water from one jug into another until the receiving jug is full, or the transferring jug is empty.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Input: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 3, y = 5, target = 4 </span></p>\n\n<p><strong>Output: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> true </span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Follow these steps to reach a total of 4 liters:</p>\n\n<ol>\n\t<li>Fill the 5-liter jug (0, 5).</li>\n\t<li>Pour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).</li>\n\t<li>Empty the 3-liter jug (0, 2).</li>\n\t<li>Transfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).</li>\n\t<li>Fill the 5-liter jug again (2, 5).</li>\n\t<li>Pour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).</li>\n\t<li>Empty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).</li>\n</ol>\n\n<p>Reference: The <a href=\"https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01\" target=\"_blank\">Die Hard</a> example.</p>\n</div>\n\n<p><strong class=\"example\">Example 2: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Input: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 2, y = 6, target = 5 </span></p>\n\n<p><strong>Output: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> false </span></p>\n</div>\n\n<p><strong class=\"example\">Example 3: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Input: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 1, y = 2, target = 3 </span></p>\n\n<p><strong>Output: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> true </span></p>\n\n<p><strong>Explanation:</strong> Fill both jugs. The total amount of water in both jugs is equal to 3 now.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/water-and-jug-problem/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:\n    return targetCapacity == 0 or \\\n        jug1Capacity + jug2Capacity >= targetCapacity and \\\n        targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n    return targetCapacity == 0 || jug1Capacity + jug2Capacity >= targetCapacity &&\n                                      targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0;\n  }\n\n  private int gcd(int a, int b) {\n    return b == 0 ? a : gcd(b, a % b);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {\n    return targetCapacity == 0 ||\n           jug1Capacity + jug2Capacity >= targetCapacity &&\n               targetCapacity % __gcd(jug1Capacity, jug2Capacity) == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/365.html",
    "category": "Algorithms",
    "acceptance_rate": 42.917227573603775,
    "topics": [
      "Math",
      "Depth-First Search",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 1587,
    "dislikes": 1499,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"123.1K\", \"totalSubmission\": \"286.7K\", \"totalAcceptedRaw\": 123060, \"totalSubmissionRaw\": 286738, \"acRate\": \"42.9%\"}",
    "title_pt": "Problema da Água e dos Jarros",
    "description_pt": "<p>Você recebe dois jarros com capacidades de <code>x</code> litros e <code>y</code> litros. Você tem um abastecimento infinito de água. Retorne se a quantidade total de água em ambos os jarros pode atingir <code>target</code> usando as seguintes operações:</p>\n\n<ul>\n\t<li>Encher completamente qualquer um dos jarros com água.</li>\n\t<li>Esvaziar completamente qualquer um dos jarros.</li>\n\t<li>Despejar água de um jarro em outro até que o jarro que recebe esteja cheio, ou até que o jarro que transfere esteja vazio.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Entrada: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 3, y = 5, target = 4 </span></p>\n\n<p><strong>Saída: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> true </span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Siga estes passos para atingir um total de 4 litros:</p>\n\n<ol>\n\t<li>Encha o jarro de 5 litros (0, 5).</li>\n\t<li>Despeje do jarro de 5 litros para o jarro de 3 litros, deixando 2 litros (3, 2).</li>\n\t<li>Esvazie o jarro de 3 litros (0, 2).</li>\n\t<li>Transfira os 2 litros do jarro de 5 litros para o jarro de 3 litros (2, 0).</li>\n\t<li>Encha o jarro de 5 litros novamente (2, 5).</li>\n\t<li>Despeje do jarro de 5 litros para o jarro de 3 litros até que o jarro de 3 litros esteja cheio. Isso deixa 4 litros no jarro de 5 litros (3, 4).</li>\n\t<li>Esvazie o jarro de 3 litros. Agora, você tem exatamente 4 litros no jarro de 5 litros (0, 4).</li>\n</ol>\n\n<p>Referência: o exemplo de <a href=\"https://www.youtube.com/watch?v=BVtQNK_ZUJg&amp;ab_channel=notnek01\" target=\"_blank\">Die Hard</a>.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Entrada: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 2, y = 6, target = 5 </span></p>\n\n<p><strong>Saída: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> false </span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3: </strong></p>\n\n<div class=\"example-block\" style=\"border-color: var(--border-tertiary); border-left-width: 2px; color: var(--text-secondary); font-size: .875rem; margin-bottom: 1rem; margin-top: 1rem; overflow: visible; padding-left: 1rem;\">\n<p><strong>Entrada: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> x = 1, y = 2, target = 3 </span></p>\n\n<p><strong>Saída: </strong> <span class=\"example-io\" style=\"font-family: Menlo,sans-serif; font-size: 0.85rem;\"> true </span></p>\n\n<p><strong>Explicação:</strong> Encha ambos os jarros. A quantidade total de água em ambos os jarros é igual a 3 agora.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= x, y, target&nbsp;&lt;= 10<sup>3</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "367",
    "paidOnly": false,
    "title": "Valid Perfect Square",
    "titleSlug": "valid-perfect-square",
    "url": "https://leetcode.com/problems/valid-perfect-square",
    "description_url": "https://leetcode.com/problems/valid-perfect-square/description/",
    "description": "<p>Given a positive integer num, return <code>true</code> <em>if</em> <code>num</code> <em>is a perfect square or</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>A <strong>perfect square</strong> is an integer that is the square of an integer. In other words, it is the product of some integer with itself.</p>\n\n<p>You must not use any built-in library function, such as <code>sqrt</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 16\n<strong>Output:</strong> true\n<strong>Explanation:</strong> We return true because 4 * 4 = 16 and 4 is an integer.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 14\n<strong>Output:</strong> false\n<strong>Explanation:</strong> We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-perfect-square/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isPerfectSquare(self, num: int) -> bool:\n    l = 1\n    r = num\n\n    while l < r:\n      m = (l + r) // 2\n      if m >= num / m:\n        r = m\n      else:\n        l = m + 1\n\n    return l * l == num",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isPerfectSquare(int num) {\n    long l = 1;\n    long r = num;\n\n    while (l < r) {\n      final long m = (l + r) / 2;\n      if (m >= num / m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l * l == num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPerfectSquare(int num) {\n    long l = 1;\n    long r = num;\n\n    while (l < r) {\n      const long m = (l + r) / 2;\n      if (m >= num / m)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l * l == num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/367.html",
    "category": "Algorithms",
    "acceptance_rate": 44.14319958154308,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [],
    "likes": 4435,
    "dislikes": 323,
    "similar_questions": "[{\"title\": \"Sqrt(x)\", \"titleSlug\": \"sqrtx\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Square Numbers\", \"titleSlug\": \"sum-of-square-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"760.4K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 760374, \"totalSubmissionRaw\": 1722517, \"acRate\": \"44.1%\"}",
    "title_pt": "Verificar Quadrado Perfeito",
    "description_pt": "<p>Dado um inteiro positivo num, retorne <code>true</code> <em>se</em> <code>num</code> <em>for um quadrado perfeito ou</em> <code>false</code> <em>caso contrário</em>.</p>\n\n<p>Um <strong>quadrado perfeito</strong> é um inteiro que é o quadrado de um inteiro. Em outras palavras, ele é o produto de algum inteiro por ele mesmo.</p>\n\n<p>Você não deve usar nenhuma função de biblioteca встро?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "368",
    "paidOnly": false,
    "title": "Largest Divisible Subset",
    "titleSlug": "largest-divisible-subset",
    "url": "https://leetcode.com/problems/largest-divisible-subset",
    "description_url": "https://leetcode.com/problems/largest-divisible-subset/description/",
    "description": "<p>Given a set of <strong>distinct</strong> positive integers <code>nums</code>, return the largest subset <code>answer</code> such that every pair <code>(answer[i], answer[j])</code> of elements in this subset satisfies:</p>\n\n<ul>\n\t<li><code>answer[i] % answer[j] == 0</code>, or</li>\n\t<li><code>answer[j] % answer[i] == 0</code></li>\n</ul>\n\n<p>If there are multiple solutions, return any of them.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> [1,2]\n<strong>Explanation:</strong> [1,3] is also accepted.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,4,8]\n<strong>Output:</strong> [1,2,4,8]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li>\n\t<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/largest-divisible-subset/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n    n = len(nums)\n    ans = []\n    count = [1] * n\n    prevIndex = [-1] * n\n    maxCount = 0\n    index = -1\n\n    nums.sort()\n\n    for i, num in enumerate(nums):\n      for j in reversed(range(i)):\n        if num % nums[j] == 0 and count[i] < count[j] + 1:\n          count[i] = count[j] + 1\n          prevIndex[i] = j\n      if count[i] > maxCount:\n        maxCount = count[i]\n        index = i\n\n    while index != -1:\n      ans.append(nums[index])\n      index = prevIndex[index]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> largestDivisibleSubset(int[] nums) {\n    final int n = nums.length;\n    List<Integer> ans = new ArrayList<>();\n    // sizeEndsAt[i] := largest size ends at nums[i]\n    int[] sizeEndsAt = new int[n];\n    // prevIndex[i] := the best index s.t.\n    // 1. nums[i] % nums[prevIndex[i]] == 0 and\n    // 2. can increase the size of the subset\n    int[] prevIndex = new int[n];\n    int maxSize = 0; // Max size of the subset\n    int index = -1;  // Track the best ending index\n\n    Arrays.fill(sizeEndsAt, 1);\n    Arrays.fill(prevIndex, -1);\n    Arrays.sort(nums);\n\n    // Fix max ending num in the subset first\n    for (int i = 0; i < n; ++i) {\n      for (int j = i - 1; j >= 0; --j)\n        if (nums[i] % nums[j] == 0 && sizeEndsAt[i] < sizeEndsAt[j] + 1) {\n          sizeEndsAt[i] = sizeEndsAt[j] + 1;\n          prevIndex[i] = j;\n        }\n      // Find a new subset that has a bigger size\n      if (maxSize < sizeEndsAt[i]) {\n        maxSize = sizeEndsAt[i];\n        index = i; // Update the best ending index\n      }\n    }\n\n    // Loop from back to front\n    while (index != -1) {\n      ans.add(nums[index]);\n      index = prevIndex[index];\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> largestDivisibleSubset(vector<int>& nums) {\n    const int n = nums.size();\n    vector<int> ans;\n    // sizeEndsAt[i] := largest size ends at nums[i]\n    vector<int> sizeEndsAt(n, 1);\n    // prevIndex[i] := the best index s.t.\n    // 1. nums[i] % nums[prevIndex[i]] == 0 and\n    // 2. can increase the size of the subset\n    vector<int> prevIndex(n, -1);\n    int maxSize = 0;  // Max size of the subset\n    int index = -1;   // Track the best ending index\n\n    sort(begin(nums), end(nums));\n\n    // Fix max ending num in the subset first\n    for (int i = 0; i < n; ++i) {\n      for (int j = i - 1; j >= 0; --j)\n        if (nums[i] % nums[j] == 0 && sizeEndsAt[i] < sizeEndsAt[j] + 1) {\n          sizeEndsAt[i] = sizeEndsAt[j] + 1;\n          prevIndex[i] = j;\n        }\n      // Find a new subset that has a bigger size\n      if (maxSize < sizeEndsAt[i]) {\n        maxSize = sizeEndsAt[i];\n        index = i;  // Update the best ending index\n      }\n    }\n\n    // Loop from back to front\n    while (index != -1) {\n      ans.push_back(nums[index]);\n      index = prevIndex[index];\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/368.html",
    "category": "Algorithms",
    "acceptance_rate": 48.76322516568897,
    "topics": [
      "Array",
      "Math",
      "Dynamic Programming",
      "Sorting"
    ],
    "hints": [],
    "likes": 6574,
    "dislikes": 320,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"435.5K\", \"totalSubmission\": \"893.1K\", \"totalAcceptedRaw\": 435499, \"totalSubmissionRaw\": 893089, \"acRate\": \"48.8%\"}",
    "title_pt": "Maior Subconjunto Divisível",
    "description_pt": "<p>Dado um conjunto de inteiros positivos <strong>distintos</strong> <code>nums</code>, retorne o maior subconjunto <code>answer</code> tal que todo par <code>(answer[i], answer[j])</code> de elementos neste subconjunto satisfaz:</p>\n\n<ul>\n\t<li><code>answer[i] % answer[j] == 0</code>, ou</li>\n\t<li><code>answer[j] % answer[i] == 0</code></li>\n</ul>\n\n<p>Se houver múltiplas soluções, retorne qualquer uma delas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> [1,2]\n<strong>Explicação:</strong> [1,3] também é aceito.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,4,8]\n<strong>Saída:</strong> [1,2,4,8]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>9</sup></code></li>\n\t<li>Todos os inteiros em <code>nums</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "371",
    "paidOnly": false,
    "title": "Sum of Two Integers",
    "titleSlug": "sum-of-two-integers",
    "url": "https://leetcode.com/problems/sum-of-two-integers",
    "description_url": "https://leetcode.com/problems/sum-of-two-integers/description/",
    "description": "<p>Given two integers <code>a</code> and <code>b</code>, return <em>the sum of the two integers without using the operators</em> <code>+</code> <em>and</em> <code>-</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> a = 1, b = 2\n<strong>Output:</strong> 3\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> a = 2, b = 3\n<strong>Output:</strong> 5\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-1000 &lt;= a, b &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sum-of-two-integers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getSum(self, a: int, b: int) -> int:\n    mask = 0xFFFFFFFF\n    kMax = 2000\n\n    while b:\n      a, b = (a ^ b) & mask, ((a & b) << 1) & mask\n\n    return a if a < kMax else ~(a ^ mask)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int getSum(int a, int b) {\n    while (b != 0) {           // Still have carry bits\n      final int carry = a & b; // Record carry bits\n      a ^= b;                  // ^ works like + w/o handling carry bits\n      b = carry << 1;\n    }\n    return a;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int getSum(unsigned a, unsigned b) {\n    while (b) {                      // Still have carry bits\n      const unsigned carry = a & b;  // Record carry bits\n      a ^= b;                        // ^ works like + w/o handling carry bits\n      b = carry << 1;\n    }\n    return a;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/371.html",
    "category": "Algorithms",
    "acceptance_rate": 53.503235497082514,
    "topics": [
      "Math",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 4449,
    "dislikes": 5700,
    "similar_questions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"583.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 583811, \"totalSubmissionRaw\": 1091172, \"acRate\": \"53.5%\"}",
    "title_pt": "Soma de Dois Inteiros",
    "description_pt": "<p>Dados dois inteiros <code>a</code> e <code>b</code>, retorne <em>a soma dos dois inteiros sem usar os operadores</em> <code>+</code> <em>e</em> <code>-</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> a = 1, b = 2\n<strong>Saída:</strong> 3\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> a = 2, b = 3\n<strong>Saída:</strong> 5\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-1000 &lt;= a, b &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "372",
    "paidOnly": false,
    "title": "Super Pow",
    "titleSlug": "super-pow",
    "url": "https://leetcode.com/problems/super-pow",
    "description_url": "https://leetcode.com/problems/super-pow/description/",
    "description": "<p>Your task is to calculate <code>a<sup>b</sup></code> mod <code>1337</code> where <code>a</code> is a positive integer and <code>b</code> is an extremely large positive integer given in the form of an array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = 2, b = [3]\n<strong>Output:</strong> 8\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = 2, b = [1,0]\n<strong>Output:</strong> 1024\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = 1, b = [4,3,3,8,5,2]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= b.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= b[i] &lt;= 9</code></li>\n\t<li><code>b</code> does not contain leading zeros.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/super-pow/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def superPow(self, a: int, b: List[int]) -> int:\n    def powMod(x: int, y: int) -> int:\n      pow = 1\n      for _ in range(y):\n        pow = (pow * x) % k\n      return pow\n\n    k = 1337\n    ans = 1\n\n    for i in b:\n      ans = powMod(ans, 10) * powMod(a, i) % k\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int superPow(int a, int[] b) {\n    int ans = 1;\n\n    a %= k;\n    for (final int i : b)\n      ans = powMod(ans, 10) * powMod(a, i) % k;\n\n    return ans;\n  }\n\n  private final int k = 1337;\n\n  private int powMod(int x, int y) {\n    int pow = 1;\n    while (y-- > 0)\n      pow = (pow * x) % k;\n    return pow;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int superPow(int a, vector<int>& b) {\n    constexpr int k = 1337;\n    int ans = 1;\n\n    auto powMod = [&](int x, int y) {  // X^y % k\n      int pow = 1;\n      while (y--)\n        pow = (pow * x) % k;\n      return pow;\n    };\n\n    a %= k;\n    for (const int i : b)\n      ans = powMod(ans, 10) * powMod(a, i) % k;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/372.html",
    "category": "Algorithms",
    "acceptance_rate": 35.4262617887864,
    "topics": [
      "Math",
      "Divide and Conquer"
    ],
    "hints": [],
    "likes": 1007,
    "dislikes": 1462,
    "similar_questions": "[{\"title\": \"Pow(x, n)\", \"titleSlug\": \"powx-n\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"85.5K\", \"totalSubmission\": \"241.2K\", \"totalAcceptedRaw\": 85457, \"totalSubmissionRaw\": 241222, \"acRate\": \"35.4%\"}",
    "title_pt": "Super Potência",
    "description_pt": "<p>Sua tarefa é calcular <code>a<sup>b</sup></code> mod <code>1337</code> onde <code>a</code> é um inteiro positivo e <code>b</code> é um inteiro positivo extremamente grande dado na forma de um array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = 2, b = [3]\n<strong>Saída:</strong> 8\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = 2, b = [1,0]\n<strong>Saída:</strong> 1024\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = 1, b = [4,3,3,8,5,2]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= b.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= b[i] &lt;= 9</code></li>\n\t<li><code>b</code> não contém zeros à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "373",
    "paidOnly": false,
    "title": "Find K Pairs with Smallest Sums",
    "titleSlug": "find-k-pairs-with-smallest-sums",
    "url": "https://leetcode.com/problems/find-k-pairs-with-smallest-sums",
    "description_url": "https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/",
    "description": "<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> sorted in <strong>non-decreasing&nbsp;order</strong> and an integer <code>k</code>.</p>\n\n<p>Define a pair <code>(u, v)</code> which consists of one element from the first array and one element from the second array.</p>\n\n<p>Return <em>the</em> <code>k</code> <em>pairs</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>with the smallest sums</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3\n<strong>Output:</strong> [[1,2],[1,4],[1,6]]\n<strong>Explanation:</strong> The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2\n<strong>Output:</strong> [[1,1],[1,1]]\n<strong>Explanation:</strong> The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>nums1</code> and <code>nums2</code> both are sorted in <strong>non-decreasing order</strong>.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n\t<li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-k-pairs-with-smallest-sums/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given two integer arrays `nums1` and `nums2` sorted in ascending order and an integer `k`.\n\nOur task is to return the `k` pairs ($u_1$, $v_1$), ($u_2$, $v_2$), ..., ($u_k$, $v_k$) with the smallest sums where the first element in the pair is from `nums1` and second elements is from `nums2`.\n\n---\n\n### Approach: Using Heap\n\n#### Intuition\n\nThe brute force approach to solving this problem is to compute the sum of all the pairs, sort the list of sums, and select the first 'k' elements from it. If the size of `nums1` is `m` and size of `nums2` is `n`, there will be `m * n` pairs in total that will be formed. As a result, it will take $O(m \\cdot n)$ time to calculate the sum of all the pairs and $O(m \\cdot n \\cdot \\log(m \\cdot n))$ time to sort the list of sums. This will result in the time limit being exceeded (TLE).\n\nWe can see from the problem description that both arrays are sorted. Let us try to make use of it.\n\nBecause the arrays are sorted, the pair with the smallest sum is undoubtedly the one formed by selecting the first element from both arrays, i.e., pair with indices `(0, 0)` where the first element is index of `nums1` and second is index of `nums2`. As a result, we add `(nums1[0], nums2[0])` to our answer list.\n\nWhat about the next pair whose sum is just greater than (or equal to) the sum of the previous pair?\n\nThe next pair with a sum that is just greater than (or equal to) the sum of the previous pair would be formed by selecting either the first element of `nums1` and the second element of `nums2`, `(0, 1)`, or the second element of `nums1` and the first element of `nums2`, `(1, 0)`, whichever has smaller sum. We only need to look at these two pairs because the sum of all the other pairs will be greater than this pair.\n\nAssume we chose `(0, 1)` as our second pair. The next smallest pair whose sum is greater than (or equal to) the sum of the second pair is either the previous iteration's leftover pair `(1, 0)`, or one of the pairs formed by taking the current pair `(0, 1)` and taking a new element from either array, so either `(1, 1)` or `(0, 2)` (notice that this is the same option we had after taking the first pair `(0, 0)`).\n\n> At each step, we chose the minimum sum pair from the remaining leftover pairs and the next two new pairs. The answer will not be present outside of these pairs being considered only because the arrays are sorted. We repeat this process until we get `k` pairs.\n\nA **heap** is a useful data structure when it is necessary to repeatedly remove the object with the lowest (or highest) priority, or when insertions need to be interspersed with removals of the objects.\n\nWe will use a min heap to solve the problem because we need to iterate from the lowest sum of a pair to pairs with higher sums. The sums of pairs will be stored in the heap, and the data structure will keep the sums in sorted order. We must store the information of the indices of `nums1` and `nums2` that lead to the formation of a particular sum in the heap in order to return the pair of integers.\n\nIn the heap, we would store a triplet of integers: the pair's sum, the first element's index in `nums1`, and the second element's index in `nums2`. We start with an empty list `ans` and push all of the `k` pairs that make up the answer one-by-one.\n\nWe begin by inserting `nums1[0] + nums2[0], 0, 0` into the heap because the sum of the first element of both arrays is guaranteed to be the smallest.\n\nTo obtain the minimum sum of a pair among all the pairs under consideration, the top of the heap is popped out. We save the triplet in `val`, `i` and `j`. We put the pair `(nums1[i], nums2[j])` in `ans`.\n\nWe then push the two new pairs as discussed in the heap. We push `nums1[i + 1] + nums2[j], i + 1, j` and `nums1[i] + nums2[j + 1], i, j + 1`.\n\nWe do this until we get `k` pairs or heap becomes empty which would happen if we have covered all the `m * n` pairs and `k > m * n`, where `m` is size of `nums1` and `n` is size of `nums2`.\n\nThe only thing to keep in mind here is that when we push the new pairs, there may be repeating states. For `(0, 0)` for example, we will push `(1, 0)` and `(0, 1)`. Then on both `(1, 0)` and `(0, 1)`, we would push `(1, 1)`. As you can see, we pushed the pair `i = 1, j = 1` twice.\n\nTo avoid this, we can create a hash set called `visited` and store the pairs that have already been pushed into the heap in order to avoid pushing them again.\n\nHere is a visual representation of how this approach works for the first example given in the problem description:\n\n!?!../Documents/373/373-slides.json:601,301!?!\n\nThis method is very similar to the Dijkstra algorithm in that we find the shortest distance between any two nodes. To find the edge with the smallest weight, we heap all of the edge weights. Then we move on to the next node (using minimum weight edge selected). We add all of the edge weights for the edges connected with the node back to the heap from the current node and choose the edge with the lowest weight from the available edges. We use the edge to move to another unvisited node and continue popping nodes and adding edge weights to the heap until all of the nodes are covered.\n\n#### Algorithm\n\n1. Create two integer variables `m` and `n`. Initialize them to size of `nums1` and `nums2` respectively.\n2. Create a list `ans` to store the pairs with smallest sums that are to be returned as the answer.\n3. Create a hash set `visited` to keep track of pairs that are seen. Please note that we used `ordered_set` in `C++` in place of `unordered_set` because the `unordered_set` uses `hash` template to compute hashes for its entries and there is no `hash` specialization for pairs. Either we define the `hash` function of pairs or use `ordered_set` which is a little expensive as it adds `log` factor. We are using `ordered_set` here.\n4. Initialize a min heap `minHeap` that takes a triplet of integers: the sum of the pair, the index in `nums1` of the first element of the pair, and the index in `nums2` of the second element of the pair.\n5. Push the first element from the both the arrays in `minHeap`, i.e., we push `nums1[0] + nums2[0], 0, 0`. We also insert pair `(0, 0)` in `visited`.\n6. Iterate till we get `k` pairs and `minHeap` is not empty:\n    - Pop the top of `minHeap` and set `i  = top[1]` and `j = top[2]`.\n    - Push pair `(nums1[i], nums2[j])` in `ans`.\n    - If `i + 1 < m` and pair `(i + 1, j)` is not in `visited`, we push a new pair `nums1[i + 1] + nums2[j], i + 1, j` into the heap.\n    - If `j + 1 < n` and pair `(i, j + 1)` is not in `visited`, we push a new pair `nums1[i] + nums2[j + 1], i, j + 1` into the heap.\n7. Return `ans`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/QsWvjcrS/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"QsWvjcrS\"></iframe>\n\n#### Complexity Analysis\n\nHere, $m$ is the size of `nums1` and $n$ is the size of `nums2`.\n\n* Time complexity: $O(\\min(k \\cdot \\log k, m \\cdot n \\cdot \\log (m \\cdot n)))$\n\n    - We iterate $O(\\min(k, m \\cdot n))$ times to get the required number of pairs.\n    - The `visited` set and `heap` both can grow up to a size of $O(\\min(k, m \\cdot n))$ because at each iteration we are inserting at most two pairs and popping one pair. Insertions into a min-heap take an additional $\\log$ factor. So, to insert $O(\\min(k, m \\cdot n))$ elements into `minHeap`, we need $O(\\min(k \\cdot \\log k, m \\cdot n \\cdot \\log (m \\cdot n))$ time.\n    - The `visited` set takes on an average constant time and hence will take $O(\\min(k, m \\cdot n))$ time in major languages like Java and Python except in C++ where it would also take $O(\\min(k \\cdot \\log k, m \\cdot n \\cdot \\log (m \\cdot n)))$ because we used `ordered_set` that keeps the values in sorted order.\n\n* Space complexity: $O(\\min(k, m \\cdot n))$\n\n    - The `visited` set and `heap` can both grow up to a size of $O(\\min(k, m \\cdot n))$ because at each iteration we are inserting at most two pairs and popping one pair.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int i;\n  public int j;\n  public int sum; // nums1[i] + nums2[j]\n  public T(int i, int j, int sum) {\n    this.i = i;\n    this.j = j;\n    this.sum = sum;\n  }\n}\n\nclass Solution {\n  public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {\n    List<List<Integer>> ans = new ArrayList<>();\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.sum - b.sum);\n\n    for (int i = 0; i < k && i < nums1.length; ++i)\n      minHeap.offer(new T(i, 0, nums1[i] + nums2[0]));\n\n    while (!minHeap.isEmpty() && ans.size() < k) {\n      final int i = minHeap.peek().i;\n      final int j = minHeap.poll().j;\n      ans.add(Arrays.asList(nums1[i], nums2[j]));\n      if (j + 1 < nums2.length)\n        minHeap.offer(new T(i, j + 1, nums1[i] + nums2[j + 1]));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int i;\n  int j;\n  int sum;  // nums1[i] + nums2[j];\n  T(int i, int j, int sum) : i(i), j(j), sum(sum) {}\n};\n\nclass Solution {\n public:\n  vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2,\n                                     int k) {\n    vector<vector<int>> ans;\n    auto compare = [&](const T& a, const T& b) { return a.sum > b.sum; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n\n    for (int i = 0; i < k && i < nums1.size(); ++i)\n      minHeap.emplace(i, 0, nums1[i] + nums2[0]);\n\n    while (!minHeap.empty() && ans.size() < k) {\n      const auto [i, j, _] = minHeap.top();\n      minHeap.pop();\n      ans.push_back({nums1[i], nums2[j]});\n      if (j + 1 < nums2.size())\n        minHeap.emplace(i, j + 1, nums1[i] + nums2[j + 1]);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/373.html",
    "category": "Algorithms",
    "acceptance_rate": 40.6153635006029,
    "topics": [
      "Array",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 6589,
    "dislikes": 471,
    "similar_questions": "[{\"title\": \"Kth Smallest Element in a Sorted Matrix\", \"titleSlug\": \"kth-smallest-element-in-a-sorted-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K-th Smallest Pair Distance\", \"titleSlug\": \"find-k-th-smallest-pair-distance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Product of Two Sorted Arrays\", \"titleSlug\": \"kth-smallest-product-of-two-sorted-arrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"372.9K\", \"totalSubmission\": \"918.1K\", \"totalAcceptedRaw\": 372871, \"totalSubmissionRaw\": 918057, \"acRate\": \"40.6%\"}",
    "title_pt": "Encontrar k Pares com Menores Somas",
    "description_pt": "<p>Você recebe dois arrays de inteiros <code>nums1</code> e <code>nums2</code> ordenados em <strong>ordem não decrescente&nbsp;</strong> e um inteiro <code>k</code>.</p>\n\n<p>Defina um par <code>(u, v)</code>, que consiste em um elemento do primeiro array e um elemento do segundo array.</p>\n\n<p>Retorne <em>os</em> <code>k</code> <em>pares</em> <code>(u<sub>1</sub>, v<sub>1</sub>), (u<sub>2</sub>, v<sub>2</sub>), ..., (u<sub>k</sub>, v<sub>k</sub>)</code> <em>com as menores somas</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,7,11], nums2 = [2,4,6], k = 3\n<strong>Saída:</strong> [[1,2],[1,4],[1,6]]\n<strong>Explicação:</strong> Os primeiros 3 pares são retornados da sequência: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,1,2], nums2 = [1,2,3], k = 2\n<strong>Saída:</strong> [[1,1],[1,1]]\n<strong>Explicação:</strong> Os primeiros 2 pares são retornados da sequência: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>nums1</code> e <code>nums2</code> ambos estão ordenados em <strong>ordem não decrescente</strong>.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n\t<li><code>k &lt;=&nbsp;nums1.length *&nbsp;nums2.length</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "374",
    "paidOnly": false,
    "title": "Guess Number Higher or Lower",
    "titleSlug": "guess-number-higher-or-lower",
    "url": "https://leetcode.com/problems/guess-number-higher-or-lower",
    "description_url": "https://leetcode.com/problems/guess-number-higher-or-lower/description/",
    "description": "<p>We are playing the Guess Game. The game is as follows:</p>\n\n<p>I pick a number from <code>1</code> to <code>n</code>. You have to guess which number I picked.</p>\n\n<p>Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.</p>\n\n<p>You call a pre-defined API <code>int guess(int num)</code>, which returns three possible results:</p>\n\n<ul>\n\t<li><code>-1</code>: Your guess is higher than the number I picked (i.e. <code>num &gt; pick</code>).</li>\n\t<li><code>1</code>: Your guess is lower than the number I picked (i.e. <code>num &lt; pick</code>).</li>\n\t<li><code>0</code>: your guess is equal to the number I picked (i.e. <code>num == pick</code>).</li>\n</ul>\n\n<p>Return <em>the number that I picked</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 10, pick = 6\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, pick = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2, pick = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= pick &lt;= n</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/guess-number-higher-or-lower/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\n/**\n * Forward declaration of guess API.\n * (The problem description is not clear, so I translate it into follows.)\n *\n * @param traget num\n *        guess num\n *\n * @return -1 if guess num >  target num\n *          0 if guess num == target num\n *          1 if guess num <  target num\n */\n\npublic class Solution extends GuessGame {\n  public int guessNumber(int n) {\n    int l = 1;\n    int r = n;\n\n    // Find the first guess num that >= target num\n    while (l < r) {\n      final int m = l + (r - l) / 2;\n      if (guess(m) <= 0) // -1, 0\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\n/**\n * Forward declaration of guess API.\n * (The problem description is not clear, so I translate it into follows.)\n *\n * @param traget num\n *        guess num\n *\n * @return -1 if guess num >  target num\n *          0 if guess num == target num\n *          1 if guess num <  target num\n */\n\nclass Solution {\n public:\n  int guessNumber(int n) {\n    int l = 1;\n    int r = n;\n\n    // Find the first guess num that >= target num\n    while (l < r) {\n      const int m = l + (r - l) / 2;\n      if (guess(m) <= 0)  // -1, 0\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/374.html",
    "category": "Algorithms",
    "acceptance_rate": 55.59915116608691,
    "topics": [
      "Binary Search",
      "Interactive"
    ],
    "hints": [],
    "likes": 3991,
    "dislikes": 626,
    "similar_questions": "[{\"title\": \"First Bad Version\", \"titleSlug\": \"first-bad-version\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Guess Number Higher or Lower II\", \"titleSlug\": \"guess-number-higher-or-lower-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K Closest Elements\", \"titleSlug\": \"find-k-closest-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"839.4K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 839449, \"totalSubmissionRaw\": 1509826, \"acRate\": \"55.6%\"}",
    "title_pt": "Adivinhe o Número: Maior ou Menor",
    "description_pt": "<p>Estamos jogando o Jogo de Adivinhação. O jogo é o seguinte:</p>\n\n<p>Eu escolho um número de <code>1</code> a <code>n</code>. Você deve adivinhar qual número eu escolhi.</p>\n\n<p>Cada vez que você errar o palpite, eu direi se o número que eu escolhi é maior ou menor do que o seu palpite.</p>\n\n<p>Você chama uma API predefinida <code>int guess(int num)</code>, que retorna três possíveis resultados:</p>\n\n<ul>\n\t<li><code>-1</code>: Seu palpite é maior do que o número que eu escolhi (ou seja, <code>num &gt; pick</code>).</li>\n\t<li><code>1</code>: Seu palpite é menor do que o número que eu escolhi (ou seja, <code>num &lt; pick</code>).</li>\n\t<li><code>0</code>: seu palpite é igual ao número que eu escolhi (ou seja, <code>num == pick</code>).</li>\n</ul>\n\n<p>Retorne <em>o número que eu escolhi</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 10, pick = 6\n<strong>Saída:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, pick = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2, pick = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= pick &lt;= n</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "375",
    "paidOnly": false,
    "title": "Guess Number Higher or Lower II",
    "titleSlug": "guess-number-higher-or-lower-ii",
    "url": "https://leetcode.com/problems/guess-number-higher-or-lower-ii",
    "description_url": "https://leetcode.com/problems/guess-number-higher-or-lower-ii/description/",
    "description": "<p>We are playing the Guessing Game. The game will work as follows:</p>\n\n<ol>\n\t<li>I pick a number between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>n</code>.</li>\n\t<li>You guess a number.</li>\n\t<li>If you guess the right number, <strong>you win the game</strong>.</li>\n\t<li>If you guess the wrong number, then I will tell you whether the number I picked is <strong>higher or lower</strong>, and you will continue guessing.</li>\n\t<li>Every time you guess a wrong number&nbsp;<code>x</code>, you will pay&nbsp;<code>x</code>&nbsp;dollars. If you run out of money, <strong>you lose the game</strong>.</li>\n</ol>\n\n<p>Given a particular&nbsp;<code>n</code>, return&nbsp;<em>the minimum amount of money you need to&nbsp;<strong>guarantee a win regardless of what number I pick</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/10/graph.png\" style=\"width: 505px; height: 388px;\" />\n<pre>\n<strong>Input:</strong> n = 10\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n&nbsp;   - If this is my number, your total is $0. Otherwise, you pay $7.\n&nbsp;   - If my number is higher, the range is [8,10]. Guess 9.\n&nbsp;       - If this is my number, your total is $7. Otherwise, you pay $9.\n&nbsp;       - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n&nbsp;       - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n&nbsp;   - If my number is lower, the range is [1,6]. Guess 3.\n&nbsp;       - If this is my number, your total is $7. Otherwise, you pay $3.\n&nbsp;       - If my number is higher, the range is [4,6]. Guess 5.\n&nbsp;           - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n&nbsp;           - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n&nbsp;           - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n&nbsp;       - If my number is lower, the range is [1,2]. Guess 1.\n&nbsp;           - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n&nbsp;           - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 0\n<strong>Explanation:</strong>&nbsp;There is only one possible number, so you can guess 1 and not have to pay anything.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 1\n<strong>Explanation:</strong>&nbsp;There are two possible numbers, 1 and 2.\n- Guess 1.\n&nbsp;   - If this is my number, your total is $0. Otherwise, you pay $1.\n&nbsp;   - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/guess-number-higher-or-lower-ii/solutions/",
    "solution": "[TOC]\n\n## Summary\n\nGiven a number $$n$$, we have to find the worst-case cost of guessing a number chosen from the range $$(1, n)$$, assuming that the guesses are made intelligently(minimize the total cost). The cost is incremented by $$i$$ for every wrong guess $$i$$.\n\nFor example:\n```\nn=5\n1 2 3 4 5\n```\nIf we start with 3 as the initial guess, the next guess would certainly be 4 as in the worst case required number is 5. Total Cost $$= 4+3=7$$.\n\nBut if we start with 4 as the initial guess, our next guess would be 2 as in the worst case required number is 3 or 1. Total Cost $$=4+2=6$$ which is the minimum cost.\n\n```\nn=8\n1 2 3 4 5 6 7 8\n```\nIn this case, we have to guess 5 followed by 7. Total Cost $$=5+7=12$$.\nIf we choose 4 as our initial guess. Total Cost $$=4+5+7=16$$.\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\nFirstly, we need to be aware of the fact that out of the range $$(1, n)$$, we have to guess the numbers intelligently in order to minimize the cost. But, along with that we have to take into account the worst-case scenario possible, that is we have to assume that the original number chosen is such that it will try to maximize the overall cost.\n\nIn Brute Force, we can pick up any number $$i$$ in the range $$(1, n)$$. Assuming it is a wrong guess(worst-case scenario), we have to minimize the cost of reaching the required number. Now, the required number could be lying either to the right or left of the number picked($$i$$). But to cover the possibility of the worst case number chosen, we need to take the maximum cost out of the cost of reaching the worst number out of the right and left segments of $$i$$. Thus, if we pick up $$i$$ as the pivot, the overall minimum cost for the worst required number will be:\n\n$$\n\\mathrm{cost}(1, n)=i + \\max\\big(\\mathrm{cost}(1,i-1), \\mathrm{cost}(i+1,n)\\big)\n$$\n\nFor every segment, we can further choose another pivot and repeat the same process for calculating the minimum cost.\n\nBy using the above procedure, we found out the cost of reaching the required number starting with $$i$$ as the pivot. In the same way, we iterate over all the numbers in the range $$(1, n)$$, choosing them as the pivot, calculating the cost of every pivot chosen, and thus, we can find the minimum cost out of those.\n\n\n<iframe src=\"https://leetcode.com/playground/QW3ndyqL/shared\" frameBorder=\"0\" name=\"QW3ndyqL\" width=\"100%\" height=\"326\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n!)$$. We choose a number as the pivot and repeat the pivoting process further $$n$$ times $$O(n!)$$. We repeat the same process for $$n$$ pivots.\n* Space complexity : $$O(n)$$. Recursion of depth $$n$$ is used.\n\n---\n### Approach #2 Modified Brute Force [Time Limit Exceeded]\n\n**Algorithm**\n\nIn Brute Force, for numbers in the range $$(i, j)$$, we picked up every number from $$i$$ to $$j$$ as the pivot and found the maximum cost out of its left and right segments. But an important point to observe is that if we choose any number from the range $$\\big( i,\\frac{i+j}{2} \\big)$$ as the pivot, the right segment(consisting of numbers larger than the picked up pivot) will be longer than the left segment(consisting of numbers smaller than it). Thus, we will always get the maximum cost from the right segment and it will be larger than the minimum cost achievable by choosing some other pivot. Therefore, our objective here is to reduce the larger cost that is coming from the right segment. Thus, it is wise to choose the pivot from the range $$\\big(\\frac{i+j}{2}, j\\big)$$. In this way the costs of the two segments will be nearer to each other and this will minimize the overall cost.\n\nThus, while choosing the pivot instead of iterating from $$i$$ to $$j$$, we iterate from $$\\frac{i+j}{2}$$ to $$j$$ and find the minimum achievable cost similar to brute force.\n\n<iframe src=\"https://leetcode.com/playground/juXrfQvD/shared\" frameBorder=\"0\" name=\"juXrfQvD\" width=\"100%\" height=\"309\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n!)$$. We choose a number as the pivot and repeat the pivoting process further $$n$$ times $$O(n!)$$. We repeat the same process for $$n$$ pivots.\n* Space complexity : $$O(n)$$. Recursion of depth $$n$$ is used.\n\n---\n### Approach #3 Using DP [Accepted]\n\n**Algorithm**\n\nThe problem of finding the minimum cost of reaching the destination number by choosing $$i$$ as a pivot can be divided into the subproblem of finding the maximum out of the minimum costs of its left and right segments as explained above. For each segment, we can continue the process leading to smaller and smaller subproblems. This leads us to the conclusion that we can use DP for this problem.\n\nWe need to use a $$dp$$ matrix, where $$dp(i, j)$$ refers to the minimum cost of finding the worst number given only the numbers in the range $$(i, j)$$. Now, we need to know how to fill in the entries of this $$dp$$. If we are given only a single number $$k$$, no matter what the number is the cost of finding that number is always 0 since we always hit the number directly without any wrong guess. Thus, firstly, we fill in all the entries of the $$dp$$ which correspond to segments of length 1 i.e. all entries $$dp(k, k)$$ are initialized to 0. Then, in order to find the entries for segments of length 2, we need all the entries for segments of length 1. Thus, in general, to fill in the entries corresponding to segments of length $$len$$, we need all the entries of length $$len-1$$ and below to be already filled. Thus, we need to fill the entries in the order of their segment lengths. Thus, we fill the entries of $$dp$$ diagonally.\n\nNow, what criteria do we need to fill up the $$dp$$ matrix? For any entry  $$dp(i, j)$$, given the current segment length of interest is $$len$$ i.e. if $$len=j-i+1$$, we assume as if we are available only with the numbers in the range $$(i, j)$$. To fill in its current entry, we follow the same process as Approach 1, choosing every number as the pivot and finding the minimum cost as:\n\n$$\n\\mathrm{cost}(i, j)=\\mathrm{pivot} + \\max\\big(\\mathrm{cost}(i,\\mathrm{pivot}-1), \\mathrm{cost}(\\mathrm{pivot}+1,j)\\big)\n$$\n\nBut, we have an advantage in terms of calculating the cost here, since we already know the costs for the segments of length smaller than $$len$$ from $$dp$$. Thus, the dp equation becomes:\n\n$$\n\\mathrm{dp}(i, j) = \\min_{\\mathrm{pivot} \\in (i, j)} \\big[ \\mathrm{pivot} + \\max \\big( \\mathrm{dp}(i,\\mathrm{pivot}-1) , \\mathrm{dp}(\\mathrm{pivot}+1,j) \\big) \\big]\n$$\n\n  where $$\\min_{\\mathrm{pivot} \\in (i, j)}$$ indicates the minimum obtained by considering every number in the range $$(i, j)$$ as the pivot.\n\nThe following animation will make the process more clear for n=5:\n<!--![Guess Number Higher or Lower](https://leetcode.com/media/original_images/375_Guess_Number_Higher_or_Lower.gif)-->\n!?!../Documents/375_Guess.json:791,552!?!\n\n\n<iframe src=\"https://leetcode.com/playground/X99KiHYD/shared\" frameBorder=\"0\" name=\"X99KiHYD\" width=\"100%\" height=\"326\"></iframe>\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. We traverse the complete $$dp$$ matrix once $$(O(n^2))$$. For every entry, we take at most $$n$$ numbers as pivot.\n\n* Space complexity : $$O(n^2)$$. $$dp$$ matrix of size $$n^2$$ is used.\n\n---\n\n### Approach #4 Better Approach using DP [Accepted]\n\n**Algorithm**\n\nIn the last approach, we chose every possible pivot from the range $$(i, j)$$. But, as per the argument given in Approach 2, we can choose pivots only from the range $$\\big(i+(len-1)/2,j\\big)$$, where $$len$$ is the current segment length of interest.\nThus the governing equation is:\n\n$$\n\\mathrm{dp}(i, j)=\\min_{\\mathrm{pivot} \\in \\big(i+\\frac{len-1}{2}, j\\big)}\\big[\\mathrm{pivot} + \\max\\big(\\mathrm{dp}(i,\\mathrm{pivot}-1), \\mathrm{dp}(\\mathrm{pivot}+1,j)\\big)\\big]\n$$\n\n Thus, we can optimize the Approach 3 to some extent.\n\n\n<iframe src=\"https://leetcode.com/playground/vxpg2Chd/shared\" frameBorder=\"0\" name=\"vxpg2Chd\" width=\"100%\" height=\"360\"></iframe>\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. We traverse the complete $$dp$$ matrix once $$(O(n^2))$$. For every entry, we take at most $$n$$ numbers as pivot.\n\n* Space complexity : $$O(n^2)$$. $$dp$$ matrix of size $$n^2$$ is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getMoneyAmount(self, n: int) -> int:\n    # Dp(i, j) := min money you need to guarantee a win of picking i..j\n    @functools.lru_cache(None)\n    def dp(i: int, j: int) -> int:\n      if i >= j:\n        return 0\n\n      ans = math.inf\n\n      for k in range(i, j + 1):\n        ans = min(ans, max(dp(i, k - 1), dp(k + 1, j)) + k)\n\n      return ans\n\n    return dp(1, n)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int getMoneyAmount(int n) {\n    // dp[i][j] := min money you need to guarantee a win of picking i..j\n    dp = new int[n + 1][n + 1];\n    Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n    return getMoneyAmount(1, n);\n  }\n\n  private int[][] dp;\n\n  private int getMoneyAmount(int i, int j) {\n    if (i >= j)\n      return 0;\n    if (dp[i][j] != Integer.MAX_VALUE)\n      return dp[i][j];\n\n    for (int k = i; k <= j; ++k)\n      dp[i][j] = Math.min(\n          dp[i][j],\n          Math.max(getMoneyAmount(i, k - 1), getMoneyAmount(k + 1, j)) + k);\n\n    return dp[i][j];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int getMoneyAmount(int n) {\n    // dp[i][j] := min money you need to guarantee a win of picking i..j\n    dp.resize(n + 1, vector<int>(n + 1, INT_MAX));\n    return getMoneyAmount(1, n);\n  }\n\n private:\n  vector<vector<int>> dp;\n\n  int getMoneyAmount(int i, int j) {\n    if (i >= j)\n      return 0;\n    if (dp[i][j] != INT_MAX)\n      return dp[i][j];\n\n    for (int k = i; k <= j; ++k)\n      dp[i][j] =\n          min(dp[i][j],\n              max(getMoneyAmount(i, k - 1), getMoneyAmount(k + 1, j)) + k);\n\n    return dp[i][j];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/375.html",
    "category": "Algorithms",
    "acceptance_rate": 50.97175898227727,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Game Theory"
    ],
    "hints": [
      "The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the <b>first</b> scenario.",
      "Take a small example (n = 3). What do you end up paying in the worst case?",
      "Check out <a href=\"https://en.wikipedia.org/wiki/Minimax\">this article</a> if you're still stuck.",
      "The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming.",
      "As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?"
    ],
    "likes": 2235,
    "dislikes": 2153,
    "similar_questions": "[{\"title\": \"Flip Game II\", \"titleSlug\": \"flip-game-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Guess Number Higher or Lower\", \"titleSlug\": \"guess-number-higher-or-lower\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Can I Win\", \"titleSlug\": \"can-i-win\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K Closest Elements\", \"titleSlug\": \"find-k-closest-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"142.3K\", \"totalSubmission\": \"279.1K\", \"totalAcceptedRaw\": 142279, \"totalSubmissionRaw\": 279133, \"acRate\": \"51.0%\"}",
    "title_pt": "Adivinhe o Número Mais Alto ou Mais Baixo II",
    "description_pt": "<p>Estamos jogando o Jogo de Adivinhação. O jogo funcionará da seguinte forma:</p>\n\n<ol>\n\t<li>Eu escolho um número entre&nbsp;<code>1</code>&nbsp;e&nbsp;<code>n</code>.</li>\n\t<li>Você adivinha um número.</li>\n\t<li>Se você adivinhar o número correto, <strong>você vence o jogo</strong>.</li>\n\t<li>Se você adivinhar o número errado, então eu lhe direi se o número que eu escolhi é <strong>maior ou menor</strong>, e você continuará adivinhando.</li>\n\t<li>Toda vez que você adivinhar um número errado&nbsp;<code>x</code>, você pagará&nbsp;<code>x</code>&nbsp;dólares. Se você ficar sem dinheiro, <strong>você perde o jogo</strong>.</li>\n</ol>\n\n<p>Dado um determinado&nbsp;<code>n</code>, retorne&nbsp;<em>a quantidade mínima de dinheiro que você precisa para&nbsp;<strong>garantir uma vitória independentemente de qual número eu escolher</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/10/graph.png\" style=\"width: 505px; height: 388px;\" />\n<pre>\n<strong>Entrada:</strong> n = 10\n<strong>Saída:</strong> 16\n<strong>Explicação:</strong> A estratégia vencedora é a seguinte:\n- O intervalo é [1,10]. Adivinhe 7.\n&nbsp;   - Se este for o meu número, seu total é $0. Caso contrário, você paga $7.\n&nbsp;   - Se o meu número for maior, o intervalo é [8,10]. Adivinhe 9.\n&nbsp;       - Se este for o meu número, seu total é $7. Caso contrário, você paga $9.\n&nbsp;       - Se o meu número for maior, ele deve ser 10. Adivinhe 10. Seu total é $7 + $9 = $16.\n&nbsp;       - Se o meu número for menor, ele deve ser 8. Adivinhe 8. Seu total é $7 + $9 = $16.\n&nbsp;   - Se o meu número for menor, o intervalo é [1,6]. Adivinhe 3.\n&nbsp;       - Se este for o meu número, seu total é $7. Caso contrário, você paga $3.\n&nbsp;       - Se o meu número for maior, o intervalo é [4,6]. Adivinhe 5.\n&nbsp;           - Se este for o meu número, seu total é $7 + $3 = $10. Caso contrário, você paga $5.\n&nbsp;           - Se o meu número for maior, ele deve ser 6. Adivinhe 6. Seu total é $7 + $3 + $5 = $15.\n&nbsp;           - Se o meu número for menor, ele deve ser 4. Adivinhe 4. Seu total é $7 + $3 + $5 = $15.\n&nbsp;       - Se o meu número for menor, o intervalo é [1,2]. Adivinhe 1.\n&nbsp;           - Se este for o meu número, seu total é $7 + $3 = $10. Caso contrário, você paga $1.\n&nbsp;           - Se o meu número for maior, ele deve ser 2. Adivinhe 2. Seu total é $7 + $3 + $1 = $11.\nO pior caso em todos esses cenários é que você paga $16. Portanto, você só precisa de $16 para garantir uma vitória.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong>&nbsp;Há apenas um número possível, então você pode adivinhar 1 e não precisar pagar nada.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong>&nbsp;Há dois números possíveis, 1 e 2.\n- Adivinhe 1.\n&nbsp;   - Se este for o meu número, seu total é $0. Caso contrário, você paga $1.\n&nbsp;   - Se o meu número for maior, ele deve ser 2. Adivinhe 2. Seu total é $1.\nO pior caso é que você paga $1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: A melhor estratégia para jogar o jogo é minimizar a perda máxima que você poderia enfrentar. Outra estratégia é minimizar a perda esperada. Aqui, estamos interessados no <b>primeiro</b> cenário.",
      "Dica 2: Pegue um exemplo pequeno (n = 3). O que você acaba pagando no pior caso?",
      "Dica 3: Confira <a href=\"https://en.wikipedia.org/wiki/Minimax\">este artigo</a> se você ainda estiver travado.",
      "Dica 4: A implementação puramente recursiva de minimax seria inútil até mesmo para um n pequeno. Você DEVE usar programação dinâmica.",
      "Dica 5: Como desafio extra, como você modificaria seu código para resolver o problema de minimizar a perda esperada, em vez da perda no pior caso?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "376",
    "paidOnly": false,
    "title": "Wiggle Subsequence",
    "titleSlug": "wiggle-subsequence",
    "url": "https://leetcode.com/problems/wiggle-subsequence",
    "description_url": "https://leetcode.com/problems/wiggle-subsequence/description/",
    "description": "<p>A <strong>wiggle sequence</strong> is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.</p>\n\n<ul>\n\t<li>For example, <code>[1, 7, 4, 9, 2, 5]</code> is a <strong>wiggle sequence</strong> because the differences <code>(6, -3, 5, -7, 3)</code> alternate between positive and negative.</li>\n\t<li>In contrast, <code>[1, 4, 7, 2, 5]</code> and <code>[1, 7, 4, 5, 5]</code> are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.</li>\n</ul>\n\n<p>A <strong>subsequence</strong> is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.</p>\n\n<p>Given an integer array <code>nums</code>, return <em>the length of the longest <strong>wiggle subsequence</strong> of </em><code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,7,4,9,2,5]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,17,5,10,13,15,10,5,16,8]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,5,6,7,8,9]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve this in <code>O(n)</code> time?</p>\n",
    "solution_url": "https://leetcode.com/problems/wiggle-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int wiggleMaxLength(int[] nums) {\n    int increasing = 1;\n    int decreasing = 1;\n\n    for (int i = 1; i < nums.length; ++i)\n      if (nums[i] > nums[i - 1])\n        increasing = decreasing + 1;\n      else if (nums[i] < nums[i - 1])\n        decreasing = increasing + 1;\n\n    return Math.max(increasing, decreasing);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int wiggleMaxLength(vector<int>& nums) {\n    int increasing = 1;\n    int decreasing = 1;\n\n    for (int i = 1; i < nums.size(); ++i)\n      if (nums[i] > nums[i - 1])\n        increasing = decreasing + 1;\n      else if (nums[i] < nums[i - 1])\n        decreasing = increasing + 1;\n\n    return max(increasing, decreasing);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/376.html",
    "category": "Algorithms",
    "acceptance_rate": 48.813420101439455,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy"
    ],
    "hints": [],
    "likes": 5219,
    "dislikes": 167,
    "similar_questions": "[{\"title\": \"Rearrange Array Elements by Sign\", \"titleSlug\": \"rearrange-array-elements-by-sign\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"268.6K\", \"totalSubmission\": \"550.3K\", \"totalAcceptedRaw\": 268609, \"totalSubmissionRaw\": 550278, \"acRate\": \"48.8%\"}",
    "title_pt": "Subsequência em Sinuosidade",
    "description_pt": "<p>Uma <strong>wiggle sequence</strong> é uma sequência em que as diferenças entre números sucessivos alternam estritamente entre positivas e negativas. A primeira diferença (se existir) pode ser positiva ou negativa. Uma sequência com um elemento e uma sequência com dois elementos diferentes são, trivialmente, <strong>wiggle sequences</strong>.</p>\n\n<ul>\n\t<li>Por exemplo, <code>[1, 7, 4, 9, 2, 5]</code> é uma <strong>wiggle sequence</strong> porque as diferenças <code>(6, -3, 5, -7, 3)</code> alternam entre positivas e negativas.</li>\n\t<li>Em contraste, <code>[1, 4, 7, 2, 5]</code> e <code>[1, 7, 4, 5, 5]</code> não são <strong>wiggle sequences</strong>. A primeira não é porque suas duas primeiras diferenças são positivas, e a segunda não é porque sua última diferença é zero.</li>\n</ul>\n\n<p>Uma <strong>subsequence</strong> é obtida pela remoção de alguns elementos (possivelmente zero) da sequência original, mantendo os elementos restantes em sua ordem original.</p>\n\n<p>Dado um array de inteiros <code>nums</code>, retorne <em>o comprimento da mais longa <strong>wiggle subsequence</strong> de </em><code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,7,4,9,2,5]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> A sequência inteira é uma <strong>wiggle sequence</strong> com diferenças (6, -3, 5, -7, 3).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,17,5,10,13,15,10,5,16,8]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Existem várias subsequences que atingem esse comprimento.\nUma delas é [1, 17, 10, 13, 10, 16, 8] com diferenças (16, -7, 3, -3, 6, -8).\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,5,6,7,8,9]\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria resolver isso em tempo <code>O(n)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "377",
    "paidOnly": false,
    "title": "Combination Sum IV",
    "titleSlug": "combination-sum-iv",
    "url": "https://leetcode.com/problems/combination-sum-iv",
    "description_url": "https://leetcode.com/problems/combination-sum-iv/description/",
    "description": "<p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p>\n\n<p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3], target = 4\n<strong>Output:</strong> 7\n<strong>Explanation:</strong>\nThe possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [9], target = 3\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>All the elements of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>1 &lt;= target &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>\n",
    "solution_url": "https://leetcode.com/problems/combination-sum-iv/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def combinationSum4(self, nums: List[int], target: int) -> int:\n    dp = [1] + [-1] * target\n\n    def dfs(target: int) -> int:\n      if target < 0:\n        return 0\n      if dp[target] != -1:\n        return dp[target]\n\n      dp[target] = sum(dfs(target - num) for num in nums)\n      return dp[target]\n\n    return dfs(target)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int combinationSum4(int[] nums, int target) {\n    // dp[i] := # of combinations that add up to i\n    int[] dp = new int[target + 1];\n    dp[0] = 1;\n\n    for (int i = 0; i <= target; ++i)\n      for (final int num : nums)\n        if (i >= num)\n          dp[i] += dp[i - num];\n\n    return dp[target];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int combinationSum4(vector<int>& nums, int target) {\n    vector<unsigned long long> dp(target + 1);\n    dp[0] = 1;\n\n    for (int i = 1; i <= target; ++i)\n      for (const int num : nums)\n        if (i >= num)\n          dp[i] += dp[i - num];\n\n    return dp[target];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/377.html",
    "category": "Algorithms",
    "acceptance_rate": 54.6171606002829,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 7569,
    "dislikes": 683,
    "similar_questions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ways to Express an Integer as Sum of Powers\", \"titleSlug\": \"ways-to-express-an-integer-as-sum-of-powers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"546K\", \"totalSubmission\": \"999.7K\", \"totalAcceptedRaw\": 545986, \"totalSubmissionRaw\": 999660, \"acRate\": \"54.6%\"}",
    "title_pt": "Soma de Combinação IV",
    "description_pt": "<p>Dado um array de inteiros <strong>distintos</strong> <code>nums</code> e um inteiro alvo <code>target</code>, retorne <em>o número de combinações possíveis que somam</em>&nbsp;<code>target</code>.</p>\n\n<p>Os casos de teste são gerados de forma que a resposta possa caber em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3], target = 4\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong>\nAs possíveis formas de combinação são:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nObserve que sequências diferentes são contadas como combinações diferentes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [9], target = 3\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>Todos os elementos de <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li><code>1 &lt;= target &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> E se números negativos forem permitidos no array dado? Como isso muda o problema? Que limitação precisamos adicionar à questão para permitir números negativos?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "378",
    "paidOnly": false,
    "title": "Kth Smallest Element in a Sorted Matrix",
    "titleSlug": "kth-smallest-element-in-a-sorted-matrix",
    "url": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix",
    "description_url": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/description/",
    "description": "<p>Given an <code>n x n</code> <code>matrix</code> where each of the rows and columns is sorted in ascending order, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest element in the matrix</em>.</p>\n\n<p>Note that it is the <code>k<sup>th</sup></code> smallest element <strong>in the sorted order</strong>, not the <code>k<sup>th</sup></code> <strong>distinct</strong> element.</p>\n\n<p>You must find a solution with a memory complexity better than <code>O(n<sup>2</sup>)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\n<strong>Output:</strong> 13\n<strong>Explanation:</strong> The elements in the matrix are [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], and the 8<sup>th</sup> smallest number is 13\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> matrix = [[-5]], k = 1\n<strong>Output:</strong> -5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == matrix.length == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>All the rows and columns of <code>matrix</code> are <strong>guaranteed</strong> to be sorted in <strong>non-decreasing order</strong>.</li>\n\t<li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Could you solve the problem with a constant memory (i.e., <code>O(1)</code> memory complexity)?</li>\n\t<li>Could you solve the problem in <code>O(n)</code> time complexity? The solution may be too advanced for an interview but you may find reading <a href=\"http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf\" target=\"_blank\">this paper</a> fun.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n    minHeap = []  # (matrix[i][j], i, j)\n\n    i = 0\n    while i < k and i < len(matrix):\n      heapq.heappush(minHeap, (matrix[i][0], i, 0))\n      i += 1\n\n    while k > 1:\n      k -= 1\n      _, i, j = heapq.heappop(minHeap)\n      if j + 1 < len(matrix[0]):\n        heapq.heappush(minHeap, (matrix[i][j + 1], i, j + 1))\n\n    return minHeap[0][0]",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int i;\n  public int j;\n  public int num; // matrix[i][j]\n  public T(int i, int j, int num) {\n    this.i = i;\n    this.j = j;\n    this.num = num;\n  }\n}\n\nclass Solution {\n  public int kthSmallest(int[][] matrix, int k) {\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.num - b.num);\n\n    for (int i = 0; i < k && i < matrix.length; ++i)\n      minHeap.offer(new T(i, 0, matrix[i][0]));\n\n    while (k-- > 1) {\n      final int i = minHeap.peek().i;\n      final int j = minHeap.poll().j;\n      if (j + 1 < matrix[0].length)\n        minHeap.offer(new T(i, j + 1, matrix[i][j + 1]));\n    }\n\n    return minHeap.peek().num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int i;\n  int j;\n  int num;  // matrix[i][j]\n  T(int i, int j, int num) : i(i), j(j), num(num) {}\n};\n\nclass Solution {\n public:\n  int kthSmallest(vector<vector<int>>& matrix, int k) {\n    auto compare = [&](const T& a, const T& b) { return a.num > b.num; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n\n    for (int i = 0; i < k && i < matrix.size(); ++i)\n      minHeap.emplace(i, 0, matrix[i][0]);\n\n    while (k-- > 1) {\n      const auto [i, j, _] = minHeap.top();\n      minHeap.pop();\n      if (j + 1 < matrix[0].size())\n        minHeap.emplace(i, j + 1, matrix[i][j + 1]);\n    }\n\n    return minHeap.top().num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/378.html",
    "category": "Algorithms",
    "acceptance_rate": 63.45346907655739,
    "topics": [
      "Array",
      "Binary Search",
      "Sorting",
      "Heap (Priority Queue)",
      "Matrix"
    ],
    "hints": [],
    "likes": 10224,
    "dislikes": 376,
    "similar_questions": "[{\"title\": \"Find K Pairs with Smallest Sums\", \"titleSlug\": \"find-k-pairs-with-smallest-sums\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Number in Multiplication Table\", \"titleSlug\": \"kth-smallest-number-in-multiplication-table\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find K-th Smallest Pair Distance\", \"titleSlug\": \"find-k-th-smallest-pair-distance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"K-th Smallest Prime Fraction\", \"titleSlug\": \"k-th-smallest-prime-fraction\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"707.4K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 707408, \"totalSubmissionRaw\": 1114845, \"acRate\": \"63.5%\"}",
    "title_pt": "K-ésimo Menor Elemento em uma Matriz Ordenada",
    "description_pt": "<p>Dada uma <code>matrix</code> <code>n x n</code> em que cada uma das linhas e colunas está ordenada em ordem crescente, retorne <em>o</em> <code>k<sup>th</sup></code> <em>menor elemento na matriz</em>.</p>\n\n<p>Observe que é o <code>k<sup>th</sup></code> menor elemento <strong>na ordem ordenada</strong>, e não o <code>k<sup>th</sup></code> elemento <strong>distinto</strong>.</p>\n\n<p>Você deve encontrar uma solução com complexidade de memória melhor que <code>O(n<sup>2</sup>)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\n<strong>Saída:</strong> 13\n<strong>Explicação:</strong> Os elementos na matriz são [1,5,9,10,11,12,13,<u><strong>13</strong></u>,15], e o 8<sup>th</sup> menor número é 13\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matrix = [[-5]], k = 1\n<strong>Saída:</strong> -5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == matrix.length == matrix[i].length</code></li>\n\t<li><code>1 &lt;= n &lt;= 300</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= matrix[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>Todas as linhas e colunas de <code>matrix</code> são <strong>garantidamente</strong> ordenadas em <strong>ordem não decrescente</strong>.</li>\n\t<li><code>1 &lt;= k &lt;= n<sup>2</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Você conseguiria resolver o problema com memória constante (isto é, complexidade de memória <code>O(1)</code>)?</li>\n\t<li>Você conseguiria resolver o problema em complexidade de tempo <code>O(n)</code>? A solução pode ser avançada demais para uma entrevista, mas você pode achar divertido ler <a href=\"http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf\" target=\"_blank\">este artigo</a>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "380",
    "paidOnly": false,
    "title": "Insert Delete GetRandom O(1)",
    "titleSlug": "insert-delete-getrandom-o1",
    "url": "https://leetcode.com/problems/insert-delete-getrandom-o1",
    "description_url": "https://leetcode.com/problems/insert-delete-getrandom-o1/description/",
    "description": "<p>Implement the <code>RandomizedSet</code> class:</p>\n\n<ul>\n\t<li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li>\n\t<li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li>\n\t<li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li>\n\t<li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li>\n</ul>\n\n<p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;]\n[[], [1], [2], [2], [], [1], [2], []]\n<strong>Output</strong>\n[null, true, false, true, 2, true, false, 2]\n\n<strong>Explanation</strong>\nRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li>\n\t<li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/insert-delete-getrandom-o1/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass RandomizedSet:\n  def __init__(self):\n    \"\"\"\n    Initialize your data structure here.\n    \"\"\"\n    self.vals = []\n    self.valToIndex = defaultdict(int)\n\n  def insert(self, val: int) -> bool:\n    \"\"\"\n    Inserts a value to the set. Returns true if the set did not already contain the specified element.\n    \"\"\"\n    if val in self.valToIndex:\n      return False\n\n    self.valToIndex[val] = len(self.vals)\n    self.vals.append(val)\n    return True\n\n  def remove(self, val: int) -> bool:\n    \"\"\"\n    Removes a value from the set. Returns true if the set contained the specified element.\n    \"\"\"\n    if val not in self.valToIndex:\n      return False\n\n    index = self.valToIndex[val]\n    self.valToIndex[self.vals[-1]] = index\n    del self.valToIndex[val]\n    self.vals[index] = self.vals[-1]\n    self.vals.pop()\n    return True\n\n  def getRandom(self) -> int:\n    \"\"\"\n    Get a random element from the set.\n    \"\"\"\n    index = randint(0, len(self.vals) - 1)\n    return self.vals[index]",
    "solution_code_java": "\t\t\t\n\nclass RandomizedSet {\n  /**\n   * Inserts a value to the set. Returns true if the set did not already contain the specified\n   * element.\n   */\n  public boolean insert(int val) {\n    if (valToIndex.containsKey(val))\n      return false;\n\n    valToIndex.put(val, vals.size());\n    vals.add(val);\n    return true;\n  }\n\n  /** Removes a value from the set. Returns true if the set contained the specified element. */\n  public boolean remove(int val) {\n    if (!valToIndex.containsKey(val))\n      return false;\n\n    final int index = valToIndex.get(val);\n    // Following two lines order are important when vals.size() == 1\n    valToIndex.put(last(vals), index);\n    valToIndex.remove(val);\n    vals.set(index, last(vals));\n    vals.remove(vals.size() - 1);\n    return true;\n  }\n\n  /** Get a random element from the set. */\n  public int getRandom() {\n    final int index = rand.nextInt(vals.size());\n    return vals.get(index);\n  }\n\n  private Map<Integer, Integer> valToIndex = new HashMap<>(); // {val: index in vals}\n  private List<Integer> vals = new ArrayList<>();\n  private Random rand = new Random();\n\n  private int last(List<Integer> vals) {\n    return vals.get(vals.size() - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass RandomizedSet {\n public:\n  /** Inserts a value to the set. Returns true if the set did not already\n   * contain the specified element. */\n  bool insert(int val) {\n    if (valToIndex.count(val))\n      return false;\n\n    valToIndex[val] = vals.size();\n    vals.push_back(val);\n    return true;\n  }\n\n  /** Removes a value from the set. Returns true if the set contained the\n   * specified element. */\n  bool remove(int val) {\n    if (!valToIndex.count(val))\n      return false;\n\n    const int index = valToIndex[val];\n    // Following two lines order are important when vals.size() == 1\n    valToIndex[vals.back()] = index;\n    valToIndex.erase(val);\n    vals[index] = vals.back();\n    vals.pop_back();\n    return true;\n  }\n\n  /** Get a random element from the set. */\n  int getRandom() {\n    const int index = rand() % vals.size();\n    return vals[index];\n  }\n\n private:\n  unordered_map<int, int> valToIndex;  // {val: index in vals}\n  vector<int> vals;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/380.html",
    "category": "Algorithms",
    "acceptance_rate": 54.931663895945995,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Design",
      "Randomized"
    ],
    "hints": [],
    "likes": 9610,
    "dislikes": 675,
    "similar_questions": "[{\"title\": \"Insert Delete GetRandom O(1) - Duplicates allowed\", \"titleSlug\": \"insert-delete-getrandom-o1-duplicates-allowed\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1171042, \"totalSubmissionRaw\": 2131816, \"acRate\": \"54.9%\"}",
    "title_pt": "Inserir, Remover e Obter Aleatório em O(1)",
    "description_pt": "<p>Implemente a classe <code>RandomizedSet</code>:</p>\n\n<ul>\n\t<li><code>RandomizedSet()</code> Inicializa o objeto <code>RandomizedSet</code>.</li>\n\t<li><code>bool insert(int val)</code> Insere um item <code>val</code> no conjunto, se não estiver presente. Retorna <code>true</code> se o item não estava presente, <code>false</code> caso contrário.</li>\n\t<li><code>bool remove(int val)</code> Remove um item <code>val</code> do conjunto, se estiver presente. Retorna <code>true</code> se o item estava presente, <code>false</code> caso contrário.</li>\n\t<li><code>int getRandom()</code> Retorna um elemento aleatório do conjunto atual de elementos (é garantido que pelo menos um elemento existe quando este método é chamado). Cada elemento deve ter a <b>mesma probabilidade</b> de ser retornado.</li>\n</ul>\n\n<p>Você deve implementar as funções da classe de modo que cada função opere com complexidade de tempo <strong>média</strong> de <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;]\n[[], [1], [2], [2], [], [1], [2], []]\n<strong>Saída</strong>\n[null, true, false, true, 2, true, false, 2]\n\n<strong>Explicação</strong>\nRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Insere 1 no conjunto. Retorna true, pois 1 foi inserido com sucesso.\nrandomizedSet.remove(2); // Retorna false, pois 2 não existe no conjunto.\nrandomizedSet.insert(2); // Insere 2 no conjunto, retorna true. O conjunto agora contém [1,2].\nrandomizedSet.getRandom(); // getRandom() deve retornar 1 ou 2 aleatoriamente.\nrandomizedSet.remove(1); // Remove 1 do conjunto, retorna true. O conjunto agora contém [2].\nrandomizedSet.insert(2); // 2 já estava no conjunto, então retorna false.\nrandomizedSet.getRandom(); // Como 2 é o único número no conjunto, getRandom() sempre retornará 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>No máximo <code>2 *&nbsp;</code><code>10<sup>5</sup></code> chamadas serão feitas para <code>insert</code>, <code>remove</code> e <code>getRandom</code>.</li>\n\t<li>Haverá <strong>pelo menos um</strong> elemento na estrutura de dados quando <code>getRandom</code> for chamado.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "381",
    "paidOnly": false,
    "title": "Insert Delete GetRandom O(1) - Duplicates allowed",
    "titleSlug": "insert-delete-getrandom-o1-duplicates-allowed",
    "url": "https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed",
    "description_url": "https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/",
    "description": "<p><code>RandomizedCollection</code> is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.</p>\n\n<p>Implement the <code>RandomizedCollection</code> class:</p>\n\n<ul>\n\t<li><code>RandomizedCollection()</code> Initializes the empty <code>RandomizedCollection</code> object.</li>\n\t<li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the multiset, even if the item is already present. Returns <code>true</code> if the item is not present, <code>false</code> otherwise.</li>\n\t<li><code>bool remove(int val)</code> Removes an item <code>val</code> from the multiset if present. Returns <code>true</code> if the item is present, <code>false</code> otherwise. Note that if <code>val</code> has multiple occurrences in the multiset, we only remove one of them.</li>\n\t<li><code>int getRandom()</code> Returns a random element from the current multiset of elements. The probability of each element being returned is <strong>linearly related</strong> to the number of the same values the multiset contains.</li>\n</ul>\n\n<p>You must implement the functions of the class such that each function works on <strong>average</strong> <code>O(1)</code> time complexity.</p>\n\n<p><strong>Note:</strong> The test cases are generated such that <code>getRandom</code> will only be called if there is <strong>at least one</strong> item in the <code>RandomizedCollection</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;RandomizedCollection&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;getRandom&quot;]\n[[], [1], [1], [2], [], [1], []]\n<strong>Output</strong>\n[null, true, false, true, 2, true, 1]\n\n<strong>Explanation</strong>\nRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1);   // return true since the collection does not contain 1.\n                                  // Inserts 1 into the collection.\nrandomizedCollection.insert(1);   // return false since the collection contains 1.\n                                  // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2);   // return true since the collection does not contain 2.\n                                  // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n                                  // - return 1 with probability 2/3, or\n                                  // - return 2 with probability 1/3.\nrandomizedCollection.remove(1);   // return true since the collection contains 1.\n                                  // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>At most <code>2 * 10<sup>5</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li>\n\t<li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n#### Intuition\n\nWe must support three operations with duplicates:\n\n1. `insert`\n2. `remove`\n3. `getRandom`\n\nTo `getRandom` in $$O(1)$$ and have it scale linearly with the number of copies of a value. The simplest solution is to store all values in a list. Once all values are stored, all we have to do is pick a random index.\n\nWe don't care about the order of our elements, so `insert` can be done in $$O(1)$$ using a dynamic array (`ArrayList` in Java or `list` in Python).\n\nThe issue we run into is how to go about an `O(1)` remove. Generally we learn that removing an element from an array takes a place in $$O(N)$$, unless it is the last element in which case it is $$O(1)$$.\n\nThe key here is that _we don't care about order_. For the purposes of this problem, if we want to remove the element at the `i`th index, we can simply swap the `i`th element and the last element, and perform an $$O(1)$$ pop (_technically_ we don't have to swap, we just have to copy the last element into index `i` because it's popped anyway).\n\nWith this in mind, the most difficult part of the problem becomes _finding_ the index of the element we have to remove. All we have to do is have an accompanying data structure that maps the element values to their index.\n\n---\n### Approach 1: ArrayList + HashMap\n\n**Algorithm**\n\nWe will keep a `list` to store all our elements. In order to make finding the index of elements we want to remove $$O(1)$$, we will use a `HashMap` or dictionary to map values to all indices that have those values. To make this work each value will be mapped to a set of indices. The tricky part is properly updating the `HashMap` as we modify the `list`.\n\n- `insert`: Append the element to the `list` and add the index to `HashMap[element]`.\n- `remove`: This is the tricky part. We find the index of the element using the `HashMap`.  We use the trick discussed in the intuition to remove the element from the `list` in $$O(1)$$. Since the last element in the list gets moved around, we have to update its value in the `HashMap`. We also have to get rid of the index of the element we removed from the `HashMap`.\n- `getRandom`: Sample a random element from the list.\n\n**Implementation**\n<iframe src=\"https://leetcode.com/playground/MQ3RGKXN/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"MQ3RGKXN\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(N)$$, with $$N$$ being the number of operations. All of our operations are $$O(1)$$, giving $$N * O(1) = O(N)$$.\n\n* Space complexity : $$O(N)$$, with $$N$$ being the number of operations. The worst case scenario is if we get $$N$$ `add` operations, in which case our `ArrayList` and our `HashMap` grow to size $$N$$.",
    "solution_code_python": "\t\t\t\n\nclass RandomizedCollection:\n  def __init__(self):\n    \"\"\"\n    Initialize your data structure here.\n    \"\"\"\n    self.vals = []\n    self.valToIndices = defaultdict(list)\n\n  def insert(self, val: int) -> bool:\n    \"\"\"\n    Inserts a value to the collection. Returns true if the collection did not already contain the specified element.\n    \"\"\"\n    self.valToIndices[val].append(len(self.vals))\n    self.vals.append([val, len(self.valToIndices[val]) - 1])\n    return len(self.valToIndices[val]) == 1\n\n  def remove(self, val: int) -> bool:\n    \"\"\"\n    Removes a value from the collection. Returns true if the collection contained the specified element.\n    \"\"\"\n    if val not in self.valToIndices or self.valToIndices[val] == []:\n      return False\n\n    index = self.valToIndices[val][-1]\n    self.valToIndices[self.vals[-1][0]][self.vals[-1][1]] = index\n    self.valToIndices[val].pop()\n    self.vals[index] = self.vals[-1]\n    self.vals.pop()\n    return True\n\n  def getRandom(self) -> int:\n    \"\"\"\n    Get a random element from the collection.\n    \"\"\"\n    index = randint(0, len(self.vals) - 1)\n    return self.vals[index][0]",
    "solution_code_java": "\t\t\t\n\nclass Item {\n  public int val;\n  public int indexInMap;\n  public Item(int val, int indexInMap) {\n    this.val = val;\n    this.indexInMap = indexInMap;\n  }\n}\n\nclass RandomizedCollection {\n  /**\n   * Inserts a value to the collection. Returns true if the collection did not already contain the\n   * specified element.\n   */\n  public boolean insert(int val) {\n    valToIndices.putIfAbsent(val, new ArrayList<>());\n    valToIndices.get(val).add(items.size());\n    items.add(new Item(val, valToIndices.get(val).size() - 1));\n    return valToIndices.get(val).size() == 1;\n  }\n\n  /**\n   * Removes a value from the collection. Returns true if the collection contained the specified\n   * element.\n   */\n  public boolean remove(int val) {\n    if (!valToIndices.containsKey(val))\n      return false;\n\n    final int index = lastIndex(valToIndices.get(val));\n    valToIndices.get(last(items).val).set(last(items).indexInMap, index);\n    final int indicesSize = valToIndices.get(val).size();\n    valToIndices.get(val).remove(indicesSize - 1);\n    if (valToIndices.get(val).isEmpty())\n      valToIndices.remove(val);\n    items.set(index, last(items));\n    items.remove(items.size() - 1);\n    return true;\n  }\n\n  /** Get a random element from the collection. */\n  public int getRandom() {\n    final int index = rand.nextInt(items.size());\n    return items.get(index).val;\n  }\n\n  private Map<Integer, List<Integer>> valToIndices = new HashMap<>();\n  private List<Item> items = new ArrayList<>();\n  private Random rand = new Random();\n\n  private int lastIndex(List<Integer> indices) {\n    return indices.get(indices.size() - 1);\n  }\n\n  private Item last(List<Item> items) {\n    return items.get(items.size() - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Item {\n  int val;\n  int indexInMap;\n  Item(int val, int indexInMap) : val(val), indexInMap(indexInMap) {}\n};\n\nclass RandomizedCollection {\n public:\n  /** Inserts a value to the collection. Returns true if the collection did not\n   * already contain the specified element. */\n  bool insert(int val) {\n    valToIndices[val].push_back(items.size());\n    items.emplace_back(val, valToIndices[val].size() - 1);\n    return valToIndices[val].size() == 1;\n  }\n\n  /** Removes a value from the collection. Returns true if the collection\n   * contained the specified element. */\n  bool remove(int val) {\n    if (!valToIndices.count(val))\n      return false;\n\n    const int index = valToIndices[val].back();\n    valToIndices[items.back().val][items.back().indexInMap] = index;\n    valToIndices[val].pop_back();\n    if (valToIndices[val].empty())\n      valToIndices.erase(val);\n    items[index] = items.back();\n    items.pop_back();\n    return true;\n  }\n\n  /** Get a random element from the collection. */\n  int getRandom() {\n    const int index = rand() % items.size();\n    return items[index].val;\n  }\n\n private:\n  unordered_map<int, vector<int>> valToIndices;\n  vector<Item> items;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/381.html",
    "category": "Algorithms",
    "acceptance_rate": 35.72381006331513,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Design",
      "Randomized"
    ],
    "hints": [],
    "likes": 2357,
    "dislikes": 153,
    "similar_questions": "[{\"title\": \"Insert Delete GetRandom O(1)\", \"titleSlug\": \"insert-delete-getrandom-o1\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"164K\", \"totalSubmission\": \"459K\", \"totalAcceptedRaw\": 163963, \"totalSubmissionRaw\": 458974, \"acRate\": \"35.7%\"}",
    "title_pt": "Inserir, Remover e Obter Aleatório em O(1) - Duplicatas Permitidas",
    "description_pt": "<p><code>RandomizedCollection</code> é uma estrutura de dados que contém uma coleção de números, possivelmente com duplicatas (isto é, um multiconjunto). Ela deve suportar a inserção e a remoção de elementos específicos e também a obtenção de um elemento aleatório.</p>\n\n<p>Implemente a classe <code>RandomizedCollection</code>:</p>\n\n<ul>\n\t<li><code>RandomizedCollection()</code> Inicializa o objeto <code>RandomizedCollection</code> vazio.</li>\n\t<li><code>bool insert(int val)</code> Insere um item <code>val</code> no multiconjunto, mesmo que o item já esteja presente. Retorna <code>true</code> se o item não estiver presente, <code>false</code> caso contrário.</li>\n\t<li><code>bool remove(int val)</code> Remove um item <code>val</code> do multiconjunto, se presente. Retorna <code>true</code> se o item estiver presente, <code>false</code> caso contrário. Observe que, se <code>val</code> tiver múltiplas ocorrências no multiconjunto, removemos apenas uma delas.</li>\n\t<li><code>int getRandom()</code> Retorna um elemento aleatório do multiconjunto atual de elementos. A probabilidade de cada elemento ser retornado é <strong>linearmente relacionada</strong> ao número de valores iguais que o multiconjunto contém.</li>\n</ul>\n\n<p>Você deve implementar as funções da classe de modo que cada função funcione com complexidade de tempo <strong>média</strong> <code>O(1)</code>.</p>\n\n<p><strong>Nota:</strong> Os casos de teste são gerados de forma que <code>getRandom</code> só será chamado se houver <strong>pelo menos um</strong> item no <code>RandomizedCollection</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;RandomizedCollection&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;getRandom&quot;]\n[[], [1], [1], [2], [], [1], []]\n<strong>Saída</strong>\n[null, true, false, true, 2, true, 1]\n\n<strong>Explicação</strong>\nRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1);   // return true since the collection does not contain 1.\n                                  // Inserts 1 into the collection.\nrandomizedCollection.insert(1);   // return false since the collection contains 1.\n                                  // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2);   // return true since the collection does not contain 2.\n                                  // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n                                  // - return 1 with probability 2/3, or\n                                  // - return 2 with probability 1/3.\nrandomizedCollection.remove(1);   // return true since the collection contains 1.\n                                  // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li>No máximo <code>2 * 10<sup>5</sup></code> chamadas <strong>no total</strong> serão feitas para <code>insert</code>, <code>remove</code> e <code>getRandom</code>.</li>\n\t<li>Haverá <strong>pelo menos um</strong> elemento na estrutura de dados quando <code>getRandom</code> for chamado.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "382",
    "paidOnly": false,
    "title": "Linked List Random Node",
    "titleSlug": "linked-list-random-node",
    "url": "https://leetcode.com/problems/linked-list-random-node",
    "description_url": "https://leetcode.com/problems/linked-list-random-node/description/",
    "description": "<p>Given a singly linked list, return a random node&#39;s value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(ListNode head)</code> Initializes the object with the head of the singly-linked list <code>head</code>.</li>\n\t<li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg\" style=\"width: 302px; height: 62px;\" />\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;]\n[[[1, 2, 3]], [], [], [], [], []]\n<strong>Output</strong>\n[null, 1, 3, 2, 2, 3]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>What if the linked list is extremely large and its length is unknown to you?</li>\n\t<li>Could you solve this efficiently without using extra space?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/linked-list-random-node/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  /**\n   * @param head The linked list's head. Note that the head is guaranteed to be\n   *             not null, so it contains at least one node.\n   */\n  public Solution(ListNode head) {\n    this.head = head;\n  }\n\n  /** Returns a random node's value. */\n  public int getRandom() {\n    int ans = -1;\n    int i = 1;\n\n    for (ListNode curr = head; curr != null; curr = curr.next, ++i)\n      if (rand.nextInt(i) == i - 1)\n        ans = curr.val;\n\n    return ans;\n  }\n\n  private ListNode head;\n  private Random rand = new Random();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  /** @param head The linked list's head.\n      Note that the head is guaranteed to be not null, so it contains at least\n     one node. */\n  Solution(ListNode* head) : head(head) {}\n\n  /** Returns a random node's value. */\n  int getRandom() {\n    int ans = -1;\n    int i = 1;\n\n    for (ListNode* curr = head; curr; curr = curr->next, ++i)\n      if (rand() % i == 0)\n        ans = curr->val;\n\n    return ans;\n  }\n\n private:\n  ListNode* head;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/382.html",
    "category": "Algorithms",
    "acceptance_rate": 63.908354948112446,
    "topics": [
      "Linked List",
      "Math",
      "Reservoir Sampling",
      "Randomized"
    ],
    "hints": [],
    "likes": 3149,
    "dislikes": 715,
    "similar_questions": "[{\"title\": \"Random Pick Index\", \"titleSlug\": \"random-pick-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"264.4K\", \"totalSubmission\": \"413.7K\", \"totalAcceptedRaw\": 264378, \"totalSubmissionRaw\": 413683, \"acRate\": \"63.9%\"}",
    "title_pt": "Nó Aleatório em Lista Encadeada",
    "description_pt": "<p>Dada uma lista encadeada simplesmente encadeada, retorne o valor de um nó aleatório da lista encadeada. Cada nó deve ter a <strong>mesma probabilidade</strong> de ser escolhido.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(ListNode head)</code> Inicializa o objeto com a cabeça da lista encadeada simplesmente encadeada <code>head</code>.</li>\n\t<li><code>int getRandom()</code> Escolhe um nó aleatoriamente da lista e retorna seu valor. Todos os nós da lista devem ter a mesma probabilidade de serem escolhidos.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg\" style=\"width: 302px; height: 62px;\" />\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;]\n[[[1, 2, 3]], [], [], [], [], []]\n<strong>Saída</strong>\n[null, 1, 3, 2, 2, 3]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // retorna 1\nsolution.getRandom(); // retorna 3\nsolution.getRandom(); // retorna 2\nsolution.getRandom(); // retorna 2\nsolution.getRandom(); // retorna 3\n// getRandom() deve retornar aleatoriamente 1, 2 ou 3. Cada elemento deve ter a mesma probabilidade de ser retornado.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista encadeada estará no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>getRandom</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>E se a lista encadeada for extremamente grande e seu comprimento for desconhecido para você?</li>\n\t<li>Você conseguiria resolver isso eficientemente sem usar espaço extra?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "383",
    "paidOnly": false,
    "title": "Ransom Note",
    "titleSlug": "ransom-note",
    "url": "https://leetcode.com/problems/ransom-note",
    "description_url": "https://leetcode.com/problems/ransom-note/description/",
    "description": "<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p>\n\n<p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"a\", magazine = \"b\"\n<strong>Output:</strong> false\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"aa\", magazine = \"ab\"\n<strong>Output:</strong> false\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> ransomNote = \"aa\", magazine = \"aab\"\n<strong>Output:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/ransom-note/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n    count1 = Counter(ransomNote)\n    count2 = Counter(magazine)\n    return all(count1[c] <= count2[c] for c in string.ascii_lowercase)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canConstruct(String ransomNote, String magazine) {\n    int[] count = new int[128];\n\n    for (final char c : magazine.toCharArray())\n      ++count[c];\n\n    for (final char c : ransomNote.toCharArray())\n      if (--count[c] < 0)\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canConstruct(string ransomNote, string magazine) {\n    vector<int> count(128);\n\n    for (const char c : magazine)\n      ++count[c];\n\n    for (const char c : ransomNote)\n      if (--count[c] < 0)\n        return false;\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/383.html",
    "category": "Algorithms",
    "acceptance_rate": 64.34441355563038,
    "topics": [
      "Hash Table",
      "String",
      "Counting"
    ],
    "hints": [],
    "likes": 5333,
    "dislikes": 526,
    "similar_questions": "[{\"title\": \"Stickers to Spell Word\", \"titleSlug\": \"stickers-to-spell-word\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Words That Can Be Formed by Characters\", \"titleSlug\": \"find-words-that-can-be-formed-by-characters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1591708, \"totalSubmissionRaw\": 2473735, \"acRate\": \"64.3%\"}",
    "title_pt": "Bilhete de Resgate",
    "description_pt": "<p>Dadas duas strings <code>ransomNote</code> e <code>magazine</code>, retorne <code>true</code><em> se </em><code>ransomNote</code><em> puder ser construída usando as letras de </em><code>magazine</code><em> e </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>Cada letra em <code>magazine</code> só pode ser usada uma vez em <code>ransomNote</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> ransomNote = \"a\", magazine = \"b\"\n<strong>Saída:</strong> false\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> ransomNote = \"aa\", magazine = \"ab\"\n<strong>Saída:</strong> false\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> ransomNote = \"aa\", magazine = \"aab\"\n<strong>Saída:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>ransomNote</code> e <code>magazine</code> consistem em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "384",
    "paidOnly": false,
    "title": "Shuffle an Array",
    "titleSlug": "shuffle-an-array",
    "url": "https://leetcode.com/problems/shuffle-an-array",
    "description_url": "https://leetcode.com/problems/shuffle-an-array/description/",
    "description": "<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li>\n\t<li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li>\n\t<li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;]\n[[[1, 2, 3]], [], [], []]\n<strong>Output</strong>\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle();    // Shuffle the array [1,2,3] and return its result.\n                       // Any permutation of [1,2,3] must be equally likely to be returned.\n                       // Example: return [3, 1, 2]\nsolution.reset();      // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle();    // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 50</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>All the elements of <code>nums</code> are <strong>unique</strong>.</li>\n\t<li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/shuffle-an-array/solutions/",
    "solution": "[TOC]\n\n### Initial Thoughts\n\nNormally I would display more than two approaches, but shuffling is\ndeceptively easy to do _almost_ properly, and the Fisher-Yates algorithm is\nboth the canonical solution and asymptotically optimal.\n\nA few notes on randomness are necessary before beginning - both approaches\ndisplayed below assume that the languages' pseudorandom number generators\n(PRNGs) are sufficiently random. The sample code uses the simplest techniques\navailable for getting pseudorandom numbers, but for each possible permutation\nof the array to be truly equally likely, more care must be taken. For\nexample, an array of length $$n$$ has $$n!$$ distinct permutations. Therefore, in\norder to encode all permutations in an integer space, $$\\lceil lg(n!)\\rceil$$\nbits are necessary, which may not be guaranteed by the default PRNG.\n\n### Approach #1 Brute Force [Accepted]\n\n**Intuition**\n\nIf we put each number in a \"hat\" and draw them out at random, the order in\nwhich we draw them will define a random ordering.\n\n**Algorithm**\n\nThe brute force algorithm essentially puts each number in the aforementioned\n\"hat\", and draws them at random (without replacement) until there are none\nleft. Mechanically, this is performed by copying the contents of `array` into\na second auxiliary array named `aux` before overwriting each element of\n`array` with a randomly selected one from `aux`. After selecting each random\nelement, it is removed from `aux` to prevent duplicate draws. The\nimplementation of `reset` is simple, as we just store the original state of\n`nums` on construction.\n\nThe correctness of the algorithm follows from the fact that an element\n(without loss of generality) is equally likely to be selected during all\niterations of the `for` loop. To prove this, observe that the probability of a\nparticular element $$e$$ being chosen on the $$k$$th iteration (indexed from 0)\nis simply $$P(e$$ being chosen during the $$k$$th iteration$$)\\cdot P(e$$ not being\nchosen before the $$k$$th iteration$$)$$. Given that the array to be shuffled has\n$$n$$ elements, this probability is more concretely stated as the following:\n\n$$\n   \\frac{1}{n-k} \\cdot \\prod_{i=1}^{k} \\frac{n-i}{n-i+1}\n$$\n\nWhen expanded (and rearranged), it looks like this (for sufficiently large\n$$k$$):\n\n$$\n   (\\frac{n-1}{n}\n   \\cdot \\frac{n-2}{n-1}\n   \\cdot (\\ldots)\n   \\cdot \\frac{n-k+1}{n-k+2}\n   \\cdot \\frac{n-k}{n-k+1})\n   \\cdot \\frac{1}{n-k}\n$$\n\nFor the base case ($$k = 0$$), it is trivial to see that\n$$\\frac{1}{n-k} = \\frac{1}{n}$$. For $$k > 0$$, the numerator of each fraction\ncan be cancelled with the denominator of the next, leaving the $$n$$ from the\n0th draw as the only uncancelled denominator. Therefore, no matter on which\ndraw an element is drawn, it is drawn with a $$\\frac{1}{n}$$ chance, so each\narray permutation is equally likely to arise.\n\n<iframe src=\"https://leetcode.com/playground/NMKmaSiN/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"NMKmaSiN\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$\\mathcal{O}(n^2)$$\n\n    The quadratic time complexity arises from the calls to `list.remove` (or\n    `list.pop`), which run in linear time. $$n$$ linear list removals occur,\n    which results in a fairly easy quadratic analysis.\n\n* Space complexity : $$\\mathcal{O}(n)$$\n\n    Because the problem also asks us to implement `reset`, we must use linear\n    additional space to store the original array. Otherwise, it would be lost\n    upon the first call to `shuffle`.\n\n---\n\n### Approach #2 Fisher-Yates Algorithm [Accepted]\n\n**Intuition**\n\nWe can cut down the time and space complexities of `shuffle` with a bit of\ncleverness - namely, by swapping elements around within the array itself, we\ncan avoid the linear space cost of the auxiliary array and the linear time\ncost of list modification.\n\n**Algorithm**\n\nThe Fisher-Yates algorithm is remarkably similar to the brute force solution.\nOn each iteration of the algorithm, we generate a random integer between the\ncurrent index and the last index of the array. Then, we swap the elements at\nthe current index and the chosen index - this simulates drawing (and\nremoving) the element from the hat, as the next range from which we select a\nrandom index will not include the most recently processed one. One small, yet important\ndetail is that it is possible to swap an element with itself - otherwise, some\narray permutations would be more likely than others. To see this illustrated more\nclearly, consider the animation below:\n\n!?!../Documents/384_Shuffle_an_Array.json:697,161!?!\n\n<iframe src=\"https://leetcode.com/playground/nhPu5mbP/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"nhPu5mbP\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$\\mathcal{O}(n)$$\n\n    The Fisher-Yates algorithm runs in linear time, as generating a random\n    index and swapping two values can be done in constant time.\n\n* Space complexity : $$\\mathcal{O}(n)$$\n\n    Although we managed to avoid using linear space on the auxiliary array\n    from the brute force approach, we still need it for `reset`, so we're\n    stuck with linear space complexity.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self, nums: List[int]):\n    self.nums = nums\n\n  def reset(self) -> List[int]:\n    \"\"\"\n    Resets the array to its original configuration and return it.\n    \"\"\"\n    return self.nums\n\n  def shuffle(self) -> List[int]:\n    \"\"\"\n    Returns a random shuffling of the array.\n    \"\"\"\n    A = self.nums.copy()\n    for i in range(len(A) - 1, 0, -1):\n      j = randint(0, i)\n      A[i], A[j] = A[j], A[i]\n    return A",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int[] nums) {\n    this.nums = nums;\n  }\n\n  /** Resets the array to its original configuration and return it. */\n  public int[] reset() {\n    return nums;\n  }\n\n  /** Returns a random shuffling of the array. */\n  public int[] shuffle() {\n    int[] A = nums.clone();\n    for (int i = A.length - 1; i > 0; --i) {\n      final int j = rand.nextInt(i + 1);\n      swap(A, i, j);\n    }\n    return A;\n  }\n\n  private int[] nums;\n  private Random rand = new Random();\n\n  private void swap(int[] A, int i, int j) {\n    final int temp = A[i];\n    A[i] = A[j];\n    A[j] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(vector<int>& nums) : nums(move(nums)) {}\n\n  /** Resets the array to its original configuration and return it. */\n  vector<int> reset() {\n    return nums;\n  }\n\n  /** Returns a random shuffling of the array. */\n  vector<int> shuffle() {\n    vector<int> A(nums);\n    for (int i = A.size() - 1; i > 0; --i) {\n      const int j = rand() % (i + 1);\n      swap(A[i], A[j]);\n    }\n    return A;\n  }\n\n private:\n  vector<int> nums;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/384.html",
    "category": "Algorithms",
    "acceptance_rate": 58.97071923870991,
    "topics": [
      "Array",
      "Math",
      "Design",
      "Randomized"
    ],
    "hints": [
      "The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)"
    ],
    "likes": 1387,
    "dislikes": 941,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"364.7K\", \"totalSubmission\": \"618.5K\", \"totalAcceptedRaw\": 364746, \"totalSubmissionRaw\": 618523, \"acRate\": \"59.0%\"}",
    "title_pt": "Embaralhar um Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, projete um algoritmo para embaralhar aleatoriamente o array. Todas as permutações do array devem ser <strong>igualmente prováveis</strong> como resultado do embaralhamento.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(int[] nums)</code> Inicializa o objeto com o array de inteiros <code>nums</code>.</li>\n\t<li><code>int[] reset()</code> Redefine o array para sua configuração original e o retorna.</li>\n\t<li><code>int[] shuffle()</code> Retorna um embaralhamento aleatório do array.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;]\n[[[1, 2, 3]], [], [], []]\n<strong>Output</strong>\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle();    // Embaralha o array [1,2,3] e retorna seu resultado.\n                       // Qualquer permutação de [1,2,3] deve ser igualmente provável de ser retornada.\n                       // Exemplo: retorne [3, 1, 2]\nsolution.reset();      // Redefine o array de volta para sua configuração original [1,2,3]. Retorne [1, 2, 3]\nsolution.shuffle();    // Retorna o embaralhamento aleatório do array [1,2,3]. Exemplo: retorne [1, 3, 2]\n\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 50</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>Todos os elementos de <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas <strong>no total</strong> serão feitas para <code>reset</code> e <code>shuffle</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: A solução espera que sempre usemos o array original para `shuffle()`; caso contrário, alguns dos casos de teste falham. (Créditos; @snehasingh31)"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "385",
    "paidOnly": false,
    "title": "Mini Parser",
    "titleSlug": "mini-parser",
    "url": "https://leetcode.com/problems/mini-parser",
    "description_url": "https://leetcode.com/problems/mini-parser/description/",
    "description": "<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p>\n\n<p>Each element is either an integer or a list whose elements may also be integers or other lists.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;324&quot;\n<strong>Output:</strong> 324\n<strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot;\n<strong>Output:</strong> [123,[456,[789]]]\n<strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements:\n1. An integer containing value 123.\n2. A nested list containing two elements:\n    i.  An integer containing value 456.\n    ii. A nested list with one element:\n         a. An integer containing value 789\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li>\n\t<li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li>\n\t<li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/mini-parser/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def deserialize(self, s: str) -> NestedInteger:\n    if s[0] != '[':\n      return NestedInteger(int(s))\n\n    stack = []\n\n    for i, c in enumerate(s):\n      if c == '[':\n        stack.append(NestedInteger())\n        start = i + 1\n      elif c == ',':\n        if i > start:\n          num = int(s[start:i])\n          stack[-1].add(NestedInteger(num))\n        start = i + 1\n      elif c == ']':\n        popped = stack.pop()\n        if i > start:\n          num = int(s[start:i])\n          popped.add(NestedInteger(num))\n        if stack:\n          stack[-1].add(popped)\n        else:\n          return popped\n        start = i + 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public NestedInteger deserialize(String s) {\n    if (s.charAt(0) != '[')\n      return new NestedInteger(Integer.parseInt(s));\n\n    Deque<NestedInteger> stack = new ArrayDeque<>();\n    int start = 1;\n\n    for (int i = 0; i < s.length(); ++i)\n      switch (s.charAt(i)) {\n        case '[':\n          stack.push(new NestedInteger());\n          start = i + 1;\n          break;\n        case ',':\n          if (i > start) {\n            final int num = Integer.parseInt(s.substring(start, i));\n            stack.peek().add(new NestedInteger(num));\n          }\n          start = i + 1;\n          break;\n        case ']':\n          NestedInteger popped = stack.pop();\n          if (i > start) {\n            final int num = Integer.parseInt(s.substring(start, i));\n            popped.add(new NestedInteger(num));\n          }\n          if (!stack.isEmpty())\n            stack.peek().add(popped);\n          else\n            return popped;\n          start = i + 1;\n          break;\n      }\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  NestedInteger deserialize(string s) {\n    if (s[0] != '[')\n      return NestedInteger(stoi(s));\n\n    stack<NestedInteger> stack;\n    int start;  // The start index of num\n\n    for (int i = 0; i < s.length(); ++i) {\n      switch (s[i]) {\n        case '[':\n          stack.push(NestedInteger());\n          start = i + 1;\n          break;\n        case ',':\n          if (i > start) {\n            const int num = stoi(s.substr(start, i));\n            stack.top().add(NestedInteger(num));\n          }\n          start = i + 1;\n          break;\n        case ']':\n          NestedInteger popped = stack.top();\n          stack.pop();\n          if (i > start) {\n            const int num = stoi(s.substr(start, i));\n            popped.add(NestedInteger(num));\n          }\n          if (stack.empty())\n            return popped;\n          else\n            stack.top().add(popped);\n          start = i + 1;\n          break;\n      }\n    }\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/385.html",
    "category": "Algorithms",
    "acceptance_rate": 39.99850486852188,
    "topics": [
      "String",
      "Stack",
      "Depth-First Search"
    ],
    "hints": [],
    "likes": 473,
    "dislikes": 1455,
    "similar_questions": "[{\"title\": \"Flatten Nested List Iterator\", \"titleSlug\": \"flatten-nested-list-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ternary Expression Parser\", \"titleSlug\": \"ternary-expression-parser\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Remove Comments\", \"titleSlug\": \"remove-comments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"64.2K\", \"totalSubmission\": \"160.5K\", \"totalAcceptedRaw\": 64206, \"totalSubmissionRaw\": 160521, \"acRate\": \"40.0%\"}",
    "title_pt": "Mini Parser",
    "description_pt": "<p>Dada uma string s que representa a serialização de uma lista encadeada aninhada, implemente um parser para desserializá-la e retorne <em>o</em> <code>NestedInteger</code> <em>desserializado</em>.</p>\n\n<p>Cada elemento é ou um inteiro ou uma lista cujos elementos também podem ser inteiros ou outras listas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;324&quot;\n<strong>Saída:</strong> 324\n<strong>Explicação:</strong> Você deve retornar um objeto NestedInteger que contém um único inteiro 324.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;[123,[456,[789]]]&quot;\n<strong>Saída:</strong> [123,[456,[789]]]\n<strong>Explicação:</strong> Retorne um objeto NestedInteger contendo uma lista aninhada com 2 elementos:\n1. Um inteiro contendo o valor 123.\n2. Uma lista aninhada contendo dois elementos:\n    i.  Um inteiro contendo o valor 456.\n    ii. Uma lista aninhada com um elemento:\n         a. Um inteiro contendo o valor 789\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste em dígitos, colchetes <code>&quot;[]&quot;</code>, sinal de negativo <code>&#39;-&#39;</code>, e vírgulas <code>&#39;,&#39;</code>.</li>\n\t<li><code>s</code> é a serialização de um <code>NestedInteger</code> válido.</li>\n\t<li>Todos os valores na entrada estão no intervalo <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "386",
    "paidOnly": false,
    "title": "Lexicographical Numbers",
    "titleSlug": "lexicographical-numbers",
    "url": "https://leetcode.com/problems/lexicographical-numbers",
    "description_url": "https://leetcode.com/problems/lexicographical-numbers/description/",
    "description": "<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p>\n\n<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 13\n<strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> [1,2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/lexicographical-numbers/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe need to create a list of integers from 1 to $n$ and sort them in lexicographical order. Lexicographical order is similar to dictionary order, where the sequence is based on how words are arranged alphabetically. For numbers, this means sorting them as if they were strings. For example, `'10'` comes before `'2'` because `'1'` is less than `'2'`.\n\nThe solution must be efficient, with a time complexity of $O(n)$. This means the algorithm should handle the input size directly without any nested loops that could slow it down. Additionally, the solution should use constant extra space, $O(1)$, which means it should not require extra memory beyond the output list itself.\n\n---\n\n### Approach 1: DFS Approach\n\n#### Intuition\n\nWe can think of generating numbers in lexicographical order by imagining how they would appear in a dictionary. The first number is `1`, followed by `10`, `11`, `12`, and so on, before moving to `2`, then `20`, `21`, and so forth. The key is that smaller numbers starting with a particular digit should be fully explored before moving to the next starting digit.\n\nNow, to translate this thinking into an algorithm, consider each number as part of a tree. For instance, `1` has children like `10`, `11`, `12`, and so on, while `2` has children `20`, `21`, and so forth. This naturally suggests a depth-first search (DFS) approach: we explore each number and its children before moving to the next digit.\n\nWe start with the numbers `1` through `9` as the roots of the tree. For each of these, we generate their children by appending digits from `0` to `9`, as long as the resulting number remains within the range `[1, n]`. Once we exhaust one branch (e.g., numbers starting with `1` that exceed `n`), we move to the next root (i.e., `2`) and repeat the process. In this way, we progressively build the lexicographical order.\n\n\n![lexico_tree](../Figures/386/lexico_tree.png)\n\n\n#### Algorithm\n\n- Initialize an empty array `lexicographicalNumbers` to store the result.\n\n- Iterate over each starting number from 1 to 9:\n  - For each `start`, call `generateLexicalNumbers` with the current `start`, limit `n`, and `lexicographicalNumbers` array.\n\n- `generateLexicalNumbers` function:\n  - If `currentNumber` exceeds the `limit`, return from the function to stop recursion.\n\n  - Add the `currentNumber` to the `result` array.\n\n  - Iterate over digits from 0 to 9 to try appending them to `currentNumber`:\n    - Calculate `nextNumber` by appending the digit to `currentNumber`.\n    - If `nextNumber` is within the `limit`, recursively call `generateLexicalNumbers` with `nextNumber`, `limit`, and `result`.\n    - If `nextNumber` exceeds the `limit`, break the loop to avoid unnecessary further recursion.\n\n- Return the `lexicographicalNumbers` array containing numbers in lexicographical order.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/hwyuzUDB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"hwyuzUDB\"></iframe>\n\n#### Complexity Analysis\n\n- Time Complexity: $O(n)$\n\n    The algorithm generates all numbers from 1 to n in lexicographical order. Each number is visited exactly once and added to the result list. The total number of operations is proportional to the number of elements generated, which is n.\n\n- Space Complexity: $O(\\log_{10}(n))$\n\n    We only consider the recursion stack depth. The depth of recursion is proportional to the number of digits $d$ in $n$. Given that the maximum value for $n$ is 50,000, the maximum number of digits $d$ is 5. Thus, the recursion stack depth and corresponding space complexity is $O(d)$, which simplifies to $O(\\log_{10}(n))$, but with a maximum constant value of 5 for practical constraints. It can also be argued as $O(1)$. This is because, when substituting $n$ as 50,000, the result is approximately 5 (specifically $4.698970004336$), which is extremely small and does not significantly affect the overall complexity in this range.\n\n> The space complexity analysis does not account for the result list itself, as the problem requires returning a list with $n$ elements. Since we are only storing the elements in the list without performing additional operations on it, the space used by the list is not considered in the complexity analysis.\n\n---\n\n### Approach 2: Iterative Approach\n\n#### Intuition\n\nWe can do the same thing iterative, the overall concept remains the same as DFS approach. The difference will be how we organize and implement it.\n\nWe initialize the current number as `1`, which is the first number in lexicographical order, and set up a loop that runs `n` times because we want to generate exactly `n` numbers.\n\nIn each iteration, we add the current number to the result list. After that, we check if we can go deeper by multiplying the current number by `10`, appending a zero to the current number, giving us the lexicographically smallest possible next number. If the result is still less than or equal to `n`, we update the current number to this new value and continue.\n\nIf multiplying by `10` would exceed `n`, we increment the current number. However, this increment can’t always happen directly. If the current number ends in `9` or goes beyond the next \"root\" (like moving from `19` to `2`), we divide by `10` to move up a level and strip off the last digit. This way we make sure we don’t skip any numbers.\n\nAfter incrementing, if the new current number ends in a zero (like `20`), we continue removing zeroes, dividing by `10`, until we get a valid number. This ensures we stay in lexicographical order as we move forward.\n\nThis way we mimic the way we would manually write numbers in lexicographical order. We move from one number to the next by considering when to go deeper (appending digits) and when to backtrack (moving to the next root). Unlike the recursive method, which builds numbers by diving into each tree branch, this way it keeps track of the current number and adjusts it directly, making it more space efficient to be specfic no speace overhead and in $O(n)$ time.\n\n#### Algorithm\n\n- Initialize an empty array `lexicographicalNumbers` to store the results.\n- Start with `currentNumber` set to 1.\n\n- Generate numbers from 1 to `n`:\n  - Add `currentNumber` to the `lexicographicalNumbers` array.\n  \n  - If multiplying `currentNumber` by 10 is less than or equal to `n` (i.e., `currentNumber * 10 <= n`), multiply `currentNumber` by 10 to move to the next lexicographical number (i.e., go deeper into the tree of numbers).\n\n  - Otherwise:\n    - Adjust `currentNumber` to move to the next valid lexicographical number:\n      - While `currentNumber` ends with a 9 or is greater than or equal to `n`:\n        - Divide `currentNumber` by 10 to remove the last digit.\n      - Increment `currentNumber` by 1 to move to the next number in the sequence.\n\n- Return the `lexicographicalNumbers` array containing the numbers in lexicographical order from 1 to `n`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/jTcVTqVh/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"jTcVTqVh\"></iframe>\n\n#### Complexity Analysis\n\n- Time Complexity: $O(n)$\n\n    The algorithm generates numbers in lexicographical order and iterates up to $n$ times to populate the `lexicographicalNumbers` array. Each iteration involves constant-time operations (checking conditions and updating `currentNumber`). Thus, the time complexity is linear in terms of $n$.\n\n- Space Complexity: $O(1)$\n\n    The algorithm uses a constant amount of additional space for variables like `currentNumber` and loop counters. Therefore, the space complexity is $O(1)$.\n\n> The space complexity analysis does not account for the result list itself, as the problem requires returning a list with $n$ elements. Since we are only storing the elements in the list without performing additional operations on it, the space used by the list is not considered in the complexity analysis.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> lexicalOrder(int n) {\n    List<Integer> ans = new ArrayList<>();\n    int curr = 1;\n\n    while (ans.size() < n) {\n      ans.add(curr);\n      if (curr * 10 <= n) {\n        curr *= 10;\n      } else {\n        while (curr % 10 == 9 || curr == n)\n          curr /= 10;\n        ++curr;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> lexicalOrder(int n) {\n    vector<int> ans;\n    int curr = 1;\n\n    while (ans.size() < n) {\n      ans.push_back(curr);\n      if (curr * 10 <= n) {\n        curr *= 10;\n      } else {\n        while (curr % 10 == 9 || curr == n)\n          curr /= 10;\n        ++curr;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/386.html",
    "category": "Algorithms",
    "acceptance_rate": 73.0939223493458,
    "topics": [
      "Depth-First Search",
      "Trie"
    ],
    "hints": [],
    "likes": 2731,
    "dislikes": 191,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"266.9K\", \"totalSubmission\": \"365.2K\", \"totalAcceptedRaw\": 266920, \"totalSubmissionRaw\": 365174, \"acRate\": \"73.1%\"}",
    "title_pt": "Números em Ordem Lexicográfica",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne todos os números no intervalo <code>[1, n]</code> ordenados em ordem lexicográfica.</p>\n\n<p>Você deve escrever um algoritmo que execute em tempo <code>O(n)</code> e use <code>O(1)</code> de espaço extra.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 13\n<strong>Saída:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> [1,2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "387",
    "paidOnly": false,
    "title": "First Unique Character in a String",
    "titleSlug": "first-unique-character-in-a-string",
    "url": "https://leetcode.com/problems/first-unique-character-in-a-string",
    "description_url": "https://leetcode.com/problems/first-unique-character-in-a-string/description/",
    "description": "<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;leetcode&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;loveleetcode&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">2</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">s = &quot;aabb&quot;</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">-1</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/first-unique-character-in-a-string/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Linear time solution\n\nThe best possible solution here could be of a linear time because to ensure that the character is unique you have to check the whole string anyway. \n\nThe idea is to go through the string and save in a hash map the number of times each character appears in the string. That would take $$\\mathcal{O}(N)$$ time, where `N` is the number of characters in the string.\n \nThen we go through the string the second time, this time we use the hash map as a reference to check if a character is unique or not. If the character is unique, one could just return its index. The complexity of the second iteration is $$\\mathcal{O}(N)$$ as well.\n\n!?!../Documents/387_LIS.json:1000,621!?!\n\n<iframe src=\"https://leetcode.com/playground/e6zf5RKZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"361\" name=\"e6zf5RKZ\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$\\mathcal{O}(N)$$ since we go through the string of length `N` two times. \n* Space complexity: $$\\mathcal{O}(1)$$ because English alphabet contains 26 letters.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def firstUniqChar(self, s: str) -> int:\n    count = Counter(s)\n\n    for i, c in enumerate(s):\n      if count[c] == 1:\n        return i\n\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int firstUniqChar(String s) {\n    int[] count = new int[128];\n\n    for (final char c : s.toCharArray())\n      ++count[c];\n\n    for (int i = 0; i < s.length(); ++i)\n      if (count[s.charAt(i)] == 1)\n        return i;\n\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int firstUniqChar(string s) {\n    vector<int> count(128);\n\n    for (const char c : s)\n      ++count[c];\n\n    for (int i = 0; i < s.length(); ++i)\n      if (count[s[i]] == 1)\n        return i;\n\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/387.html",
    "category": "Algorithms",
    "acceptance_rate": 63.536479014065165,
    "topics": [
      "Hash Table",
      "String",
      "Queue",
      "Counting"
    ],
    "hints": [],
    "likes": 9272,
    "dislikes": 312,
    "similar_questions": "[{\"title\": \"Sort Characters By Frequency\", \"titleSlug\": \"sort-characters-by-frequency\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"First Letter to Appear Twice\", \"titleSlug\": \"first-letter-to-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"3.1M\", \"totalAcceptedRaw\": 1988953, \"totalSubmissionRaw\": 3130414, \"acRate\": \"63.5%\"}",
    "title_pt": "Primeiro Caractere Único em uma String",
    "description_pt": "<p>Dada uma string <code>s</code>, encontre o <strong>primeiro</strong> caractere não repetido nela e retorne seu índice. Se ele <strong>não</strong> existir, retorne <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;leetcode&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>O caractere <code>&#39;l&#39;</code> no índice 0 é o primeiro caractere que não ocorre em nenhum outro índice.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;loveleetcode&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">2</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">s = &quot;aabb&quot;</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">-1</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "388",
    "paidOnly": false,
    "title": "Longest Absolute File Path",
    "titleSlug": "longest-absolute-file-path",
    "url": "https://leetcode.com/problems/longest-absolute-file-path",
    "description_url": "https://leetcode.com/problems/longest-absolute-file-path/description/",
    "description": "<p>Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:</p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg\" style=\"width: 681px; height: 322px;\" /></p>\n\n<p>Here, we have <code>dir</code> as the only directory in the root. <code>dir</code> contains two subdirectories, <code>subdir1</code> and <code>subdir2</code>. <code>subdir1</code> contains a file <code>file1.ext</code> and subdirectory <code>subsubdir1</code>. <code>subdir2</code> contains a subdirectory <code>subsubdir2</code>, which contains a file <code>file2.ext</code>.</p>\n\n<p>In text form, it looks like this (with ⟶ representing the tab character):</p>\n\n<pre>\ndir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext\n</pre>\n\n<p>If we were to write this representation in code, it will look like this: <code>&quot;dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext&quot;</code>. Note that the <code>&#39;\\n&#39;</code> and <code>&#39;\\t&#39;</code> are the new-line and tab characters.</p>\n\n<p>Every file and directory has a unique <strong>absolute path</strong> in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by <code>&#39;/&#39;s</code>. Using the above example, the <strong>absolute path</strong> to <code>file2.ext</code> is <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form <code>name.extension</code>, where <code>name</code> and <code>extension</code> consist of letters, digits, and/or spaces.</p>\n\n<p>Given a string <code>input</code> representing the file system in the explained format, return <em>the length of the <strong>longest absolute path</strong> to a <strong>file</strong> in the abstracted file system</em>. If there is no file in the system, return <code>0</code>.</p>\n\n<p><strong>Note</strong> that the testcases are generated such that the file system is valid and no file or directory name has length 0.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg\" style=\"width: 401px; height: 202px;\" />\n<pre>\n<strong>Input:</strong> input = &quot;dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext&quot;\n<strong>Output:</strong> 20\n<strong>Explanation:</strong> We have only one file, and the absolute path is &quot;dir/subdir2/file.ext&quot; of length 20.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg\" style=\"width: 641px; height: 322px;\" />\n<pre>\n<strong>Input:</strong> input = &quot;dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext&quot;\n<strong>Output:</strong> 32\n<strong>Explanation:</strong> We have two files:\n&quot;dir/subdir1/file1.ext&quot; of length 21\n&quot;dir/subdir2/subsubdir2/file2.ext&quot; of length 32.\nWe return 32 since it is the longest absolute path to a file.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> input = &quot;a&quot;\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> We do not have any files, just a single directory named &quot;a&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>input</code> may contain lowercase or uppercase English letters, a new line character <code>&#39;\\n&#39;</code>, a tab character <code>&#39;\\t&#39;</code>, a dot <code>&#39;.&#39;</code>, a space <code>&#39; &#39;</code>, and digits.</li>\n\t<li>All file and directory names have <strong>positive</strong> length.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-absolute-file-path/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int depth;\n  public int length;\n  public T(int depth, int length) {\n    this.depth = depth;\n    this.length = length;\n  }\n}\n\nclass Solution {\n  public int lengthLongestPath(String input) {\n    int ans = 0;\n    Deque<T> stack = new ArrayDeque<>();\n    stack.push(new T(-1, 0));\n\n    for (String token : input.split(\"\\n\")) {\n      final int depth = getDepth(token);\n      token = token.replace(\"\\t\", \"\");\n      while (depth <= stack.peek().depth)\n        stack.pop();\n      if (token.contains(\".\")) // File\n        ans = Math.max(ans, stack.peek().length + token.length());\n      else // Directory + '/'\n        stack.push(new T(depth, stack.peek().length + token.length() + 1));\n    }\n\n    return ans;\n  }\n\n  private int getDepth(final String token) {\n    return (int) token.chars().filter(c -> c == '\\t').count();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int depth;\n  size_t length;\n  T(int depth, size_t length) : depth(depth), length(length) {}\n};\n\nclass Solution {\n public:\n  int lengthLongestPath(string input) {\n    size_t ans = 0;\n    stack<T> stack{{{-1, 0}}};  // Placeholder\n    istringstream iss(input);\n\n    for (string token; getline(iss, token, '\\n');) {\n      const int depth =\n          count_if(begin(token), end(token), [](char c) { return c == '\\t'; });\n      token.erase(remove(begin(token), end(token), '\\t'), end(token));\n      while (depth <= stack.top().depth)\n        stack.pop();\n      if (isFile(token))\n        ans = max(ans, stack.top().length + token.length());\n      else  // Directory + '/'\n        stack.emplace(depth, stack.top().length + token.length() + 1);\n    }\n\n    return ans;\n  }\n\n private:\n  bool isFile(const string& token) {\n    return token.find('.') != string::npos;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/388.html",
    "category": "Algorithms",
    "acceptance_rate": 48.29365873174635,
    "topics": [
      "String",
      "Stack",
      "Depth-First Search"
    ],
    "hints": [],
    "likes": 1338,
    "dislikes": 2559,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"169K\", \"totalSubmission\": \"349.9K\", \"totalAcceptedRaw\": 168994, \"totalSubmissionRaw\": 349930, \"acRate\": \"48.3%\"}",
    "title_pt": "Caminho Absoluto Mais Longo de Arquivo",
    "description_pt": "<p>Suponha que temos um sistema de arquivos que armazena tanto arquivos quanto diretórios. Um exemplo de um sistema é representado na figura a seguir:</p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/mdir.jpg\" style=\"width: 681px; height: 322px;\" /></p>\n\n<p>Aqui, temos <code>dir</code> como o único diretório na raiz. <code>dir</code> contém dois subdiretórios, <code>subdir1</code> e <code>subdir2</code>. <code>subdir1</code> contém um arquivo <code>file1.ext</code> e o subdiretório <code>subsubdir1</code>. <code>subdir2</code> contém um subdiretório <code>subsubdir2</code>, que contém um arquivo <code>file2.ext</code>.</p>\n\n<p>Em forma de texto, fica assim (com ⟶ representando o caractere de tabulação):</p>\n\n<pre>\ndir\n⟶ subdir1\n⟶ ⟶ file1.ext\n⟶ ⟶ subsubdir1\n⟶ subdir2\n⟶ ⟶ subsubdir2\n⟶ ⟶ ⟶ file2.ext\n</pre>\n\n<p>Se fôssemos escrever essa representação em código, ela ficaria assim: <code>&quot;dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\tsubsubdir2\\n\\t\\t\\tfile2.ext&quot;</code>. Observe que <code>&#39;\\n&#39;</code> e <code>&#39;\\t&#39;</code> são os caracteres de nova linha e tabulação.</p>\n\n<p>Cada arquivo e diretório tem um <strong>caminho absoluto</strong> único no sistema de arquivos, que é a sequência de diretórios que devem ser abertos para alcançar o próprio arquivo/diretório, todos concatenados por <code>&#39;/&#39;s</code>. Usando o exemplo acima, o <strong>caminho absoluto</strong> para <code>file2.ext</code> é <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Cada nome de diretório consiste em letras, dígitos e/ou espaços. Cada nome de arquivo está na forma <code>name.extension</code>, em que <code>name</code> e <code>extension</code> consistem em letras, dígitos e/ou espaços.</p>\n\n<p>Dada uma string <code>input</code> representando o sistema de arquivos no formato explicado, retorne <em>o comprimento do <strong>caminho absoluto mais longo</strong> para um <strong>arquivo</strong> no sistema de arquivos abstraído</em>. Se não houver nenhum arquivo no sistema, retorne <code>0</code>.</p>\n\n<p><strong>Nota</strong> que os casos de teste são gerados de modo que o sistema de arquivos é válido e nenhum nome de arquivo ou diretório tem comprimento 0.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/dir1.jpg\" style=\"width: 401px; height: 202px;\" />\n<pre>\n<strong>Entrada:</strong> input = &quot;dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext&quot;\n<strong>Saída:</strong> 20\n<strong>Explicação:</strong> Temos apenas um arquivo, e o caminho absoluto é &quot;dir/subdir2/file.ext&quot; com comprimento 20.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/28/dir2.jpg\" style=\"width: 641px; height: 322px;\" />\n<pre>\n<strong>Entrada:</strong> input = &quot;dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext&quot;\n<strong>Saída:</strong> 32\n<strong>Explicação:</strong> Temos dois arquivos:\n&quot;dir/subdir1/file1.ext&quot; com comprimento 21\n&quot;dir/subdir2/subsubdir2/file2.ext&quot; com comprimento 32.\nRetornamos 32, pois ele é o caminho absoluto mais longo para um arquivo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> input = &quot;a&quot;\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Não გვაქვს nenhum arquivo, apenas um único diretório chamado &quot;a&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>input</code> pode conter letras maiúsculas ou minúsculas do alfabeto inglês, um caractere de nova linha <code>&#39;\\n&#39;</code>, um caractere de tabulação <code>&#39;\\t&#39;</code>, um ponto <code>&#39;.&#39;</code>, um espaço <code>&#39; &#39;</code> e dígitos.</li>\n\t<li>Todos os nomes de arquivos e diretórios têm comprimento <strong>positivo</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "389",
    "paidOnly": false,
    "title": "Find the Difference",
    "titleSlug": "find-the-difference",
    "url": "https://leetcode.com/problems/find-the-difference",
    "description_url": "https://leetcode.com/problems/find-the-difference/description/",
    "description": "<p>You are given two strings <code>s</code> and <code>t</code>.</p>\n\n<p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p>\n\n<p>Return the letter that was added to <code>t</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot;\n<strong>Output:</strong> &quot;e&quot;\n<strong>Explanation:</strong> &#39;e&#39; is the letter that was added.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot;\n<strong>Output:</strong> &quot;y&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>t.length == s.length + 1</code></li>\n\t<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-the-difference/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findTheDifference(self, s: str, t: str) -> str:\n    count = Counter(s)\n\n    for i, c in enumerate(t):\n      count[c] -= 1\n      if count[c] == -1:\n        return c",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public char findTheDifference(String s, String t) {\n    char ans = 0;\n\n    for (final char c : s.toCharArray())\n      ans ^= c;\n\n    for (final char c : t.toCharArray())\n      ans ^= c;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  char findTheDifference(string s, string t) {\n    char ans = 0;\n\n    for (const char c : s)\n      ans ^= c;\n\n    for (const char c : t)\n      ans ^= c;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/389.html",
    "category": "Algorithms",
    "acceptance_rate": 59.702125365337736,
    "topics": [
      "Hash Table",
      "String",
      "Bit Manipulation",
      "Sorting"
    ],
    "hints": [],
    "likes": 5199,
    "dislikes": 495,
    "similar_questions": "[{\"title\": \"Single Number\", \"titleSlug\": \"single-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Permutation Difference between Two Strings\", \"titleSlug\": \"permutation-difference-between-two-strings\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"897K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 896950, \"totalSubmissionRaw\": 1502376, \"acRate\": \"59.7%\"}",
    "title_pt": "Encontrar a Diferença",
    "description_pt": "<p>Você recebe duas strings <code>s</code> e <code>t</code>.</p>\n\n<p>A string <code>t</code> é gerada embaralhando aleatoriamente a string <code>s</code> e então adicionando mais uma letra em uma posição aleatória.</p>\n\n<p>Retorne a letra que foi adicionada a <code>t</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot;\n<strong>Saída:</strong> &quot;e&quot;\n<strong>Explicação:</strong> &#39;e&#39; é a letra que foi adicionada.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;&quot;, t = &quot;y&quot;\n<strong>Saída:</strong> &quot;y&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>t.length == s.length + 1</code></li>\n\t<li><code>s</code> e <code>t</code> consistem em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "390",
    "paidOnly": false,
    "title": "Elimination Game",
    "titleSlug": "elimination-game",
    "url": "https://leetcode.com/problems/elimination-game",
    "description_url": "https://leetcode.com/problems/elimination-game/description/",
    "description": "<p>You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>:</p>\n\n<ul>\n\t<li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li>\n\t<li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li>\n\t<li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li>\n</ul>\n\n<p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 9\n<strong>Output:</strong> 6\n<strong>Explanation:</strong>\narr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>]\narr = [2, <u>4</u>, 6, <u>8</u>]\narr = [<u>2</u>, 6]\narr = [6]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/elimination-game/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int lastRemaining(int n) {\n    return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int lastRemaining(int n) {\n    return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/390.html",
    "category": "Algorithms",
    "acceptance_rate": 44.7451725229503,
    "topics": [
      "Math",
      "Recursion"
    ],
    "hints": [],
    "likes": 1645,
    "dislikes": 733,
    "similar_questions": "[{\"title\": \"Min Max Game\", \"titleSlug\": \"min-max-game\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"87.6K\", \"totalSubmission\": \"195.9K\", \"totalAcceptedRaw\": 87637, \"totalSubmissionRaw\": 195858, \"acRate\": \"44.7%\"}",
    "title_pt": "Jogo da Eliminação",
    "description_pt": "<p>Você tem uma lista <code>arr</code> de todos os inteiros no intervalo <code>[1, n]</code> ordenados em ordem estritamente crescente. Aplique o seguinte algoritmo em <code>arr</code>:</p>\n\n<ul>\n\t<li>Começando da esquerda para a direita, remova o primeiro número e todo número alternado depois dele até alcançar o final da lista.</li>\n\t<li>Repita o passo anterior novamente, mas desta vez da direita para a esquerda, remova o número mais à direita e todo número alternado dentre os números restantes.</li>\n\t<li>Continue repetindo os passos novamente, alternando entre esquerda para a direita e direita para a esquerda, até que reste um único número.</li>\n</ul>\n\n<p>Dado o inteiro <code>n</code>, retorne <em>o último número que permanece em</em> <code>arr</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 9\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong>\narr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>]\narr = [2, <u>4</u>, 6, <u>8</u>]\narr = [<u>2</u>, 6]\narr = [6]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "391",
    "paidOnly": false,
    "title": "Perfect Rectangle",
    "titleSlug": "perfect-rectangle",
    "url": "https://leetcode.com/problems/perfect-rectangle",
    "description_url": "https://leetcode.com/problems/perfect-rectangle/description/",
    "description": "<p>Given an array <code>rectangles</code> where <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> represents an axis-aligned rectangle. The bottom-left point of the rectangle is <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and the top-right point of it is <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p>\n\n<p>Return <code>true</code> <em>if all the rectangles together form an exact cover of a rectangular region</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> All 5 rectangles together form an exact cover of a rectangular region.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Input:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Because there is a gap between the two rectangular regions.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Because two of the rectangles overlap with each other.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>rectangles[i].length == 4</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/perfect-rectangle/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isRectangleCover(int[][] rectangles) {\n    int area = 0;\n    int x1 = Integer.MAX_VALUE;\n    int y1 = Integer.MAX_VALUE;\n    int x2 = Integer.MIN_VALUE;\n    int y2 = Integer.MIN_VALUE;\n    Set<String> corners = new HashSet<>();\n\n    for (int[] r : rectangles) {\n      area += (r[2] - r[0]) * (r[3] - r[1]);\n      x1 = Math.min(x1, r[0]);\n      y1 = Math.min(y1, r[1]);\n      x2 = Math.max(x2, r[2]);\n      y2 = Math.max(y2, r[3]);\n\n      // Four points of current rectangle\n      String[] points = new String[] {\n        r[0] + \" \" + r[1],\n        r[0] + \" \" + r[3],\n        r[2] + \" \" + r[1],\n        r[2] + \" \" + r[3]\n      };\n      for (final String point : points)\n        if (!corners.add(point))\n          corners.remove(point);\n    }\n\n    if (corners.size() != 4)\n      return false;\n    if (!corners.contains(x1 + \" \" + y1) ||\n        !corners.contains(x1 + \" \" + y2) ||\n        !corners.contains(x2 + \" \" + y1) ||\n        !corners.contains(x2 + \" \" + y2))\n      return false;\n\n    return area == (x2 - x1) * (y2 - y1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isRectangleCover(vector<vector<int>>& rectangles) {\n    int area = 0;\n    int x1 = INT_MAX;\n    int y1 = INT_MAX;\n    int x2 = INT_MIN;\n    int y2 = INT_MIN;\n    unordered_set<string> corners;\n\n    for (const vector<int>& r : rectangles) {\n      area += (r[2] - r[0]) * (r[3] - r[1]);\n      x1 = min(x1, r[0]);\n      y1 = min(y1, r[1]);\n      x2 = max(x2, r[2]);\n      y2 = max(y2, r[3]);\n\n      // Four points of current rectangle\n      const vector<string> points{to_string(r[0]) + \" \" + to_string(r[1]),\n                                  to_string(r[0]) + \" \" + to_string(r[3]),\n                                  to_string(r[2]) + \" \" + to_string(r[1]),\n                                  to_string(r[2]) + \" \" + to_string(r[3])};\n      for (const string& point : points)\n        if (!corners.insert(point).second)\n          corners.erase(point);\n    }\n\n    if (corners.size() != 4)\n      return false;\n    if (!corners.count(to_string(x1) + \" \" + to_string(y1)) ||\n        !corners.count(to_string(x1) + \" \" + to_string(y2)) ||\n        !corners.count(to_string(x2) + \" \" + to_string(y1)) ||\n        !corners.count(to_string(x2) + \" \" + to_string(y2)))\n      return false;\n\n    return area == (x2 - x1) * (y2 - y1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/391.html",
    "category": "Algorithms",
    "acceptance_rate": 35.05767869289393,
    "topics": [
      "Array",
      "Line Sweep"
    ],
    "hints": [],
    "likes": 912,
    "dislikes": 119,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"50.5K\", \"totalSubmission\": \"144.1K\", \"totalAcceptedRaw\": 50509, \"totalSubmissionRaw\": 144074, \"acRate\": \"35.1%\"}",
    "title_pt": "Retângulo Perfeito",
    "description_pt": "<p>Dado um array <code>rectangles</code> em que <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> representa um retângulo alinhado aos eixos. O ponto inferior esquerdo do retângulo é <code>(x<sub>i</sub>, y<sub>i</sub>)</code> e o ponto superior direito dele é <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p>\n\n<p>Retorne <code>true</code> <em>se todos os retângulos, juntos, formarem uma cobertura exata de uma região retangular</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perectrec1-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Entrada:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Todos os 5 retângulos juntos formam uma cobertura exata de uma região retangular.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perfectrec2-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Entrada:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Porque há uma lacuna entre as duas regiões retangulares.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/27/perfecrrec4-plane.jpg\" style=\"width: 300px; height: 294px;\" />\n<pre>\n<strong>Entrada:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Porque dois dos retângulos se sobrepõem entre si.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>rectangles[i].length == 4</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "392",
    "paidOnly": false,
    "title": "Is Subsequence",
    "titleSlug": "is-subsequence",
    "url": "https://leetcode.com/problems/is-subsequence",
    "description_url": "https://leetcode.com/problems/is-subsequence/description/",
    "description": "<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"abc\", t = \"ahbgdc\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"axc\", t = \"ahbgdc\"\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?",
    "solution_url": "https://leetcode.com/problems/is-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isSubsequence(String s, String t) {\n    if (s.isEmpty())\n      return true;\n\n    int i = 0;\n    for (final char c : t.toCharArray())\n      if (s.charAt(i) == c && ++i == s.length())\n        return true;\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isSubsequence(string s, string t) {\n    if (s.empty())\n      return true;\n\n    int i = 0;\n    for (const char c : t)\n      if (s[i] == c && ++i == s.length())\n        return true;\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/392.html",
    "category": "Algorithms",
    "acceptance_rate": 48.3245468110204,
    "topics": [
      "Two Pointers",
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 10234,
    "dislikes": 576,
    "similar_questions": "[{\"title\": \"Number of Matching Subsequences\", \"titleSlug\": \"number-of-matching-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Way to Form String\", \"titleSlug\": \"shortest-way-to-form-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Append Characters to String to Make Subsequence\", \"titleSlug\": \"append-characters-to-string-to-make-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Make String a Subsequence Using Cyclic Increments\", \"titleSlug\": \"make-string-a-subsequence-using-cyclic-increments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2040989, \"totalSubmissionRaw\": 4223504, \"acRate\": \"48.3%\"}",
    "title_pt": "Subsequência",
    "description_pt": "<p>Dadas duas strings <code>s</code> e <code>t</code>, retorne <code>true</code><em> se </em><code>s</code><em> for uma <strong>subsequência</strong> de </em><code>t</code><em>, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>Uma <strong>subsequência</strong> de uma string é uma nova string formada a partir da string original pela remoção de alguns (pode ser nenhum) dos caracteres, sem perturbar as posições relativas dos caracteres restantes. (isto é, <code>&quot;ace&quot;</code> é uma subsequência de <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> enquanto <code>&quot;aec&quot;</code> não é).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"abc\", t = \"ahbgdc\"\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"axc\", t = \"ahbgdc\"\n<strong>Saída:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> e <code>t</code> consistem apenas de letras minúsculas do inglês.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Suponha que haja muitas <code>s</code> de entrada, digamos <code>s_1</code>, <code>s_2</code>, ..., <code>s_k</code> em que <code>k &gt;= 10<sup>9</sup></code>, e você queira verificar uma por uma se <code>t</code> tem sua subsequência. Nesse cenário, como você mudaria seu código?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "393",
    "paidOnly": false,
    "title": "UTF-8 Validation",
    "titleSlug": "utf-8-validation",
    "url": "https://leetcode.com/problems/utf-8-validation",
    "description_url": "https://leetcode.com/problems/utf-8-validation/description/",
    "description": "<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p>\n\n<p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p>\n\n<ol>\n\t<li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li>\n\t<li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li>\n</ol>\n\n<p>This is how the UTF-8 encoding would work:</p>\n\n<pre>\n     Number of Bytes   |        UTF-8 Octet Sequence\n                       |              (binary)\n   --------------------+-----------------------------------------\n            1          |   0xxxxxxx\n            2          |   110xxxxx 10xxxxxx\n            3          |   1110xxxx 10xxxxxx 10xxxxxx\n            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n</pre>\n\n<p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p>\n\n<p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> data = [197,130,1]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> data = [235,140,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that&#39;s correct.\nBut the second continuation byte does not start with 10, so it is invalid.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= data[i] &lt;= 255</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/utf-8-validation/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n### Overview\n\nThis is an interesting problem to work with especially because it is not really hard to code up a solution for, but, you really need to pay attention to the details of the problem. A lot of people trying to solve the problem tend to miss out on small details that are mentioned and end up getting 1 or 2 test cases wrong.\n\n**Note:** The following section provides 3 different examples for the problem and explains them. If the test cases and the rules are clear to you, you can skip over the `Approach 1`.\n\nThe problem statement provides 2 different examples for you to understand the rules to define a valid UTF-8 charset. That might not be enough for a lot of people and so the first thing we would do is try to understand all the rules given in the problem statement and in the meantime look at a few examples in detail that will help clarify the problem. Here are the rules in the question statement:\n\n* A valid UTF-8 character can be `1 - 4` bytes long.\n* For a `1-byte` character, the first bit is a `0`, followed by its unicode.\n* For an `n-bytes` character, the first `n-bits` are all ones, the `n+1` bit is 0, followed by `n-1` bytes with most significant 2 bits being `10`.\n* The input given would be an array of integers containing the data. We have to return if the data in the array represents a valid UTF-8 encoding. The important thing to note here is that the array doesn't contain data for **just a single character**. As can be seen from the first example, the array can contain data for multiple characters all of which can be valid UTF-8 characters and hence the charset represented by the array is valid.\n\nNow that we have our rules defined for us, let us first look at the examples in the question and then some other examples from the discussion section that seem to cause a lot of confusion.\n\n#### Example 1\n\n<pre>\ndata = [197, 130, 1]\n</pre>\n\nLet us look at the octet sequence represented by the integers in this array. So, the octet sequence would be as follows:\n\n<pre>\n11000101 10000010 00000001\n</pre>\n\n> Remember, for an n-bytes UTF-8 character, the first n-bits would be 1 followed by a 0 in the n+1 bit. Then,\n> the next n - 1 bytes would all have 10 as their most significant bits.\n\n<pre>\n[1 1 0] 0 0 1 0 1\n ↑   ↑\n</pre>\n\nClearly, we can see that the 2 most significant bits of this byte are 1s and they are followed by a 0. This implies the start of a valid UTF-8 character. The information that we can gather from this byte is that this is a 2-byte UTF-8 character. This means that the next byte in the sequence must follow the pattern `10xxxxxx`. Let's see if it does.\n\n<pre>\n[1 1 0] 0 0 1 0 1    [1 0] 0 0 0 0 1 0\n ↑   ↑                ↑ ↑\n</pre>\n\nYes, it does follow the intended sequence and hence the first two integers in the array i.e. `197 130` combine to form a valid 2-byte UTF-8 character. Since there are more elements left in the array, we move on and check them in a similar fashion as we did with the numbers above. The next integer in the array is `1`. Let's look at the binary representation for this integer.\n\n<pre>\n00000001\n</pre>\n\nSince the most significant bit itself of this number is a `0`, the only rule it satisfies is the 1-byte UTF-8 character rule. Let's re-iterate the rule:\n\n> For 1-byte character, the first bit or the most significant but is a 0, followed by its unicode code.\n\n<pre>\n[0] 0 0 0 0 0 0 1\n ↑\n</pre>\n\nClearly, the integer `1` is a valid 1-byte UTF-8 character in itself. Since there are no more elements left in the array to process, we will return `True` since there were two characters present in the array and both of them were valid UTF-8 encoded characters.\n\n\n#### Example 2\n\n<pre>\n[235, 140, 4]\n</pre>\n\nThis is the second example that's mentioned in the problem statement.  As before, let us look at the binary representation of the integers in the array.\n\n<pre>\n11101011 10001100 00000100\n</pre>\n\nLet's start with the first integer in our array. The first byte will tell us the length of the UTF-8 character and hence the number of bytes we have to process in all in order to completely process a single UTF-8 character in the array before moving on to another one.\n\n<pre>\n[1 1 1 0] 1 0 1 1\n ↑     ↑\n</pre>\n\nSo, the first few bits of the byte above are `1110`. This means that our UTF-8 character is of `3 bytes` in all. Remember the rule that helps us identify the size of a potential UTF-8 character from it's first byte.\n\n> For an `n-bytes` character, the first `n-bits` are all one's, the `n+1` bit is 0.\n\nFollowing this rule we determined that the first UTF-8 character is of 3 bytes. Since we are done processing one byte of data, we are left with 2 other bytes of data to process before starting with another UTF-8 character. Let's look at the remaining two bytes of the array.\n\n<pre>\n[1 0] 0 0 1 1 0 0       0 0 0 0 0 1 0 0\n ↑ ↑                    ↑ (WRONG!)\n</pre>\n\nThe first byte above follows our pattern of `10xxxxxx` but the second byte does not. We had to verify a UTF-8 encoded 3-byte character as we saw from the first byte of the sequence `11101011`. The final byte is something that doesn't adhere to our rules mentioned before. Since we found an invalid byte, we can simply return `False` and we don't need to process any data further.\n\n#### Example 3\n\nWe will look at one final example before moving onto the solution for this problem. This example has caused a lot of confusion as can be seen from multiple posts on the discussion forum:\n\n* [Discussion Post - 1](https://leetcode.com/problems/utf-8-validation/discuss/87451/The-problem-description-is-super-vague-to-me.)\n* [Discussion Post - 2](https://leetcode.com/problems/utf-8-validation/discuss/147353/250145145145145-seems-valid-yet-the-testcase-flags-that-as-invalid)\n* [Discussion Post - 3](https://leetcode.com/problems/utf-8-validation/discuss/87452/2749-pass-Python-easy-to-understand-don't-understand-why-case-250-145-145-145-145-need-return-false)\n\nSo, the example is:\n\n<pre>\n[250,145,145,145,145]\n</pre>\n\nLet us look at the binary representation of all the integers in the array.\n\n<pre>\n11111010 10010001 10010001 10010001 10010001\n</pre>\n\nAs we have been doing in the previous two examples, let us look at the first byte of data to determine how many number of bytes our UTF-8 encoded character will have. Looking at the first byte of data we can see that our first UTF-8 encoded character in the sequence of data given, is of `5 bytes`.\n\n<pre>\n[1 1 1 1 1 0] 1 0\n ↑         ↑  \n</pre>\n\nIf this is a valid UTF-8 encoded character, the following four bytes of data should be in accordance with the pattern `10xxxxxx`. Let's look at the next 4 bytes of data one on each line.\n\n<pre>\n1. [1 0] 0 1 0 0 0 1\n2. [1 0] 0 1 0 0 0 1\n3. [1 0] 0 1 0 0 0 1\n4. [1 0] 0 1 0 0 0 1\n</pre>\n\nAs we can see above, all the 4 bytes are in accordance with the rules specified in the problem. Why then the result for this specific test case, `False`? People tend to miss out on one of the rules mentioned in the problem.\n\n> This is the first rule in the problem statement and it clearly says that \"A valid UTF-8 character can be 1 - 4 bytes long.\"\n\nThe first byte of data indicates that the UTF-8 encoded character contains `5 bytes` of data which cannot be true. This is why the answer for this specific test case is `False`.\n\nHopefully, most of your doubts would have been cleared by the three examples that we looked at above. Let us now move on to the solution(s) for this problem.\n<br/>\n<br/>\n\n---\n\n### Approach 1: String Manipulation.\n\n#### Intuition\n\nThe problem itself is not that complicated. As long as we adhere to the rules specified in the problem, we should be fine. So, let's jump straight in and look at the algorithm.\n\n#### Algorithm\n\n1. Start processing the integers in the given array one by one.\n2. For every integer, obtain the binary representation in the `string format`. Since integers can be very large, we should only keep/consider the `8 least significant bits` of data and discard the rest as mentioned in the problem statement. After this step, you should have 8-bits or 1-byte string representation for the integer. Let the string we get here be called `bin_rep`.\n3. There are two scenarios that we need to consider here in the next step.\n    1. One is that we are in the middle of processing some UTF-8 encoded character. In this case we simply need to check the first two bits of the string and see if they are `10` i.e. the 2 most significant bits of the integer being `1 and 0`. `bin_rep[:2] == \"10\"`\n    2. The other case is that we already processed some valid UTF-8 characters and we have to start processing a new UTF-8 character. In that case we have to look at a prefix of the string representation and look at the number of `1`s that we encounter before encountering a `0`. This will tell us the size of the next UTF-8 character.\n4. We keep on processing the integers of the array in this way until we either end up processing all of them or we find an invalid scenario.\n\nLet us move on to the implementation of this algorithm.\n\n<iframe src=\"https://leetcode.com/playground/QuH4GHKM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"QuH4GHKM\"></iframe>\n\n\n#### Complexity analysis\n\n* Time Complexity : $O(N)$ since we process each integer of the array and for each integer we obtain an 8 character string which we then use for further processing. Overall the complexity is $O(N)$ considering $N$ is the number of integers in the array.\n* Space Complexity: $O(N)$ since for every integer we create a new string that we play around with.\n<br/>\n<br/>\n\n---\n\n### Approach 2: Bit Manipulation\n\n#### Intuition\n\nThe previous solution is exactly what the problem asks us to do except that the string conversion and manipulation takes a lot of time and that is something unnecessary. We can make use of bit manipulation to perform the same task.\n\n#### Algorithm\n\nLet us look at what parts of a byte corresponding to an integer do we need to process.\n\n1. If it is the starting byte for a UTF-8 character, then we need to process the first $N$ bits where $N$ will be at max 4. Anything more than that and we would have an invalid character.\n2. In case the byte is a part of a UTF-8 character, then we simply need to check the first two bits or the most significant bits. The most significant bit needs to be a `1` and the second most significant bit needs to be a `0`.\n\nLet's see how we can make use of bit manipulation to perform both of these tasks.\n\n<pre>\nmask = 1 << 7\nwhile mask & num:\n    n_bytes += 1\n    mask = mask >> 1\n</pre>\n\nSo, we have taken a mask = `1 << 7` which is basically `10000000`. We will make use of this mask and `logically and` it with the number to see if the bit at a particular position is set of not. We do this iteratively to check how many bits are set starting from the most significant bit (Remember, the integer might be too large but we should only process the 8 least significant bits of data.)\n\nTo check if the most significant bit is a `1` and the second most significant bit is a `0`, we can make use of the following two masks\n\n<pre>\nmask1 = 1 << 7\nmask2 = 1 << 6\n\nif not (num & mask1 and not (num & mask2)):\n    return False\n</pre>\n\nThe above code will simple use the `mask1` to check if the most significant bit is set to `1` and the second most significant bit is set to `0`. if this is not a case, then we return `False`.\n\nLet's move onto the implementation.\n\n<iframe src=\"https://leetcode.com/playground/2dkD5Wvb/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"2dkD5Wvb\"></iframe>\n\n#### Complexity analysis\n\n* Time Complexity : $O(N)$.\n* Space Complexity: $O(1)$.\n\n\n\n<br />\n<br />",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean validUtf8(int[] data) {\n    int leftToCheck = 0;\n\n    for (final int d : data)\n      if (leftToCheck == 0) {\n        if ((d >> 3) == 0b11110)\n          leftToCheck = 3;\n        else if ((d >> 4) == 0b1110)\n          leftToCheck = 2;\n        else if ((d >> 5) == 0b110)\n          leftToCheck = 1;\n        else if ((d >> 7) == 0b0)\n          leftToCheck = 0;\n        else\n          return false;\n      } else {\n        if ((d >> 6) != 0b10)\n          return false;\n        --leftToCheck;\n      }\n\n    return leftToCheck == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool validUtf8(vector<int>& data) {\n    int leftToCheck = 0;\n\n    for (const int d : data)\n      if (leftToCheck == 0) {\n        if ((d >> 3) == 0b11110)\n          leftToCheck = 3;\n        else if ((d >> 4) == 0b1110)\n          leftToCheck = 2;\n        else if ((d >> 5) == 0b110)\n          leftToCheck = 1;\n        else if ((d >> 7) == 0b0)\n          leftToCheck = 0;\n        else\n          return false;\n      } else {\n        if ((d >> 6) != 0b10)\n          return false;\n        --leftToCheck;\n      }\n\n    return leftToCheck == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/393.html",
    "category": "Algorithms",
    "acceptance_rate": 45.4834046850037,
    "topics": [
      "Array",
      "Bit Manipulation"
    ],
    "hints": [
      "Read the data integer by integer. When you read it, process the least significant 8 bits of it.",
      "Assume the next encoding is 1-byte data. If it is not 1-byte data, read the next integer and assume it is 2-bytes data.",
      "Similarly, if it is not 2-bytes data, try 3-bytes then 4-bytes. If you read four integers and it still does not match any pattern, return false."
    ],
    "likes": 931,
    "dislikes": 2881,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"131.5K\", \"totalSubmission\": \"289.2K\", \"totalAcceptedRaw\": 131528, \"totalSubmissionRaw\": 289178, \"acRate\": \"45.5%\"}",
    "title_pt": "Validação de UTF-8",
    "description_pt": "<p>Dado um array de inteiros <code>data</code> representando os dados, retorne se ele é uma codificação <strong>UTF-8</strong> válida (isto é, se ele se traduz em uma sequência de caracteres codificados em UTF-8 válidos).</p>\n\n<p>Um caractere em <strong>UTF8</strong> pode ter de <strong>1 a 4 bytes</strong> de comprimento, sujeito às seguintes regras:</p>\n\n<ol>\n\t<li>Para um caractere de <strong>1 byte</strong>, o primeiro bit é <code>0</code>, seguido pelo seu código Unicode.</li>\n\t<li>Para um caractere de <strong>n bytes</strong>, os primeiros <code>n</code> bits são todos <code>1</code>, o <code>n + 1</code>º bit é <code>0</code>, seguido por <code>n - 1</code> bytes com os <code>2</code> bits mais significativos sendo <code>10</code>.</li>\n</ol>\n\n<p>É assim que a codificação UTF-8 funcionaria:</p>\n\n<pre>\n     Number of Bytes   |        UTF-8 Octet Sequence\n                       |              (binary)\n   --------------------+-----------------------------------------\n            1          |   0xxxxxxx\n            2          |   110xxxxx 10xxxxxx\n            3          |   1110xxxx 10xxxxxx 10xxxxxx\n            4          |   11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n</pre>\n\n<p><code>x</code> denota um bit na forma binária de um byte que pode ser <code>0</code> ou <code>1</code>.</p>\n\n<p><strong>Nota: </strong>A entrada é um array de inteiros. Apenas os <strong>8 bits menos significativos</strong> de cada inteiro são usados para armazenar os dados. Isso significa que cada inteiro representa apenas 1 byte de dados.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> data = [197,130,1]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> data representa a sequência de octetos: 11000101 10000010 00000001.\nÉ uma codificação utf-8 válida para um caractere de 2 bytes seguido por um caractere de 1 byte.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> data = [235,140,4]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> data representa a sequência de octetos: 11101011 10001100 00000100.\nOs primeiros 3 bits são todos <code>1</code> e o 4º bit é <code>0</code>, o que significa que é um caractere de 3 bytes.\nO próximo byte é um byte de continuação que começa com <code>10</code> e isso está correto.\nMas o segundo byte de continuação não começa com <code>10</code>, então é inválido.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= data[i] &lt;= 255</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Leia os dados inteiro por inteiro. Quando você o ler, processe os 8 bits menos significativos dele.",
      "- Dica 2: Assuma que a próxima codificação é um dado de 1 byte. Se não for um dado de 1 byte, leia o próximo inteiro e assuma que ele é um dado de 2 bytes.",
      "- Dica 3: De forma similar, se não for um dado de 2 bytes, tente 3 bytes e então 4 bytes. Se você ler quatro inteiros e ainda assim ele não corresponder a nenhum padrão, retorne false."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "394",
    "paidOnly": false,
    "title": "Decode String",
    "titleSlug": "decode-string",
    "url": "https://leetcode.com/problems/decode-string",
    "description_url": "https://leetcode.com/problems/decode-string/description/",
    "description": "<p>Given an encoded string, return its decoded string.</p>\n\n<p>The encoding rule is: <code>k[encoded_string]</code>, where the <code>encoded_string</code> inside the square brackets is being repeated exactly <code>k</code> times. Note that <code>k</code> is guaranteed to be a positive integer.</p>\n\n<p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p>\n\n<p>The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;3[a]2[bc]&quot;\n<strong>Output:</strong> &quot;aaabcbc&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;3[a2[c]]&quot;\n<strong>Output:</strong> &quot;accaccacc&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;2[abc]3[cd]ef&quot;\n<strong>Output:</strong> &quot;abcabccdcdcdef&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 30</code></li>\n\t<li><code>s</code> consists of lowercase English letters, digits, and square brackets <code>&#39;[]&#39;</code>.</li>\n\t<li><code>s</code> is guaranteed to be <strong>a valid</strong> input.</li>\n\t<li>All the integers in <code>s</code> are in the range <code>[1, 300]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/decode-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def decodeString(self, s: str) -> str:\n    stack = []  # (prevStr, repeatCount)\n    currStr = ''\n    currNum = 0\n\n    for c in s:\n      if c.isdigit():\n        currNum = currNum * 10 + int(c)\n      else:\n        if c == '[':\n          stack.append((currStr, currNum))\n          currStr = ''\n          currNum = 0\n        elif c == ']':\n          prevStr, num = stack.pop()\n          currStr = prevStr + num * currStr\n        else:\n          currStr += c\n\n    return currStr",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String decodeString(String s) {\n    Stack<Pair<StringBuilder, Integer>> stack = new Stack<>(); // (prevStr, repeatCount)\n    StringBuilder currStr = new StringBuilder();\n    int currNum = 0;\n\n    for (final char c : s.toCharArray())\n      if (Character.isDigit(c)) {\n        currNum = currNum * 10 + (c - '0');\n      } else {\n        if (c == '[') {\n          stack.push(new Pair<>(currStr, currNum));\n          currStr = new StringBuilder();\n          currNum = 0;\n        } else if (c == ']') {\n          final Pair<StringBuilder, Integer> pair = stack.pop();\n          final StringBuilder prevStr = pair.getKey();\n          final int n = pair.getValue();\n          currStr = prevStr.append(getRepeatedStr(currStr, n));\n        } else {\n          currStr.append(c);\n        }\n      }\n\n    return currStr.toString();\n  }\n\n  // S * n times\n  private StringBuilder getRepeatedStr(StringBuilder s, int n) {\n    StringBuilder sb = new StringBuilder();\n    while (n-- > 0)\n      sb.append(s);\n    return sb;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string decodeString(string s) {\n    stack<pair<string, int>> stack;  // (prevStr, repeatCount)\n    string currStr;\n    int currNum = 0;\n\n    for (const char c : s)\n      if (isdigit(c)) {\n        currNum = currNum * 10 + (c - '0');\n      } else {\n        if (c == '[') {\n          stack.emplace(currStr, currNum);\n          currStr = \"\";\n          currNum = 0;\n        } else if (c == ']') {\n          const auto [prevStr, n] = stack.top();\n          stack.pop();\n          currStr = prevStr + getRepeatedStr(currStr, n);\n        } else {\n          currStr += c;\n        }\n      }\n\n    return currStr;\n  }\n\n private:\n  // S * n times\n  string getRepeatedStr(const string& s, int n) {\n    string repeat;\n    while (n--)\n      repeat += s;\n    return repeat;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/394.html",
    "category": "Algorithms",
    "acceptance_rate": 60.99507800947948,
    "topics": [
      "String",
      "Stack",
      "Recursion"
    ],
    "hints": [],
    "likes": 13332,
    "dislikes": 655,
    "similar_questions": "[{\"title\": \"Encode String with Shortest Length\", \"titleSlug\": \"encode-string-with-shortest-length\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Atoms\", \"titleSlug\": \"number-of-atoms\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Brace Expansion\", \"titleSlug\": \"brace-expansion\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1004028, \"totalSubmissionRaw\": 1646081, \"acRate\": \"61.0%\"}",
    "title_pt": "Decodificar String",
    "description_pt": "<p>Dada uma string codificada, retorne sua string decodificada.</p>\n\n<p>A regra de codificação é: <code>k[encoded_string]</code>, em que a <code>encoded_string</code> dentro dos colchetes é repetida exatamente <code>k</code> vezes. Observe que <code>k</code> tem garantia de ser um inteiro positivo.</p>\n\n<p>Você pode assumir que a string de entrada é sempre válida; não há espaços em branco extras, os colchetes estão bem formados, etc. Além disso, você pode assumir que os dados originais não contêm dígitos e que os dígitos são apenas para esses números de repetição, <code>k</code>. Por exemplo, não haverá entrada como <code>3a</code> ou <code>2[4]</code>.</p>\n\n<p>Os casos de teste são gerados de modo que o comprimento da saída nunca excederá <code>10<sup>5</sup></code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;3[a]2[bc]&quot;\n<strong>Saída:</strong> &quot;aaabcbc&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;3[a2[c]]&quot;\n<strong>Saída:</strong> &quot;accaccacc&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;2[abc]3[cd]ef&quot;\n<strong>Saída:</strong> &quot;abcabccdcdcdef&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 30</code></li>\n\t<li><code>s</code> consiste em letras minúsculas do alfabeto inglês, dígitos e colchetes <code>&#39;[]&#39;</code>.</li>\n\t<li><code>s</code> tem garantia de ser <strong>uma entrada válida</strong>.</li>\n\t<li>Todos os inteiros em <code>s</code> estão no intervalo <code>[1, 300]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "395",
    "paidOnly": false,
    "title": "Longest Substring with At Least K Repeating Characters",
    "titleSlug": "longest-substring-with-at-least-k-repeating-characters",
    "url": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters",
    "description_url": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/description/",
    "description": "<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p>\n\n<p data-pm-slice=\"1 1 []\">if no such substring exists, return 0.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aaabb&quot;, k = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;ababbc&quot;, k = 2\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n\n### Overview ####\n\n\nWe want to find the longest substring in a given string `s` where each character is repeated at least `k` times. This is an interesting problem that can be solved using different algorithm paradigms like Divide and Conquer and the Sliding Window Approach. We will start by discussing the brute force approach, moving towards more efficient implementations.\n\nLet's discuss each approach in detail.\n\n---\n\n### Approach 1: Brute Force\n\n**Intuition**\n\nThe naive approach would be to generate all possible substrings for a given string `s`. For each substring, we must check if all the characters are repeated at least `k` times. Among all the substrings that satisfy the given condition, return the length of the longest substring.\n\n**Algorithm**\n\n- Generate substrings from string `s` starting at index `start` and ending at index `end`.\n- Use the `countMap` array to store the frequency of each character in the substring.\n- The `isValid` method uses `countMap` to check whether every character in substring has at least `k` frequency.\n- Track the maximum substring length and return the result.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/AEM7Ua5M/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"AEM7Ua5M\"></iframe>\n\n**Complexity Analysis**\n\n- Time Complexity : $$\\mathcal{O}(n^{2})$$, where $$n$$ is equal to length of string $$s$$. The nested for loop that generates all substrings from string $$s$$ takes $$\\mathcal{O}(n^{2})$$ time, and for each substring, we iterate over $$\\text{countMap}$$ array of size $$26$$.\nThis gives us time complexity as  $$\\mathcal{O}(26 \\cdot n^{2})$$ = $$\\mathcal{O}(n^{2})$$.\n\n This approach is exhaustive and results in _Time Limit Exceeded (TLE)_.\n\n- Space Complexity: $$\\mathcal{O}(1)$$ We use constant extra space of size 26 for `countMap` array.\n\n---\n\n### Approach 2: Divide And Conquer\n\n**Intuition**\n\n[Divide and Conquer](https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm) is one of the popular strategies that work in 2 phases.\n - Divide the problem into subproblems. (Divide Phase).\n-  Repeatedly solve each subproblem independently and combine the result to solve the original problem. (Conquer Phase).\n\nWe could apply this strategy by recursively splitting the string into substrings and combine the result to find the longest substring that satisfies the given condition. The longest substring for a string starting at index `start` and ending at index `end` can be given by,\n\n```java\nlongestSustring(start, end) = max(longestSubstring(start, mid), longestSubstring(mid+1, end))\n```\n\n_Finding the split position `(mid)`_\n\nThe string would be split only when we find an invalid character. An invalid character is the one with a frequency of less than `k`. As we know, the invalid character cannot be part of the result, we split the string at the index where we find the invalid character, recursively check for each split, and combine the result.\n\n**Algorithm**\n\n- Build the `countMap` with the frequency of each character in the string `s`.\n- Find the position for `mid` index by iterating over the string. The `mid` index would be the first invalid character in the string.\n- Split the string into 2 substrings at the `mid` index and recursively find the result.\n\n> To make it more efficient, we ignore all the invalid characters after the mid index as well, thereby reducing the number of recursive calls.\n\n![img](../Figures/395/divide_and_conquer.png)\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/Pqj7pAV6/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"Pqj7pAV6\"></iframe>\n\n**Complexity Analysis**\n\n- Time Complexity : $$\\mathcal{O}(N ^ {2})$$, where $$N$$ is the length of string $$s$$. Though the algorithm performs better in most cases, the worst case time complexity is still $$\\mathcal{O}(N ^ {2})$$.\n\nIn cases where we perform split at every index, the maximum depth of recursive call could be $$\\mathcal{O}(N)$$. For each recursive call it takes $$\\mathcal{O}(N)$$ time to build the `countMap` resulting in $$\\mathcal{O}(n ^ {2})$$ time complexity.\n\n- Space Complexity: $$\\mathcal{O}(N)$$ This is the space used to store the recursive call stack. The maximum depth of recursive call stack would be $$\\mathcal{O}(N)$$.\n\n---\n\n### Approach 3: Sliding Window\n\n**Intuition**\n\nThere is another intuitive method to solve the problem by using the Sliding Window Approach. The sliding window slides over the string `s` and validates each character. Based on certain conditions, the sliding window either expands or shrinks.\n\nA substring is valid if each character has at least `k` frequency. The main idea is to find all the valid substrings with a different number of unique characters and track the maximum length. Let's look at the algorithm in detail.\n\n**Algorithm**\n\n1) Find the number of unique characters in the string `s` and store the count in variable `maxUnique`. For `s` = `aabcbacad`, the unique characters are `a,b,c,d` and `maxUnique = 4`.\n\n2)  Iterate over the string `s` with the value of `currUnique` ranging from `1` to `maxUnique`. In each iteration, `currUnique`  is the maximum number of unique characters that must be present in the sliding window.\n\n3) The sliding window starts at index `windowStart` and ends at index `windowEnd` and slides over string `s` until `windowEnd` reaches the end of string `s`. At any given point, we shrink or expand the window to ensure that the number of unique characters is not greater than `currUnique`.\n\n - If the number of unique character in the sliding window is less than or equal to `currUnique`, expand the window from the right by adding a character to the end of the window given by `windowEnd`\n\n- Otherwise, shrink the window from the left by removing a character from the start of the window given by `windowStart`.\n\n4) Keep track of the number of unique characters in the current sliding window having at least `k` frequency given by `countAtLeastK`. Update the result if all the characters in the window have at least `k` frequency.\n\n\n![img](../Figures/395/sliding_window.png)\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/87MVFsgQ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"87MVFsgQ\"></iframe>\n\n**Complexity Analysis**\n\n- Time Complexity : $$\\mathcal{O}(\\text{maxUnique} \\cdot N)$$. We iterate over the string of length $$N$$, $$\\text{maxUnqiue}$$ times. Ideally, the number of unique characters in the string would not be more than $$26$$ `(a to z)`. Hence, the time complexity is approximately $$\\mathcal{O}( 26 \\cdot N)$$ = $$\\mathcal{O}(N)$$\n\n- Space Complexity: $$\\mathcal{O}(1)$$ We use constant extra space of size 26 to store the `countMap`.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestSubstring(String s, int k) {\n    int ans = 0;\n\n    for (int n = 1; n <= 26; ++n)\n      ans = Math.max(ans, longestSubstringWithNUniqueCharacters(s, k, n));\n\n    return ans;\n  }\n\n  private int longestSubstringWithNUniqueCharacters(final String s, int k, int n) {\n    int ans = 0;\n    int uniqueChars = 0; // Unique chars in current substring s[l..r]\n    int noLessThanK = 0; // # of chars >= k\n    int[] count = new int[128];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (count[s.charAt(r)] == 0)\n        ++uniqueChars;\n      if (++count[s.charAt(r)] == k)\n        ++noLessThanK;\n      while (uniqueChars > n) {\n        if (count[s.charAt(l)] == k)\n          --noLessThanK;\n        if (--count[s.charAt(l)] == 0)\n          --uniqueChars;\n        ++l;\n      }\n      if (noLessThanK == n) // Unique chars also == n\n        ans = Math.max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestSubstring(string s, int k) {\n    int ans = 0;\n\n    for (int n = 1; n <= 26; ++n)\n      ans = max(ans, longestSubstringWithNUniqueCharacters(s, k, n));\n\n    return ans;\n  }\n\n private:\n  int longestSubstringWithNUniqueCharacters(const string& s, int k, int n) {\n    int ans = 0;\n    int uniqueChars = 0;  // # of unique chars in window\n    int noLessThanK = 0;  // # of chars >= k in window\n    vector<int> count(128);\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (count[s[r]] == 0)\n        ++uniqueChars;\n      if (++count[s[r]] == k)\n        ++noLessThanK;\n      while (uniqueChars > n) {\n        if (count[s[l]] == k)\n          --noLessThanK;\n        if (--count[s[l]] == 0)\n          --uniqueChars;\n        ++l;\n      }\n      if (noLessThanK == n)  // Unique chars also == n\n        ans = max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/395.html",
    "category": "Algorithms",
    "acceptance_rate": 45.414160433774434,
    "topics": [
      "Hash Table",
      "String",
      "Divide and Conquer",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 6469,
    "dislikes": 550,
    "similar_questions": "[{\"title\": \"Longest Subsequence Repeated k Times\", \"titleSlug\": \"longest-subsequence-repeated-k-times\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Equal Count Substrings\", \"titleSlug\": \"number-of-equal-count-substrings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Optimal Partition of String\", \"titleSlug\": \"optimal-partition-of-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Length of Longest Subarray With at Most K Frequency\", \"titleSlug\": \"length-of-longest-subarray-with-at-most-k-frequency\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Longest Special Substring That Occurs Thrice II\", \"titleSlug\": \"find-longest-special-substring-that-occurs-thrice-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Longest Special Substring That Occurs Thrice I\", \"titleSlug\": \"find-longest-special-substring-that-occurs-thrice-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"260.5K\", \"totalSubmission\": \"573.6K\", \"totalAcceptedRaw\": 260479, \"totalSubmissionRaw\": 573565, \"acRate\": \"45.4%\"}",
    "title_pt": "Maior Substring com Pelo Menos K Caracteres Repetidos",
    "description_pt": "<p>Dada uma string <code>s</code> e um inteiro <code>k</code>, retorne <em>o comprimento da maior substring de</em> <code>s</code> <em>tal que a frequência de cada caractere nesta substring seja maior ou igual a</em> <code>k</code>.</p>\n\n<p data-pm-slice=\"1 1 []\">se nenhuma substring desse tipo existir, retorne 0.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aaabb&quot;, k = 3\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A maior substring é &quot;aaa&quot;, pois &#39;a&#39; é repetido 3 vezes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;ababbc&quot;, k = 2\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> A maior substring é &quot;ababb&quot;, pois &#39;a&#39; é repetido 2 vezes e &#39;b&#39; é repetido 3 vezes.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do inglês.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "396",
    "paidOnly": false,
    "title": "Rotate Function",
    "titleSlug": "rotate-function",
    "url": "https://leetcode.com/problems/rotate-function",
    "description_url": "https://leetcode.com/problems/rotate-function/description/",
    "description": "<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p>\n\n<p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p>\n\n<ul>\n\t<li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li>\n</ul>\n\n<p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p>\n\n<p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,3,2,6]\n<strong>Output:</strong> 26\n<strong>Explanation:</strong>\nF(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [100]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/rotate-function/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxRotateFunction(self, nums: List[int]) -> int:\n    f = sum(i * num for i, num in enumerate(nums))\n    ans = f\n    summ = sum(nums)\n\n    for a in reversed(nums):\n      f += summ - len(nums) * a\n      ans = max(ans, f)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxRotateFunction(int[] nums) {\n    final int sum = Arrays.stream(nums).sum();\n    int f = 0;\n\n    // Calculate F(0) first\n    for (int i = 0; i < nums.length; ++i)\n      f += i * nums[i];\n\n    int ans = f;\n\n    for (int i = nums.length - 1; i >= 0; --i) {\n      f += sum - nums.length * nums[i];\n      ans = Math.max(ans, f);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxRotateFunction(vector<int>& nums) {\n    const int sum = accumulate(begin(nums), end(nums), 0);\n    int f = 0;\n\n    // Calculate F(0) first\n    for (int i = 0; i < nums.size(); ++i)\n      f += i * nums[i];\n\n    int ans = f;\n\n    for (int i = nums.size() - 1; i > 0; --i) {\n      f += sum - nums.size() * nums[i];\n      ans = max(ans, f);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/396.html",
    "category": "Algorithms",
    "acceptance_rate": 43.89342589727376,
    "topics": [
      "Array",
      "Math",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 1619,
    "dislikes": 273,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"97.9K\", \"totalSubmission\": \"223K\", \"totalAcceptedRaw\": 97874, \"totalSubmissionRaw\": 222981, \"acRate\": \"43.9%\"}",
    "title_pt": "Função de Rotação",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> de comprimento <code>n</code>.</p>\n\n<p>Assuma que <code>arr<sub>k</sub></code> seja um array obtido ao rotacionar <code>nums</code> por <code>k</code> posições no sentido horário. Definimos a <strong>função de rotação</strong> <code>F</code> sobre <code>nums</code> da seguinte forma:</p>\n\n<ul>\n\t<li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li>\n</ul>\n\n<p>Retorne <em>o valor máximo de</em> <code>F(0), F(1), ..., F(n-1)</code>.</p>\n\n<p>Os casos de teste são gerados de modo que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,3,2,6]\n<strong>Saída:</strong> 26\n<strong>Explicação:</strong>\nF(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nEntão o valor máximo de F(0), F(1), F(2), F(3) é F(3) = 26.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [100]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "397",
    "paidOnly": false,
    "title": "Integer Replacement",
    "titleSlug": "integer-replacement",
    "url": "https://leetcode.com/problems/integer-replacement",
    "description_url": "https://leetcode.com/problems/integer-replacement/description/",
    "description": "<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p>\n\n<ol>\n\t<li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li>\n\t<li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li>\n</ol>\n\n<p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 8\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 7\n<strong>Output:</strong> 4\n<strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1\nor 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 4\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/integer-replacement/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def integerReplacement(self, n: int) -> int:\n    ans = 0\n\n    while n > 1:\n      if (n & 1) == 0:\n        n >>= 1\n      elif n == 3 or ((n >> 1) & 1) == 0:\n        n -= 1\n      else:\n        n += 1\n      ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int integerReplacement(long n) {\n    int ans = 0;\n\n    for (; n > 1; ++ans)\n      if ((n & 1) == 0) // Ends w/ 0\n        n >>= 1;\n      else if (n == 3 || ((n >> 1) & 1) == 0) // N = 3 or ends w/ 01\n        --n;\n      else // Ends w/ 11\n        ++n;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int integerReplacement(long n) {\n    int ans = 0;\n\n    for (; n > 1; ++ans)\n      if ((n & 1) == 0)  // Ends w/ 0\n        n >>= 1;\n      else if (n == 3 || ((n >> 1) & 1) == 0)  // N = 3 or ends w/ 01\n        --n;\n      else  // Ends w/ 11\n        ++n;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/397.html",
    "category": "Algorithms",
    "acceptance_rate": 36.44443166881384,
    "topics": [
      "Dynamic Programming",
      "Greedy",
      "Bit Manipulation",
      "Memoization"
    ],
    "hints": [],
    "likes": 1370,
    "dislikes": 482,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"139.5K\", \"totalSubmission\": \"382.7K\", \"totalAcceptedRaw\": 139462, \"totalSubmissionRaw\": 382671, \"acRate\": \"36.4%\"}",
    "title_pt": "Substituição de Inteiro",
    "description_pt": "<p>Dado um inteiro positivo <code>n</code>,&nbsp;você pode aplicar uma das seguintes&nbsp;operações:</p>\n\n<ol>\n\t<li>Se <code>n</code> for par, substitua <code>n</code> por <code>n / 2</code>.</li>\n\t<li>Se <code>n</code> for ímpar, substitua <code>n</code> por <code>n + 1</code> ou <code>n - 1</code>.</li>\n</ol>\n\n<p>Retorne <em>o número mínimo de operações necessárias para que</em> <code>n</code> <em>se torne</em> <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 8\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 7\n<strong>Saída:</strong> 4\n<strong>Explicação: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1\nor 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 4\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "398",
    "paidOnly": false,
    "title": "Random Pick Index",
    "titleSlug": "random-pick-index",
    "url": "https://leetcode.com/problems/random-pick-index",
    "description_url": "https://leetcode.com/problems/random-pick-index/description/",
    "description": "<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li>\n\t<li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\n<strong>Output</strong>\n[null, 4, 0, 2]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>target</code> is an integer from <code>nums</code>.</li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/random-pick-index/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int[] nums) {\n    this.nums = nums;\n  }\n\n  public int pick(int target) {\n    int ans = -1;\n    int range = 0;\n\n    for (int i = 0; i < nums.length; ++i)\n      if (nums[i] == target && rand.nextInt(++range) == 0)\n        ans = i;\n\n    return ans;\n  }\n\n  private int[] nums;\n  private Random rand = new Random();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(vector<int>& nums) : nums(move(nums)) {}\n\n  int pick(int target) {\n    int ans = -1;\n    int range = 0;\n\n    for (int i = 0; i < nums.size(); ++i)\n      if (nums[i] == target && rand() % ++range == 0)\n        ans = i;\n\n    return ans;\n  }\n\n private:\n  vector<int> nums;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/398.html",
    "category": "Algorithms",
    "acceptance_rate": 64.44663227762679,
    "topics": [
      "Hash Table",
      "Math",
      "Reservoir Sampling",
      "Randomized"
    ],
    "hints": [],
    "likes": 1355,
    "dislikes": 1302,
    "similar_questions": "[{\"title\": \"Linked List Random Node\", \"titleSlug\": \"linked-list-random-node\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Random Pick with Blacklist\", \"titleSlug\": \"random-pick-with-blacklist\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Random Pick with Weight\", \"titleSlug\": \"random-pick-with-weight\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"278.9K\", \"totalSubmission\": \"432.7K\", \"totalAcceptedRaw\": 278858, \"totalSubmissionRaw\": 432696, \"acRate\": \"64.4%\"}",
    "title_pt": "Índice de Sorteio Aleatório",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> com possíveis <strong>duplicatas</strong>, produza aleatoriamente o índice de um número <code>target</code> fornecido. Você pode assumir que o número target fornecido deve existir no array.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(int[] nums)</code> Inicializa o objeto com o array <code>nums</code>.</li>\n\t<li><code>int pick(int target)</code> Escolhe um índice aleatório <code>i</code> de <code>nums</code> tal que <code>nums[i] == target</code>. Se houver múltiplos <code>i</code>s válidos, então cada índice deve ter a mesma probabilidade de ser retornado.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\n<strong>Saída</strong>\n[null, 4, 0, 2]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // Deve retornar aleatoriamente o índice 2, 3 ou 4. Cada índice deve ter a mesma probabilidade de ser retornado.\nsolution.pick(1); // Deve retornar 0. Como no array apenas nums[0] é igual a 1.\nsolution.pick(3); // Deve retornar aleatoriamente o índice 2, 3 ou 4. Cada índice deve ter a mesma probabilidade de ser retornado.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>target</code> é um inteiro de <code>nums</code>.</li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas a <code>pick</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "399",
    "paidOnly": false,
    "title": "Evaluate Division",
    "titleSlug": "evaluate-division",
    "url": "https://leetcode.com/problems/evaluate-division",
    "description_url": "https://leetcode.com/problems/evaluate-division/description/",
    "description": "<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p>\n\n<p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p>\n\n<p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p>\n\n<p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p>\n\n<p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]]\n<strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000]\n<strong>Explanation:</strong> \nGiven: <em>a / b = 2.0</em>, <em>b / c = 3.0</em>\nqueries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em>\nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnote: x is undefined =&gt; -1.0</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]]\n<strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]]\n<strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= equations.length &lt;= 20</code></li>\n\t<li><code>equations[i].length == 2</code></li>\n\t<li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li>\n\t<li><code>values.length == equations.length</code></li>\n\t<li><code>0.0 &lt; values[i] &lt;= 20.0</code></li>\n\t<li><code>1 &lt;= queries.length &lt;= 20</code></li>\n\t<li><code>queries[i].length == 2</code></li>\n\t<li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li>\n\t<li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/evaluate-division/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n    ans = []\n    # graph[A][B] := A / B\n    graph = defaultdict(dict)\n\n    for (A, B), value in zip(equations, values):\n      graph[A][B] = value\n      graph[B][A] = 1 / value\n\n    # Returns A / C\n    def devide(A: str, C: str, seen: Set[str]) -> float:\n      if A == C:\n        return 1.0\n\n      seen.add(A)\n\n      # Value := A / B\n      for B, value in graph[A].items():\n        if B in seen:\n          continue\n        res = devide(B, C, seen)  # B / C\n        if res > 0:  # Valid\n          return value * res  # (A / B) * (B / C) = A / C\n\n      return -1.0  # Invalid\n\n    for A, C in queries:\n      if A not in graph and C not in graph:\n        ans.append(-1.0)\n      else:\n        ans.append(devide(A, C, set()))\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public double[] calcEquation(List<List<String>> equations, double[] values,\n                               List<List<String>> queries) {\n    double[] ans = new double[queries.size()];\n    // Graph.get(A).get(B) := A / B\n    Map<String, Map<String, Double>> graph = new HashMap<>();\n\n    // Construct the graph\n    for (int i = 0; i < equations.size(); ++i) {\n      final String A = equations.get(i).get(0);\n      final String B = equations.get(i).get(1);\n      graph.putIfAbsent(A, new HashMap<>());\n      graph.putIfAbsent(B, new HashMap<>());\n      graph.get(A).put(B, values[i]);\n      graph.get(B).put(A, 1.0 / values[i]);\n    }\n\n    for (int i = 0; i < queries.size(); ++i) {\n      final String A = queries.get(i).get(0);\n      final String C = queries.get(i).get(1);\n      if (!graph.containsKey(A) || !graph.containsKey(C))\n        ans[i] = -1.0;\n      else\n        ans[i] = divide(graph, A, C, new HashSet<>());\n    }\n\n    return ans;\n  }\n\n  // Returns A / C\n  private double divide(Map<String, Map<String, Double>> graph, final String A, final String C,\n                        Set<String> seen) {\n    if (A.equals(C))\n      return 1.0;\n\n    seen.add(A);\n\n    for (final String B : graph.get(A).keySet()) {\n      if (seen.contains(B))\n        continue;\n      final double res = divide(graph, B, C, seen); // B / C\n      if (res > 0)                                  // Valid result\n        return graph.get(A).get(B) * res;           // A / C = (A / B) * (B / C)\n    }\n\n    return -1.0; // Invalid result\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<double> calcEquation(vector<vector<string>>& equations,\n                              vector<double>& values,\n                              vector<vector<string>>& queries) {\n    vector<double> ans;\n    // graph[A][B] := A / B\n    unordered_map<string, unordered_map<string, double>> graph;\n\n    for (int i = 0; i < equations.size(); ++i) {\n      const string& A = equations[i][0];\n      const string& B = equations[i][1];\n      graph[A][B] = values[i];\n      graph[B][A] = 1 / values[i];\n    }\n\n    for (const vector<string>& q : queries) {\n      const string& A = q[0];\n      const string& C = q[1];\n      if (!graph.count(A) || !graph.count(C))\n        ans.push_back(-1);\n      else\n        ans.push_back(divide(graph, A, C, unordered_set<string>()));\n    }\n\n    return ans;\n  }\n\n private:\n  // Returns A / C\n  double divide(\n      const unordered_map<string, unordered_map<string, double>>& graph,\n      const string& A, const string& C, unordered_set<string>&& seen) {\n    if (A == C)\n      return 1.0;\n\n    seen.insert(A);\n\n    // Value := A / B\n    for (const auto& [B, value] : graph.at(A)) {\n      if (seen.count(B))\n        continue;\n      const double res = divide(graph, B, C, move(seen));  // B / C\n      if (res > 0)                                         // Valid result\n        return value * res;  // A / C = (A / B) * (B / C)\n    }\n\n    return -1;  // Invalid result\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/399.html",
    "category": "Algorithms",
    "acceptance_rate": 63.00642596156292,
    "topics": [
      "Array",
      "String",
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Graph",
      "Shortest Path"
    ],
    "hints": [
      "Do you recognize this as a graph problem?"
    ],
    "likes": 9757,
    "dislikes": 1029,
    "similar_questions": "[{\"title\": \"Check for Contradictions in Equations\", \"titleSlug\": \"check-for-contradictions-in-equations\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximize Amount After Two Days of Conversions\", \"titleSlug\": \"maximize-amount-after-two-days-of-conversions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"594.6K\", \"totalSubmission\": \"943.7K\", \"totalAcceptedRaw\": 594568, \"totalSubmissionRaw\": 943666, \"acRate\": \"63.0%\"}",
    "title_pt": "Avaliar Divisão",
    "description_pt": "<p>Você recebe um array de pares de variáveis <code>equations</code> e um array de números reais <code>values</code>, onde <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> e <code>values[i]</code> representam a equação <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Cada <code>A<sub>i</sub></code> ou <code>B<sub>i</sub></code> é uma string que representa uma única variável.</p>\n\n<p>Você também recebe algumas <code>queries</code>, onde <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> representa a <code>j<sup>th</sup></code> consulta em que você deve encontrar a resposta para <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p>\n\n<p>Retorne <em>as respostas para todas as consultas</em>. Se uma única resposta não puder ser determinada, retorne <code>-1.0</code>.</p>\n\n<p><strong>Nota:</strong> A entrada é sempre válida. Você pode assumir que a avaliação das consultas não resultará em divisão por zero e que não há contradição.</p>\n\n<p><strong>Nota:&nbsp;</strong>As variáveis que não ocorrem na lista de equações são indefinidas, então a resposta não pode ser determinada para elas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]]\n<strong>Saída:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000]\n<strong>Explicação:</strong> \nDado: <em>a / b = 2.0</em>, <em>b / c = 3.0</em>\nas consultas são: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em>\nretorne: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnota: x é indefinida =&gt; -1.0</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]]\n<strong>Saída:</strong> [3.75000,0.40000,5.00000,0.20000]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]]\n<strong>Saída:</strong> [0.50000,2.00000,-1.00000,-1.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= equations.length &lt;= 20</code></li>\n\t<li><code>equations[i].length == 2</code></li>\n\t<li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li>\n\t<li><code>values.length == equations.length</code></li>\n\t<li><code>0.0 &lt; values[i] &lt;= 20.0</code></li>\n\t<li><code>1 &lt;= queries.length &lt;= 20</code></li>\n\t<li><code>queries[i].length == 2</code></li>\n\t<li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li>\n\t<li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Você reconhece isso como um problema de grafo?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "400",
    "paidOnly": false,
    "title": "Nth Digit",
    "titleSlug": "nth-digit",
    "url": "https://leetcode.com/problems/nth-digit",
    "description_url": "https://leetcode.com/problems/nth-digit/description/",
    "description": "<p>Given an integer <code>n</code>, return the <code>n<sup>th</sup></code> digit of the infinite integer sequence <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 11\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The 11<sup>th</sup> digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/nth-digit/solutions/",
    "solution": null,
    "solution_code_python": null,
    "solution_code_java": null,
    "solution_code_cpp": null,
    "solution_code_url": "https://leetcodehelp.github.io/400.html",
    "category": "Algorithms",
    "acceptance_rate": 35.595960382926094,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [],
    "likes": 1154,
    "dislikes": 2093,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"109.7K\", \"totalSubmission\": \"308K\", \"totalAcceptedRaw\": 109652, \"totalSubmissionRaw\": 308048, \"acRate\": \"35.6%\"}",
    "title_pt": "Enésimo Dígito",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne o <code>n<sup>ésimo</sup></code> dígito da sequência infinita de inteiros <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 11\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> O 11<sup>ésimo</sup> dígito da sequência 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... é um 0, que faz parte do número 10.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "401",
    "paidOnly": false,
    "title": "Binary Watch",
    "titleSlug": "binary-watch",
    "url": "https://leetcode.com/problems/binary-watch",
    "description_url": "https://leetcode.com/problems/binary-watch/description/",
    "description": "<p>A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent&nbsp;the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.</p>\n\n<ul>\n\t<li>For example, the below binary watch reads <code>&quot;4:51&quot;</code>.</li>\n</ul>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg\" style=\"width: 500px; height: 500px;\" /></p>\n\n<p>Given an integer <code>turnedOn</code> which represents the number of LEDs that are currently on (ignoring the PM), return <em>all possible times the watch could represent</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>The hour must not contain a leading zero.</p>\n\n<ul>\n\t<li>For example, <code>&quot;01:00&quot;</code> is not valid. It should be <code>&quot;1:00&quot;</code>.</li>\n</ul>\n\n<p>The minute must&nbsp;consist of two digits and may contain a leading zero.</p>\n\n<ul>\n\t<li>For example, <code>&quot;10:2&quot;</code> is not valid. It should be <code>&quot;10:02&quot;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> turnedOn = 1\n<strong>Output:</strong> [\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> turnedOn = 9\n<strong>Output:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= turnedOn &lt;= 10</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-watch/solutions/",
    "solution": null,
    "solution_code_python": null,
    "solution_code_java": null,
    "solution_code_cpp": null,
    "solution_code_url": "https://leetcodehelp.github.io/401.html",
    "category": "Algorithms",
    "acceptance_rate": 56.3718729517151,
    "topics": [
      "Backtracking",
      "Bit Manipulation"
    ],
    "hints": [
      "Simplify by seeking for solutions that involve comparing bit counts.",
      "Consider calculating all possible times for comparison purposes."
    ],
    "likes": 1490,
    "dislikes": 2732,
    "similar_questions": "[{\"title\": \"Letter Combinations of a Phone Number\", \"titleSlug\": \"letter-combinations-of-a-phone-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"165.1K\", \"totalSubmission\": \"292.9K\", \"totalAcceptedRaw\": 165127, \"totalSubmissionRaw\": 292926, \"acRate\": \"56.4%\"}",
    "title_pt": "Relógio Binário",
    "description_pt": "<p>Um relógio binário tem 4 LEDs na parte superior para representar as horas (0-11), e 6 LEDs na parte inferior para representar&nbsp;os minutos (0-59). Cada LED representa zero ou um, com o bit menos significativo à direita.</p>\n\n<ul>\n\t<li>Por exemplo, o relógio binário abaixo mostra <code>&quot;4:51&quot;</code>.</li>\n</ul>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/binarywatch.jpg\" style=\"width: 500px; height: 500px;\" /></p>\n\n<p>Dado um inteiro <code>turnedOn</code> que representa o número de LEDs que estão atualmente acesos (ignorando o PM), retorne <em>todos os horários possíveis que o relógio pode representar</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>A hora não deve conter zero à esquerda.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;01:00&quot;</code> não é válido. Deve ser <code>&quot;1:00&quot;</code>.</li>\n</ul>\n\n<p>O minuto deve&nbsp;consistir de dois dígitos e pode conter um zero à esquerda.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;10:2&quot;</code> não é válido. Deve ser <code>&quot;10:02&quot;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> turnedOn = 1\n<strong>Saída:</strong> [&quot;0:01&quot;,&quot;0:02&quot;,&quot;0:04&quot;,&quot;0:08&quot;,&quot;0:16&quot;,&quot;0:32&quot;,&quot;1:00&quot;,&quot;2:00&quot;,&quot;4:00&quot;,&quot;8:00&quot;]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> turnedOn = 9\n<strong>Saída:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= turnedOn &lt;= 10</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Simplifique buscando soluções que envolvam comparar contagens de bits.",
      "Dica 2: Considere calcular todos os horários possíveis para fins de comparação."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "402",
    "paidOnly": false,
    "title": "Remove K Digits",
    "titleSlug": "remove-k-digits",
    "url": "https://leetcode.com/problems/remove-k-digits",
    "description_url": "https://leetcode.com/problems/remove-k-digits/description/",
    "description": "<p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;1432219&quot;, k = 3\n<strong>Output:</strong> &quot;1219&quot;\n<strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;10200&quot;, k = 1\n<strong>Output:</strong> &quot;200&quot;\n<strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = &quot;10&quot;, k = 2\n<strong>Output:</strong> &quot;0&quot;\n<strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>num</code> consists of only digits.</li>\n\t<li><code>num</code> does not have any leading zeros except for the zero itself.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-k-digits/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String removeKdigits(String num, int k) {\n    if (num.length() == k)\n      return \"0\";\n\n    StringBuilder sb = new StringBuilder();\n    LinkedList<Character> stack = new LinkedList<>();\n\n    for (int i = 0; i < num.length(); ++i) {\n      while (k > 0 && !stack.isEmpty() && stack.getLast() > num.charAt(i)) {\n        stack.pollLast();\n        --k;\n      }\n      stack.addLast(num.charAt(i));\n    }\n\n    while (k-- > 0)\n      stack.pollLast();\n\n    for (final char c : stack) {\n      if (c == '0' && sb.length() == 0)\n        continue;\n      sb.append(c);\n    }\n\n    return sb.length() == 0 ? \"0\" : sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string removeKdigits(string num, int k) {\n    if (num.length() == k)\n      return \"0\";\n\n    string ans;\n    vector<char> stack;\n\n    for (int i = 0; i < num.length(); ++i) {\n      while (k > 0 && !stack.empty() && stack.back() > num[i]) {\n        stack.pop_back();\n        --k;\n      }\n      stack.push_back(num[i]);\n    }\n\n    while (k-- > 0)\n      stack.pop_back();\n\n    for (const char c : stack) {\n      if (c == '0' && ans.empty())\n        continue;\n      ans += c;\n    }\n\n    return ans.empty() ? \"0\" : ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/402.html",
    "category": "Algorithms",
    "acceptance_rate": 34.74051036173576,
    "topics": [
      "String",
      "Stack",
      "Greedy",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 9944,
    "dislikes": 525,
    "similar_questions": "[{\"title\": \"Create Maximum Number\", \"titleSlug\": \"create-maximum-number\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Monotone Increasing Digits\", \"titleSlug\": \"monotone-increasing-digits\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Most Competitive Subsequence\", \"titleSlug\": \"find-the-most-competitive-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Append K Integers With Minimal Sum\", \"titleSlug\": \"append-k-integers-with-minimal-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Remove Digit From Number to Maximize Result\", \"titleSlug\": \"remove-digit-from-number-to-maximize-result\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make a Special Number\", \"titleSlug\": \"minimum-operations-to-make-a-special-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"587.8K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 587771, \"totalSubmissionRaw\": 1691889, \"acRate\": \"34.7%\"}",
    "title_pt": "Remover K Dígitos",
    "description_pt": "<p>Dada a string num representando um inteiro não negativo <code>num</code>, e um inteiro <code>k</code>, retorne <em>o menor inteiro possível após remover</em> <code>k</code> <em>dígitos de</em> <code>num</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;1432219&quot;, k = 3\n<strong>Saída:</strong> &quot;1219&quot;\n<strong>Explicação:</strong> Remova os três dígitos 4, 3 e 2 para formar o novo número 1219, que é o menor.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;10200&quot;, k = 1\n<strong>Saída:</strong> &quot;200&quot;\n<strong>Explicação:</strong> Remova o 1 inicial e o número é 200. Observe que a saída não deve conter zeros à esquerda.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = &quot;10&quot;, k = 2\n<strong>Saída:</strong> &quot;0&quot;\n<strong>Explicação:</strong> Remova todos os dígitos do número e ele ficará sem nada, o que é 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>num</code> consiste apenas de dígitos.</li>\n\t<li><code>num</code> não possui zeros à esquerda, exceto pelo próprio zero.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "403",
    "paidOnly": false,
    "title": "Frog Jump",
    "titleSlug": "frog-jump",
    "url": "https://leetcode.com/problems/frog-jump",
    "description_url": "https://leetcode.com/problems/frog-jump/description/",
    "description": "<p>A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.</p>\n\n<p>Given a list of <code>stones</code>&nbsp;positions (in units) in sorted <strong>ascending order</strong>, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be <code>1</code> unit.</p>\n\n<p>If the frog&#39;s last jump was <code>k</code> units, its next jump must be either <code>k - 1</code>, <code>k</code>, or <code>k + 1</code> units. The frog can only jump in the forward direction.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> stones = [0,1,3,5,6,8,12,17]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> stones = [0,1,2,3,4,8,9,11]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= stones.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>stones[0] == 0</code></li>\n\t<li><code>stones</code>&nbsp;is sorted in a strictly increasing order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/frog-jump/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canCross(self, stones: List[int]) -> bool:\n    n = len(stones)\n    # dp[i][j] := True if a frog can make a size j jump to stones[i]\n    dp = [[False] * (n + 1) for _ in range(n)]\n    dp[0][0] = True\n\n    for i in range(1, n):\n      for j in range(i):\n        k = stones[i] - stones[j]\n        if k > n:\n          continue\n        for x in (k - 1, k, k + 1):\n          if 0 <= x <= n:\n            dp[i][k] |= dp[j][x]\n\n    return any(dp[-1])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canCross(int[] stones) {\n    final int n = stones.length;\n    // dp[i][j] := 1 if a frog can make a size j jump to stones[i]\n    int[][] dp = new int[n][n + 1];\n    dp[0][0] = 1;\n\n    for (int i = 1; i < n; ++i)\n      for (int j = 0; j < i; ++j) {\n        final int k = stones[i] - stones[j];\n        if (k > n)\n          continue;\n        for (final int x : new int[] {k - 1, k, k + 1})\n          if (0 <= x && x <= n)\n            dp[i][k] |= dp[j][x];\n      }\n\n    return Arrays.stream(dp[n - 1]).anyMatch(a -> a == 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canCross(vector<int>& stones) {\n    const int n = stones.size();\n    // dp[i][j] := true if a frog can make a size j jump to stones[i]\n    vector<vector<bool>> dp(n, vector<bool>(n + 1));\n    dp[0][0] = true;\n\n    for (int i = 1; i < n; ++i)\n      for (int j = 0; j < i; ++j) {\n        const int k = stones[i] - stones[j];\n        if (k > n)\n          continue;\n        for (const int x : {k - 1, k, k + 1})\n          if (0 <= x && x <= n)\n            dp[i][k] = dp[i][k] || dp[j][x];\n      }\n\n    return any_of(begin(dp.back()), end(dp.back()),\n                  [](bool val) { return val; });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/403.html",
    "category": "Algorithms",
    "acceptance_rate": 46.49799092595573,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 5758,
    "dislikes": 261,
    "similar_questions": "[{\"title\": \"Minimum Sideway Jumps\", \"titleSlug\": \"minimum-sideway-jumps\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Solving Questions With Brainpower\", \"titleSlug\": \"solving-questions-with-brainpower\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Jumps to Reach the Last Index\", \"titleSlug\": \"maximum-number-of-jumps-to-reach-the-last-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"297.5K\", \"totalSubmission\": \"639.8K\", \"totalAcceptedRaw\": 297506, \"totalSubmissionRaw\": 639825, \"acRate\": \"46.5%\"}",
    "title_pt": "Salto do Sapo",
    "description_pt": "<p>Um sapo está atravessando um rio. O rio é dividido em algum número de unidades, e em cada unidade pode ou não existir uma pedra. O sapo pode saltar sobre uma pedra, mas não deve saltar para a água.</p>\n\n<p>Dada uma lista de posições de <code>stones</code>&nbsp;(em unidades) em ordem <strong>crescente</strong>, determine se o sapo pode atravessar o rio pousando na última pedra. Inicialmente, o sapo está na primeira pedra e assume-se que o primeiro salto deve ser de <code>1</code> unidade.</p>\n\n<p>Se o último salto do sapo foi de <code>k</code> unidades, seu próximo salto deve ser de <code>k - 1</code>, <code>k</code> ou <code>k + 1</code> unidades. O sapo só pode saltar na direção para frente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> stones = [0,1,3,5,6,8,12,17]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O sapo pode saltar até a última pedra saltando 1 unidade até a 2ª pedra, depois 2 unidades até a 3ª pedra, depois 2 unidades até a 4ª pedra, depois 3 unidades até a 6ª pedra, 4 unidades até a 7ª pedra, e 5 unidades até a 8ª pedra.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> stones = [0,1,2,3,4,8,9,11]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Não há maneira de saltar até a última pedra, pois a distância entre a 5ª e a 6ª pedra é grande demais.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= stones.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= stones[i] &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>stones[0] == 0</code></li>\n\t<li><code>stones</code>&nbsp;está ordenado em ordem estritamente crescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "404",
    "paidOnly": false,
    "title": "Sum of Left Leaves",
    "titleSlug": "sum-of-left-leaves",
    "url": "https://leetcode.com/problems/sum-of-left-leaves",
    "description_url": "https://leetcode.com/problems/sum-of-left-leaves/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the sum of all left leaves.</em></p>\n\n<p>A <strong>leaf</strong> is a node with no children. A <strong>left leaf</strong> is a leaf that is the left child of another node.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> 24\n<strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sum-of-left-leaves/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int sumOfLeftLeaves(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n\n    int ans = 0;\n    stack<TreeNode*> stack{{root}};\n\n    while (!stack.empty()) {\n      root = stack.top(), stack.pop();\n      if (root->left) {\n        if (root->left->left == nullptr && root->left->right == nullptr)\n          ans += root->left->val;\n        else\n          stack.push(root->left);\n      }\n      if (root->right)\n        stack.push(root->right);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int sumOfLeftLeaves(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    int ans = 0;\n\n    if (root.left != null) {\n      if (root.left.left == null && root.left.right == null)\n        ans += root.left.val;\n      else\n        ans += sumOfLeftLeaves(root.left);\n    }\n    ans += sumOfLeftLeaves(root.right);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int sumOfLeftLeaves(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n\n    int ans = 0;\n\n    if (root->left) {\n      if (root->left->left == nullptr && root->left->right == nullptr)\n        ans += root->left->val;\n      else\n        ans += sumOfLeftLeaves(root->left);\n    }\n    ans += sumOfLeftLeaves(root->right);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/404.html",
    "category": "Algorithms",
    "acceptance_rate": 61.564545210385745,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5628,
    "dislikes": 315,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"703.7K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 703721, \"totalSubmissionRaw\": 1143063, \"acRate\": \"61.6%\"}",
    "title_pt": "Soma das Folhas à Esquerda",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a soma de todas as folhas à esquerda.</em></p>\n\n<p>Uma <strong>folha</strong> é um nó sem filhos. Uma <strong>folha à esquerda</strong> é uma folha que é o filho esquerdo de outro nó.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> 24\n<strong>Explicação:</strong> Há duas folhas à esquerda na árvore binária, com valores 9 e 15 respectivamente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 1000]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "405",
    "paidOnly": false,
    "title": "Convert a Number to Hexadecimal",
    "titleSlug": "convert-a-number-to-hexadecimal",
    "url": "https://leetcode.com/problems/convert-a-number-to-hexadecimal",
    "description_url": "https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/",
    "description": "<p>Given a 32-bit integer <code>num</code>, return <em>a string representing its hexadecimal representation</em>. For negative integers, <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" target=\"_blank\">two&rsquo;s complement</a> method is used.</p>\n\n<p>All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.</p>\n\n<p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in library method to directly solve this problem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> num = 26\n<strong>Output:</strong> \"1a\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> num = -1\n<strong>Output:</strong> \"ffffffff\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/convert-a-number-to-hexadecimal/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String toHex(int num) {\n    final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',\n                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n    StringBuilder sb = new StringBuilder();\n\n    while (num != 0) {\n      sb.append(hex[num & 0xf]);\n      num >>>= 4;\n    }\n\n    return sb.length() == 0 ? \"0\" : sb.reverse().toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string toHex(unsigned num) {\n    const vector<char> hex{'0', '1', '2', '3', '4', '5', '6', '7',\n                           '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n    string ans;\n\n    while (num) {\n      ans += hex[num & 0xf];\n      num >>= 4;\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans.empty() ? \"0\" : ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/405.html",
    "category": "Algorithms",
    "acceptance_rate": 50.69570565255429,
    "topics": [
      "Math",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 1363,
    "dislikes": 225,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"175.6K\", \"totalSubmission\": \"346.3K\", \"totalAcceptedRaw\": 175576, \"totalSubmissionRaw\": 346334, \"acRate\": \"50.7%\"}",
    "title_pt": "Converter um Número para Hexadecimal",
    "description_pt": "<p>Dado um inteiro de 32 bits <code>num</code>, retorne <em>uma string representando sua representação hexadecimal</em>. Para inteiros negativos, o método do <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" target=\"_blank\">complemento de dois</a> é usado.</p>\n\n<p>Todas as letras na string de პასუხ devem ser caracteres minúsculos, e não deve haver zeros à esquerda na string de resposta, exceto para o próprio zero.</p>\n\n<p><strong>Nota:&nbsp;</strong>Você não tem permissão para usar qualquer método de biblioteca embutida para resolver este problema diretamente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> num = 26\n<strong>Saída:</strong> \"1a\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> num = -1\n<strong>Saída:</strong> \"ffffffff\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-2<sup>31</sup> &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "406",
    "paidOnly": false,
    "title": "Queue Reconstruction by Height",
    "titleSlug": "queue-reconstruction-by-height",
    "url": "https://leetcode.com/problems/queue-reconstruction-by-height",
    "description_url": "https://leetcode.com/problems/queue-reconstruction-by-height/description/",
    "description": "<p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p>\n\n<p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n<strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n<strong>Explanation:</strong>\nPerson 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\n<strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= people.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li>\n\t<li>It is guaranteed that the queue can be reconstructed.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/queue-reconstruction-by-height/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] reconstructQueue(int[][] people) {\n    List<int[]> ans = new ArrayList<>();\n\n    Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);\n\n    for (final int[] p : people)\n      ans.add(p[1], p);\n\n    return ans.toArray(new int[ans.size()][]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {\n    vector<vector<int>> ans;\n\n    sort(begin(people), end(people), [](const auto& a, const auto& b) {\n      return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0];\n    });\n\n    for (const vector<int>& p : people)\n      ans.insert(begin(ans) + p[1], p);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/406.html",
    "category": "Algorithms",
    "acceptance_rate": 74.11549335789469,
    "topics": [
      "Array",
      "Binary Indexed Tree",
      "Segment Tree",
      "Sorting"
    ],
    "hints": [
      "What can you say about the position of the shortest person? </br>\r\nIf the position of the shortest person is <i>i</i>, how many people would be in front of the shortest person?",
      "Once you fix the position of the shortest person, what can you say about the position of the second shortest person?"
    ],
    "likes": 7161,
    "dislikes": 737,
    "similar_questions": "[{\"title\": \"Count of Smaller Numbers After Self\", \"titleSlug\": \"count-of-smaller-numbers-after-self\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Reward Top K Students\", \"titleSlug\": \"reward-top-k-students\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"323.5K\", \"totalSubmission\": \"436.5K\", \"totalAcceptedRaw\": 323483, \"totalSubmissionRaw\": 436458, \"acRate\": \"74.1%\"}",
    "title_pt": "Reconstrução de Fila por Altura",
    "description_pt": "<p>Você recebe um array de pessoas, <code>people</code>, que são os atributos de algumas pessoas em uma fila (não necessariamente em ordem). Cada <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> representa a <code>i<sup>th</sup></code> pessoa de altura <code>h<sub>i</sub></code> com <strong>exatamente</strong> <code>k<sub>i</sub></code> outras pessoas à sua frente que têm altura maior ou igual a <code>h<sub>i</sub></code>.</p>\n\n<p>Reconstrua e retorne <em>a fila que é representada pelo array de entrada </em><code>people</code>. A fila retornada deve ser formatada como um array <code>queue</code>, onde <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> é o atributo da <code>j<sup>th</sup></code> pessoa na fila (<code>queue[0]</code> é a pessoa na frente da fila).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n<strong>Saída:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n<strong>Explicação:</strong>\nA pessoa 0 tem altura 5 e não há outras pessoas mais altas ou da mesma altura à sua frente.\nA pessoa 1 tem altura 7 e não há outras pessoas mais altas ou da mesma altura à sua frente.\nA pessoa 2 tem altura 5 e há duas pessoas mais altas ou da mesma altura à sua frente, que são as pessoas 0 e 1.\nA pessoa 3 tem altura 6 e há uma pessoa mais alta ou da mesma altura à sua frente, que é a pessoa 1.\nA pessoa 4 tem altura 4 e há quatro pessoas mais altas ou da mesma altura à sua frente, que são as pessoas 0, 1, 2 e 3.\nA pessoa 5 tem altura 7 e há uma pessoa mais alta ou da mesma altura à sua frente, que é a pessoa 1.\nPortanto [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] é a fila reconstruída.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\n<strong>Saída:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= people.length &lt;= 2000</code></li>\n\t<li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li>\n\t<li>É гарантido que a fila pode ser reconstruída.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: O que você pode dizer sobre a posição da pessoa mais baixa? </br>\nSe a posição da pessoa mais baixa for <i>i</i>, quantas pessoas estariam à frente da pessoa mais baixa?",
      "- Dica 2: Depois que você fixa a posição da pessoa mais baixa, o que você pode dizer sobre a posição da segunda pessoa mais baixa?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "407",
    "paidOnly": false,
    "title": "Trapping Rain Water II",
    "titleSlug": "trapping-rain-water-ii",
    "url": "https://leetcode.com/problems/trapping-rain-water-ii",
    "description_url": "https://leetcode.com/problems/trapping-rain-water-ii/description/",
    "description": "<p>Given an <code>m x n</code> integer matrix <code>heightMap</code> representing the height of each unit cell in a 2D elevation map, return <em>the volume of water it can trap after raining</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg\" style=\"width: 361px; height: 321px;\" />\n<pre>\n<strong>Input:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg\" style=\"width: 401px; height: 321px;\" />\n<pre>\n<strong>Input:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\n<strong>Output:</strong> 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == heightMap.length</code></li>\n\t<li><code>n == heightMap[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/trapping-rain-water-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a grid, `heightMap`, where each element represents the height of the corresponding cell in the 3D representation of the map. Our task is to calculate the total amount of water trapped on the map after it rains.\n\nWe can assume that it rains an infinite amount of water, but the water stays inside any area of the map only if there is a boundary that traps it. Specifically, the water remains on top of a cell as long as its combined height (the height of the cell plus the water above it) is less than or equal to the height of all its neighbors. If any neighbor is lower, the water will flow out to that lower cell. \n\n---\n\n### Approach: BFS + Priority Queue \n\n#### Intuition\n\nBuilding on the earlier observation, the total height of any cell (its original height plus any trapped water) must not exceed the smallest total height of its neighbors. Specifically, it cannot exceed the smallest total height of its neighboring cells. This constraint propagates outward from the grid’s edges, which act as the ultimate boundary since no water can be trapped beyond them.\n\nIn simpler terms, the cells around a region of the grid act as a boundary, and the smallest height of this boundary determines how much water can be stored in that region. To solve the problem, we begin by treating the edges of the grid as the initial boundary since water cannot spill beyond them. From there, we move inward, processing cells in a manner that respects the relationship between a cell’s height and the boundary:\n\n1. **Trapping Water**: When we process a cell, if its height is lower than the current boundary height, water can be trapped above it. The amount of water trapped is equal to the difference between the boundary height and the cell’s height. We then add this trapped water to our running total. To ensure the boundary remains valid, the cell is added to the boundary with its effective height adjusted to match the current boundary height. This adjustment prevents water from \"spilling\" through this cell and invalidating the boundary.\n\n2. **Updating the Boundary**: If the cell's height is greater than or equal to the boundary height, no water can be trapped above it. However, the cell still becomes part of the boundary because it might help trap water in adjacent, higher regions as we continue processing.\n\nTo efficiently manage the boundary and dynamically update the smallest height, we use a min-heap (priority queue). The heap lets us quickly find the lowest boundary height and ensure the traversal always processes the most constrained regions first.\n\n> For a more comprehensive understanding of heaps and priority queues, check out the [Heap Explore Card 🔗](https://leetcode.com/explore/learn/card/heap/). This resource provides an in-depth look at heap-based algorithms, explaining their key concepts and applications with a variety of problems to solidify understanding of the pattern.\n\n!?!../Documents/407/407_approach1_fix.json:960,540!?!\n\n#### Algorithm\n\n-   Define a struct `Cell` that stores the height and the coordinates of a cell in the map.\n-   Define two direction arrays, that will help us explore the neighbors of each cell: `dRow = [0, 0, -1, 1], dCol = [-1, 1, 0, 0]`.\n-   Initialize `numOfRows` and `numOfCols` to the number of rows and columns of the original grid, respectively.\n-   Create a `numOfRows x numOfCols` boolean grid, called `visited`, with all its values initialized to `false`.\n-   Initialize a priority queue (min-heap) of `Cells`, called `boundary`.\n-   Push the cells of the first and last row and column of the grid into the `boundary` and mark them as visited.\n-   Initialize `totalWaterVolume` to `0`.\n-   While the `boundary` is not empty:\n    -   Pop the top cell out of the `boundary`, as `[minBoundaryHeight, [currentRow, currentCol]]` - this is the cell with the minimum height in the unexplored part of the boundary.\n    -   Update `minBoundaryHeight` to `height`.\n    -   Loop through all neighbors of the current cell, with `direction` from `0` to `3`:\n        -   Initialize `neighborRow` to `currentRow + dRow[direction]` and `neighborCol` to `currentCol + dCol[direction]`.\n        -   If the cell `(neighborRow, neighborCol)` is valid, i.e. it is not out of the bounds of the grid and not visited:\n            -   If the height of the cell, `neighborHeight` is lower than `minBoundaryHeight`, add the difference `minBoundaryHeight - neighborHeight` to the `totalWaterVolume`.\n            -   Push the neighboring cell into the `boundary` with its height set to the maximum of its value and `minBoundayHeight`, as the lowest height of the boundary cannot fall below its current value.\n            -   Mark the neighboring cell as visited.\n-   Return `totalWaterVolume`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/dt4uER9y/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"dt4uER9y\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the number of rows and $n$ the number of columns of the input grid.\n\n-   Time complexity: $O(m \\cdot n \\times \\log{m \\cdot n})$\n\n    Each cell is pushed in the `boundary` exactly once, so the while loops runs $O(mn)$ times. On each iteration, an element is popped from the priority queue and four other elements (the neighboring cells) are potentially pushed into it. Since the push and pop operations of the priority queue have a time complexity of $O(k)$, where $k$ represents the size of the priority queue, the overall time complexity of the algorithm becomes $O(m \\cdot n \\times \\log{m \\cdot n})$.\n\n-   Space complexity: $O(m \\times n)$\n\n    We create a `visited` grid of size $m \\times n$ to keep track of the cells already explored. The priority queue, `boundary` can also grow up to $O(m \\times n)$ in size, so the algorithm requires $O(m \\times n)$ extra space.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int i;\n  public int j;\n  public int h; // heightMap[i][j] or the height after filling water\n  public T(int i, int j, int h) {\n    this.i = i;\n    this.j = j;\n    this.h = h;\n  }\n}\n\nclass Solution {\n  public int trapRainWater(int[][] heightMap) {\n    final int m = heightMap.length;\n    final int n = heightMap[0].length;\n    final int[] dirs = {0, 1, 0, -1, 0};\n    int ans = 0;\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.h - b.h);\n    boolean[][] seen = new boolean[m][n];\n\n    for (int i = 0; i < m; ++i) {\n      minHeap.offer(new T(i, 0, heightMap[i][0]));\n      minHeap.offer(new T(i, n - 1, heightMap[i][n - 1]));\n      seen[i][0] = true;\n      seen[i][n - 1] = true;\n    }\n\n    for (int j = 1; j < n - 1; ++j) {\n      minHeap.offer(new T(0, j, heightMap[0][j]));\n      minHeap.offer(new T(m - 1, j, heightMap[m - 1][j]));\n      seen[0][j] = true;\n      seen[m - 1][j] = true;\n    }\n\n    while (!minHeap.isEmpty()) {\n      final int i = minHeap.peek().i;\n      final int j = minHeap.peek().j;\n      final int h = minHeap.poll().h;\n      for (int k = 0; k < 4; ++k) {\n        final int x = i + dirs[k];\n        final int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (seen[x][y])\n          continue;\n        if (heightMap[x][y] < h) {\n          ans += h - heightMap[x][y];\n          minHeap.offer(new T(x, y, h)); // Fill the water on grid[x][y]\n        } else {\n          minHeap.offer(new T(x, y, heightMap[x][y]));\n        }\n        seen[x][y] = true;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int i;\n  int j;\n  int h;  // heightMap[i][j] or the height after filling water\n  T(int i, int j, int h) : i(i), j(j), h(h) {}\n};\n\nclass Solution {\n public:\n  int trapRainWater(vector<vector<int>>& heightMap) {\n    const int m = heightMap.size();\n    const int n = heightMap[0].size();\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    int ans = 0;\n    auto compare = [](const T& a, const T& b) { return a.h > b.h; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n    vector<vector<bool>> seen(m, vector<bool>(n));\n\n    for (int i = 0; i < m; ++i) {\n      minHeap.emplace(i, 0, heightMap[i][0]);\n      minHeap.emplace(i, n - 1, heightMap[i][n - 1]);\n      seen[i][0] = true;\n      seen[i][n - 1] = true;\n    }\n\n    for (int j = 1; j < n - 1; ++j) {\n      minHeap.emplace(0, j, heightMap[0][j]);\n      minHeap.emplace(m - 1, j, heightMap[m - 1][j]);\n      seen[0][j] = true;\n      seen[m - 1][j] = true;\n    }\n\n    while (!minHeap.empty()) {\n      const auto [i, j, h] = minHeap.top();\n      minHeap.pop();\n      for (int k = 0; k < 4; ++k) {\n        const int x = i + dirs[k];\n        const int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (seen[x][y])\n          continue;\n        if (heightMap[x][y] < h) {\n          ans += h - heightMap[x][y];\n          minHeap.emplace(x, y, h);  // Fill the water on grid[x][y]\n        } else {\n          minHeap.emplace(x, y, heightMap[x][y]);\n        }\n        seen[x][y] = true;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/407.html",
    "category": "Algorithms",
    "acceptance_rate": 58.773557943424805,
    "topics": [
      "Array",
      "Breadth-First Search",
      "Heap (Priority Queue)",
      "Matrix"
    ],
    "hints": [],
    "likes": 4497,
    "dislikes": 144,
    "similar_questions": "[{\"title\": \"Trapping Rain Water\", \"titleSlug\": \"trapping-rain-water\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Points From Grid Queries\", \"titleSlug\": \"maximum-number-of-points-from-grid-queries\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"178.9K\", \"totalSubmission\": \"304.4K\", \"totalAcceptedRaw\": 178912, \"totalSubmissionRaw\": 304409, \"acRate\": \"58.8%\"}",
    "title_pt": "Água da Chuva Aprisionada II",
    "description_pt": "<p>Dada uma matriz inteira <code>m x n</code> <code>heightMap</code> representando a altura de cada célula unitária em um mapa de elevação 2D, retorne <em>o volume de água que ela pode aprisionar após chover</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/trap1-3d.jpg\" style=\"width: 361px; height: 321px;\" />\n<pre>\n<strong>Entrada:</strong> heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Depois da chuva, água fica aprisionada entre os blocos.\nTemos dois pequenos lagos com 1 e 3 unidades aprisionadas.\nO volume total de água aprisionada é 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/08/trap2-3d.jpg\" style=\"width: 401px; height: 321px;\" />\n<pre>\n<strong>Entrada:</strong> heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\n<strong>Saída:</strong> 10\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == heightMap.length</code></li>\n\t<li><code>n == heightMap[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= heightMap[i][j] &lt;= 2 * 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "409",
    "paidOnly": false,
    "title": "Longest Palindrome",
    "titleSlug": "longest-palindrome",
    "url": "https://leetcode.com/problems/longest-palindrome",
    "description_url": "https://leetcode.com/problems/longest-palindrome/description/",
    "description": "<p>Given a string <code>s</code> which consists of lowercase or uppercase letters, return the length of the <strong>longest <span data-keyword=\"palindrome-string\">palindrome</span></strong>&nbsp;that can be built with those letters.</p>\n\n<p>Letters are <strong>case sensitive</strong>, for example, <code>&quot;Aa&quot;</code> is not considered a palindrome.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abccccdd&quot;\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> One longest palindrome that can be built is &quot;dccaccd&quot;, whose length is 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a&quot;\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The longest palindrome that can be built is &quot;a&quot;, whose length is 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2000</code></li>\n\t<li><code>s</code> consists of lowercase <strong>and/or</strong> uppercase English&nbsp;letters only.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-palindrome/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe need to find the length of the longest palindrome using the letters from a given string `s`. \n\nTo determine when a letter from the given string is eligible to be a part of the longest palindrome, let's examine our example palindromes:\n1. \"acbbca\": in a palindrome of even length, each character must appear an even number of times.\n2. \"madam\": in a palindrome of odd length, a single additional character may be counted for the center character. \n\n---\n\n### Approach 1: Greedy Way (Hash Table)\n\n#### Intuition\n\nTo determine the longest possible length of the palindrome, we need to find out how many times each character appears in `s`. A good way to count the frequency of each character is by using a hash table, where each character is a key and its frequency is the value.\n\nHash tables are a data structure that allows for the efficient storage and retrieval of key-value pairs. For more information about hash tables, refer to the [HashMap Explore Card](https://leetcode.com/explore/learn/card/hash-table/184/comparison-with-other-data-structures/).\n\nConsider the example string `s` = `cabcacdd`.\n\nIf we count the frequencies of each character in a hash table, we get the following table:\n\n| Character | Frequency |\n| :------: | :-------:  |\n| a   | 2  |\n| b   | 1  |\n| c   | 3  |\n| d   | 2  |\n\nTo form the longest palindrome, we take the maximum number of even occurrences of each character. In this case, we can count all occurrences of `a` and `d`, and 2 occurrences of `c`. \n\nWith one occurrence each of `b` and `c` remaining, we can further increase the length of the palindrome by adding a center character. \n\n#### Algorithm\n\n- Initialize a map `frequencyMap` to store the frequency of each character.\n- Count the frequency of each character in `s`.\n- Initialize variables:\n  - `res` to store the length of the longest palindrome.\n  - `hasOddFrequency` flag to check whether a character with odd frequency exists.\n- Loop through the frequencies `freq` of each character:\n  - If `freq` is even, add it to `res`.\n  - If the `freq` is odd, add `freq-1` to `res` and set `hasOddFrequency` to `true`.\n- If `hasOddFrequency` is `true`, return `res+1`, otherwise, return `res`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/DeaL9XJB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"DeaL9XJB\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the given string `s`.\n\n- Time complexity: $O(n)$\n\n    The algorithm goes through the characters of `s` twice: once to count their frequencies and once to construct the palindrome. Since hash table operations like inserting and updating take constant time ($O(1)$), the time complexity of the algorithm is $O(2 \\cdot n)$, which simplifies to $O(n)$.\n\n- Space complexity: $O(1)$\n\n    The algorithm uses a hash table to store the frequency of characters. Given that there can be at most $52$ unique characters in `s`, the space complexity is $O(52)$, which can be simplified to $O(1)$ space.\n\n---\n\n### Approach 2: Greedy Way (Optimized)\n\n#### Intuition.\n\nNotice that every character with an odd frequency has one unused occurrence in our longest palindrome, except for one character that can be used as the center. Like our previous approach, we will use a hash table to count the number of occurrences of each letter and a variable,`oddFreqCharsCount`, to track the number of letters with an odd number of occurrences. For example, in a string where the letter `a` appears 3 times, the letter `b` appears 7 times, and all other characters appear an even number of times, the count of `oddFreqCharsCount` is 2. Whenever we increase the frequency of a character in our hash table, we check if the new frequency is odd. If it is, we increment `oddFreqCharsCount`. If it isn't, we decrease `oddFreqCharsCount` to remove it from the count of characters with an odd frequency.\n\nThe following slideshow demonstrates the optimized greedy approach:\n\n!?!../Documents/409/map_slideshow.json:1182,902!?!\n\nA non-zero value of `oddFreqCharsCount` indicates that at least one letter is left unmatched. We can use this letter to form the center of a odd length palindrome, thereby increasing the length of the palindrome by one. \n\nNow the length of the longest palindrome can be determined by subtracting the count of characters with odd frequencies from the total length of the given string, and adding one unpaired character for the center if one exists.\n\n> The hash table used to store the frequencies of each character can be replaced with an integer array, where each index corresponds to a character's ASCII value. For our purposes, we can create an array of size 52: the first 26 indices represent the characters 'A' to 'Z', and the next 26 represent 'a' to 'z'. This approach is slightly more space-efficient than using a hash table, as hash tables need to store both the characters and the frequencies and often involve additional overhead from internal data structures used to handle hash collisions.\n\n#### Algorithm\n\n- Initialize a hash table `frequencyMap` to store the frequency of each character.\n- Initialize a variable `oddFreqCharsCount` to store the number of characters with odd frequency of occurrence.\n- Count the frequency of each character `c` in `s`.\n  - If after addition, the frequency of `c` becomes odd, increment `oddFreqCharsCount`.\n  - Else, decrement `oddFreqCharsCount`.\n- If the `oddFreqCharsCount` is greater than zero, return the length of the string minus `oddFreqCharsCount`, plus one.\n- Else, return the length of `s`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/nrb9y96V/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"nrb9y96V\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the given string `s`.\n\n* Time complexity: $O(n)$\n\n    The algorithm loops over the entire string `s` only once. Since hash table operations like inserting and updating take constant time ($O(1)$), the time complexity of the algorithm is $O(2 \\cdot n)$, which simplifies to $O(n)$.\n\n* Space complexity: $O(1)$\n\n    The only data structure used in our algorithm is a hash table, which stores the frequencies of at most $52$ unique characters. Thus, the space complexity of the algorithm is $O(52)$, which can be simplified to $O(1)$.\n\n---\n\n### Approach 3: Greedy Way (Hash Set)\n\n#### Intuition\n\nWe can also create the longest palindrome by simulating the matching process and counting the number of characters that we can match.\n\nLet's loop over the string `s` and track all the characters encountered at each step. For each character, we check if it matches any previously seen character. If it does, we add these two characters to our palindrome and remove the matched character from our tracking collection. If there are unmatched characters remaining at the end, we can use any one as the middle character.\n\nWe can use a hash set to track and count our letter pairings as we loop through the string.\n\nHash sets are an efficient way to store and repeatedly query elements. A hash set is a data structure that stores unique elements, providing efficient insertions, deletions, and lookups. It is implemented using a hash table, which ensures that operations average $O(1)$ time complexity. For more detailed information on hash sets and their applications, check out LeetCode's [Hash Set Explore Card](https://leetcode.com/explore/learn/card/hash-table/183/combination-with-other-algorithms/).\n\nAs we loop through the string `s`, we store each character in a hash set. If we encounter a character that matches a letter already in the set, we know we can pair it.  We remove that letter from the set and count these two letters as part of our palindrome.\n\nThe following slideshow illustrates the process of matching characters in the set:\n\n!?!../Documents/409/set_slideshow.json:1102,802!?!\n\nAt the end of this process, if the hash set isn't empty, it means we have some unmatched characters. We can use one of these unmatched characters to increase the length of the palindrome by one, making it the longest possible palindrome from the given string.\n\n#### Algorithm\n\n- Initialize a set `characterSet` to store a running collection of characters.\n- Initialize a variable `res` to store our required answer.\n- Loop over each character `c` of the string `s`:\n  - If `characterSet` already contains `c`, remove `c` from the set and add 2 to `res`.\n  - Else, add `c` to `characterSet`.\n- If `characterSet` is not empty, increment `res`.\n- Return `res`, which holds the length of the longest palindrome.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ifUEC382/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ifUEC382\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the given string `s`.\n\n- Time complexity: $O(n)$\n\n    The algorithm loops over the entire string only once, which takes $O(n)$ time. All insert, query and delete operations on the set takes constant time, so the time complexity of the algorithm remains $O(n)$.\n\n- Space complexity: $O(1)$\n\n    The maximum number of unique characters in the string is 52 (considering both uppercase and lowercase English letters). Since 52 is a constant number, the space complexity of the set is $O(52)$, which simplifies to $O(1)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestPalindrome(self, s: str) -> int:\n    ans = 0\n    count = Counter(s)\n\n    for c in count.values():\n      ans += c if c % 2 == 0 else c - 1\n\n    hasOddCount = any(c % 2 == 1 for c in count.values())\n\n    return ans + hasOddCount",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestPalindrome(String s) {\n    int ans = 0;\n    int[] count = new int[128];\n\n    for (final char c : s.toCharArray())\n      ++count[c];\n\n    for (final int c : count)\n      ans += c % 2 == 0 ? c : c - 1;\n\n    final boolean hasOddCount = Arrays.stream(count).anyMatch(c -> c % 2 == 1);\n\n    return ans + (hasOddCount ? 1 : 0);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestPalindrome(string s) {\n    int ans = 0;\n    vector<int> count(128);\n\n    for (const char c : s)\n      ++count[c];\n\n    for (const int c : count)\n      ans += c % 2 == 0 ? c : c - 1;\n\n    const bool hasOddCount =\n        any_of(begin(count), end(count), [](int c) { return c & 1; });\n\n    return ans + hasOddCount;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/409.html",
    "category": "Algorithms",
    "acceptance_rate": 55.518339786519334,
    "topics": [
      "Hash Table",
      "String",
      "Greedy"
    ],
    "hints": [],
    "likes": 6105,
    "dislikes": 429,
    "similar_questions": "[{\"title\": \"Palindrome Permutation\", \"titleSlug\": \"palindrome-permutation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Longest Palindrome by Concatenating Two Letter Words\", \"titleSlug\": \"longest-palindrome-by-concatenating-two-letter-words\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Largest Palindromic Number\", \"titleSlug\": \"largest-palindromic-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"913.8K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 913803, \"totalSubmissionRaw\": 1645950, \"acRate\": \"55.5%\"}",
    "title_pt": "Maior Palíndromo",
    "description_pt": "<p>Dada uma string <code>s</code> que consiste em letras minúsculas ou maiúsculas, retorne o comprimento do <strong>maior <span data-keyword=\"palindrome-string\">palíndromo</span></strong>&nbsp;que pode ser construído com essas letras.</p>\n\n<p>As letras são <strong>diferenciadas por maiúsculas e minúsculas</strong>; por exemplo, <code>&quot;Aa&quot;</code> não é considerado um palíndromo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abccccdd&quot;\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Um dos maiores palíndromos que pode ser construído é &quot;dccaccd&quot;, cujo comprimento é 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a&quot;\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> O maior palíndromo que pode ser construído é &quot;a&quot;, cujo comprimento é 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 2000</code></li>\n\t<li><code>s</code> consiste apenas de letras inglesas minúsculas <strong>e/ou</strong> maiúsculas.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "410",
    "paidOnly": false,
    "title": "Split Array Largest Sum",
    "titleSlug": "split-array-largest-sum",
    "url": "https://leetcode.com/problems/split-array-largest-sum",
    "description_url": "https://leetcode.com/problems/split-array-largest-sum/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, split <code>nums</code> into <code>k</code> non-empty subarrays such that the largest sum of any subarray is <strong>minimized</strong>.</p>\n\n<p>Return <em>the minimized largest sum of the split</em>.</p>\n\n<p>A <strong>subarray</strong> is a contiguous part of the array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [7,2,5,10,8], k = 2\n<strong>Output:</strong> 18\n<strong>Explanation:</strong> There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,5], k = 2\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> There are four ways to split nums into two subarrays.\nThe best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/split-array-largest-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def splitArray(self, nums: List[int], m: int) -> int:\n    n = len(nums)\n    prefix = [0] + list(itertools.accumulate(nums))\n\n    # Dp(i, k) := min of largest sum to split first i nums into k groups\n    @functools.lru_cache(None)\n    def dp(i: int, k: int) -> int:\n      if k == 1:\n        return prefix[i]\n\n      ans = math.inf\n\n      # Try all possible partitions\n      for j in range(k - 1, i):\n        ans = min(ans, max(dp(j, k - 1), prefix[i] - prefix[j]))\n\n      return ans\n\n    return dp(n, m)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int splitArray(int[] nums, int m) {\n    final int n = nums.length;\n    // dp[i][k] := min of largest sum to split first i nums into k groups\n    dp = new int[n + 1][m + 1];\n    prefix = new int[n + 1];\n\n    Arrays.stream(dp).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));\n\n    for (int i = 0; i < n; ++i)\n      prefix[i + 1] = nums[i] + prefix[i];\n\n    return splitArray(nums, n, m);\n  }\n\n  private int[][] dp;\n  private int[] prefix;\n\n  private int splitArray(int[] nums, int i, int k) {\n    if (k == 1)\n      return prefix[i];\n    if (dp[i][k] < Integer.MAX_VALUE)\n      return dp[i][k];\n\n    // Try all possible partitions\n    for (int j = k - 1; j < i; ++j)\n      dp[i][k] = Math.min(dp[i][k], Math.max(splitArray(nums, j, k - 1), prefix[i] - prefix[j]));\n\n    return dp[i][k];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int splitArray(vector<int>& nums, int m) {\n    const int n = nums.size();\n    // dp[i][k] := min of largest sum to split first i nums into k groups\n    dp.resize(n + 1, vector<int>(m + 1, INT_MAX));\n    prefix.resize(n + 1);\n\n    partial_sum(begin(nums), end(nums), begin(prefix) + 1);\n    return splitArray(nums, n, m);\n  }\n\n private:\n  vector<vector<int>> dp;\n  vector<int> prefix;\n\n  int splitArray(const vector<int>& nums, int i, int k) {\n    if (k == 1)\n      return prefix[i];\n    if (dp[i][k] < INT_MAX)\n      return dp[i][k];\n\n    // Try all possible partitions\n    for (int j = k - 1; j < i; ++j)\n      dp[i][k] =\n          min(dp[i][k], max(splitArray(nums, j, k - 1), prefix[i] - prefix[j]));\n\n    return dp[i][k];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/410.html",
    "category": "Algorithms",
    "acceptance_rate": 57.79752968135754,
    "topics": [
      "Array",
      "Binary Search",
      "Dynamic Programming",
      "Greedy",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 10471,
    "dislikes": 243,
    "similar_questions": "[{\"title\": \"Capacity To Ship Packages Within D Days\", \"titleSlug\": \"capacity-to-ship-packages-within-d-days\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Divide Chocolate\", \"titleSlug\": \"divide-chocolate\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Fair Distribution of Cookies\", \"titleSlug\": \"fair-distribution-of-cookies\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subsequence of Size K With the Largest Even Sum\", \"titleSlug\": \"subsequence-of-size-k-with-the-largest-even-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Total Beauty of the Gardens\", \"titleSlug\": \"maximum-total-beauty-of-the-gardens\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Split Array\", \"titleSlug\": \"number-of-ways-to-split-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost to Split an Array\", \"titleSlug\": \"minimum-cost-to-split-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Distribute Elements Into Two Arrays I\", \"titleSlug\": \"distribute-elements-into-two-arrays-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Distribute Elements Into Two Arrays II\", \"titleSlug\": \"distribute-elements-into-two-arrays-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"468.1K\", \"totalSubmission\": \"809.9K\", \"totalAcceptedRaw\": 468117, \"totalSubmissionRaw\": 809930, \"acRate\": \"57.8%\"}",
    "title_pt": "Dividir Array com Menor Soma Máxima",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, divida <code>nums</code> em <code>k</code> subarrays não vazios de forma que a maior soma de qualquer subarray seja <strong>minimizada</strong>.</p>\n\n<p>Retorne <em>a menor soma máxima da divisão</em>.</p>\n\n<p>Um <strong>subarray</strong> é uma parte contígua do array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [7,2,5,10,8], k = 2\n<strong>Saída:</strong> 18\n<strong>Explicação:</strong> Há quatro maneiras de dividir nums em dois subarrays.\nA melhor maneira é dividi-lo em [7,2,5] e [10,8], onde a maior soma entre os dois subarrays é apenas 18.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,5], k = 2\n<strong>Saída:</strong> 9\n<strong>Explicação:</strong> Há quatro maneiras de dividir nums em dois subarrays.\nA melhor maneira é dividi-lo em [1,2,3] e [4,5], onde a maior soma entre os dois subarrays é apenas 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= min(50, nums.length)</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "412",
    "paidOnly": false,
    "title": "Fizz Buzz",
    "titleSlug": "fizz-buzz",
    "url": "https://leetcode.com/problems/fizz-buzz",
    "description_url": "https://leetcode.com/problems/fizz-buzz/description/",
    "description": "<p>Given an integer <code>n</code>, return <em>a string array </em><code>answer</code><em> (<strong>1-indexed</strong>) where</em>:</p>\n\n<ul>\n\t<li><code>answer[i] == &quot;FizzBuzz&quot;</code> if <code>i</code> is divisible by <code>3</code> and <code>5</code>.</li>\n\t<li><code>answer[i] == &quot;Fizz&quot;</code> if <code>i</code> is divisible by <code>3</code>.</li>\n\t<li><code>answer[i] == &quot;Buzz&quot;</code> if <code>i</code> is divisible by <code>5</code>.</li>\n\t<li><code>answer[i] == i</code> (as a string) if none of the above conditions are true.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> [\"1\",\"2\",\"Fizz\"]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 5\n<strong>Output:</strong> [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> n = 15\n<strong>Output:</strong> [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/fizz-buzz/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fizzBuzz(self, n: int) -> List[str]:\n    d = {3: 'Fizz', 5: 'Buzz'}\n    return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> fizzBuzz(int n) {\n    List<String> ans = new ArrayList<>();\n\n    for (int i = 1; i <= n; ++i) {\n      StringBuilder sb = new StringBuilder();\n      if (i % 3 == 0)\n        sb.append(\"Fizz\");\n      if (i % 5 == 0)\n        sb.append(\"Buzz\");\n      ans.add(sb.length() == 0 ? String.valueOf(i) : sb.toString());\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> fizzBuzz(int n) {\n    vector<string> ans;\n\n    for (int i = 1; i <= n; ++i) {\n      string s;\n      if (i % 3 == 0)\n        s += \"Fizz\";\n      if (i % 5 == 0)\n        s += \"Buzz\";\n      ans.push_back(s.empty() ? to_string(i) : s);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/412.html",
    "category": "Algorithms",
    "acceptance_rate": 74.24257378355765,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 3010,
    "dislikes": 424,
    "similar_questions": "[{\"title\": \"Fizz Buzz Multithreaded\", \"titleSlug\": \"fizz-buzz-multithreaded\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Categorize Box According to Criteria\", \"titleSlug\": \"categorize-box-according-to-criteria\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1496914, \"totalSubmissionRaw\": 2016252, \"acRate\": \"74.2%\"}",
    "title_pt": "Fizz Buzz",
    "description_pt": "<p>Dado um inteiro <code>n</code>, retorne <em>um array de strings </em><code>answer</code><em> (<strong>indexado em 1</strong>) onde</em>:</p>\n\n<ul>\n\t<li><code>answer[i] == &quot;FizzBuzz&quot;</code> se <code>i</code> for divisível por <code>3</code> e <code>5</code>.</li>\n\t<li><code>answer[i] == &quot;Fizz&quot;</code> se <code>i</code> for divisível por <code>3</code>.</li>\n\t<li><code>answer[i] == &quot;Buzz&quot;</code> se <code>i</code> for divisível por <code>5</code>.</li>\n\t<li><code>answer[i] == i</code> (como uma string) se nenhuma das condições acima for verdadeira.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> [\"1\",\"2\",\"Fizz\"]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> n = 15\n<strong>Saída:</strong> [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "413",
    "paidOnly": false,
    "title": "Arithmetic Slices",
    "titleSlug": "arithmetic-slices",
    "url": "https://leetcode.com/problems/arithmetic-slices",
    "description_url": "https://leetcode.com/problems/arithmetic-slices/description/",
    "description": "<p>An integer array is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p>\n\n<ul>\n\t<li>For example, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code>, and <code>[3,-1,-5,-9]</code> are arithmetic sequences.</li>\n</ul>\n\n<p>Given an integer array <code>nums</code>, return <em>the number of arithmetic <strong>subarrays</strong> of</em> <code>nums</code>.</p>\n\n<p>A <strong>subarray</strong> is a contiguous subsequence of the array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/arithmetic-slices/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int numberOfArithmeticSlices(vector<int>& A) {\n    int ans = 0;\n    int dp = 0;  // # arithmetic slices ends at i\n\n    for (int i = 2; i < A.size(); ++i)\n      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])\n        ans += ++dp;\n      else\n        dp = 0;\n\n    return ans;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numberOfArithmeticSlices(int[] A) {\n    final int n = A.length;\n    if (n < 3)\n      return 0;\n\n    int[] dp = new int[n]; // dp[i] := # of arithmetic slices ends at A[i]\n\n    for (int i = 2; i < n; ++i)\n      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])\n        dp[i] += dp[i - 1] + 1;\n\n    return Arrays.stream(dp).sum();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numberOfArithmeticSlices(vector<int>& A) {\n    const int n = A.size();\n    if (n < 3)\n      return 0;\n\n    vector<int> dp(n);  // # arithmetic slices ends at i\n\n    for (int i = 2; i < A.size(); ++i)\n      if (A[i] - A[i - 1] == A[i - 1] - A[i - 2])\n        dp[i] = dp[i - 1] + 1;\n\n    return accumulate(begin(dp), end(dp), 0);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/413.html",
    "category": "Algorithms",
    "acceptance_rate": 64.82695580298537,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 5479,
    "dislikes": 302,
    "similar_questions": "[{\"title\": \"Arithmetic Slices II - Subsequence\", \"titleSlug\": \"arithmetic-slices-ii-subsequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Arithmetic Subarrays\", \"titleSlug\": \"arithmetic-subarrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Zero-Filled Subarrays\", \"titleSlug\": \"number-of-zero-filled-subarrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Length of the Longest Alphabetical Continuous Substring\", \"titleSlug\": \"length-of-the-longest-alphabetical-continuous-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"333.3K\", \"totalSubmission\": \"514.2K\", \"totalAcceptedRaw\": 333322, \"totalSubmissionRaw\": 514173, \"acRate\": \"64.8%\"}",
    "title_pt": "Slices Aritméticos",
    "description_pt": "<p>Um array de inteiros é chamado de aritmético se ele consiste em <strong>pelo menos três elementos</strong> e se a diferença entre quaisquer dois elementos consecutivos for a mesma.</p>\n\n<ul>\n\t<li>Por exemplo, <code>[1,3,5,7,9]</code>, <code>[7,7,7,7]</code> e <code>[3,-1,-5,-9]</code> são sequências aritméticas.</li>\n</ul>\n\n<p>Dado um array de inteiros <code>nums</code>, retorne <em>o número de <strong>subarrays</strong> aritméticos de</em> <code>nums</code>.</p>\n\n<p>Um <strong>subarray</strong> é uma subsequência contígua do array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Temos 3 slices aritméticos em nums: [1, 2, 3], [2, 3, 4] e [1,2,3,4] em si.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "414",
    "paidOnly": false,
    "title": "Third Maximum Number",
    "titleSlug": "third-maximum-number",
    "url": "https://leetcode.com/problems/third-maximum-number",
    "description_url": "https://leetcode.com/problems/third-maximum-number/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the <strong>third distinct maximum</strong> number in this array. If the third maximum does not exist, return the <strong>maximum</strong> number</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,2,1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong>\nThe first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\nThe first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,2,3,1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong>\nThe first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2&#39;s are counted together since they have the same value).\nThe third distinct maximum is 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Can you find an <code>O(n)</code> solution?",
    "solution_url": "https://leetcode.com/problems/third-maximum-number/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nIn this problem, we have to return the $3^{rd}$ largest number and if it does not exist we have to return the largest number.    \n\nIn problems where we have to find $k^{th}$ largest/smallest number, we can always start by using any one of these three methods: sorting the array, using a priority queue, or using a sorted set. \nAs these three methods keep array elements in sorted order and it's easy to find the required element.\n\nAlso, we can keep track of the $3^{rd}$ largest number using 3 pointers which point to the top 3 largest numbers of the array.    \nLet's explore all of these approaches in detail.\n\n---\n\n### Approach 1: Sorting\n\n#### Intuition\n\nThe most intuitive approach will be sorting the array and finding the $3^{rd}$ largest number.     \nWe also have to take care of duplicates, we have to consider only distinct numbers.\n\nAfter the array is sorted in non-increasing order, we can check the current number with the previous number. If the current number is different from the previous number it means the current number can be counted.    \nAnd whenever we count 3 different numbers we return that $3^{rd}$ distinct number.\n\n![sorting](../Figures/414/Slide1.png)\n\n#### Algorithm\n\n1. Sort the `nums` array in non-increasing order.\n\n2. Initialize variables:\n    - `elemCounted = 1`, it counts the number of distinct numbers that occurred till now.\n    - `prevElem` to the first array number, it denotes the previous counted number of the array.\n\n3. Iterate on `nums` array's second number to the last number:\n    - If the current number is different than `prevElem`, it means it is a new distinct number, thus increment `elemCounted` by `1` and store the current number in `prevElem`.\n    - If `elemCounted` reaches `3`, it means the current number is the third largest number, thus return this number.\n\n4. If we traversed on the whole array it means `3` distinct numbers were not present in the array, thus we return the largest number, which is at the beginning of the `nums` array.\n \n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/XsVibfJU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"XsVibfJU\"></iframe>\n\n\n#### Complexity Analysis\n\nIf $N$ is the number of elements in the input array.\n\n* Time complexity: $O(N \\log N)$.\n  - We sort the `nums` array, which takes $O(N \\log N)$ time.\n  - We iterate on the `nums` array once to find the $3^{rd}$ distinct number.\n  - Thus, overall it takes, $O(N \\log N + N) = O(N \\log N)$ time.\n\n* Space complexity: $O(1)$.\n    - We don't use any additional space.    \n       > **Note:** The built-in sort methods do use some additional space, you can tell this during the interview, but, the interviewer does not expect us to go into much detail about it, and it will be fine if we state the above space complexity analysis. \n\n---\n\n\n### Approach 2: Min Heap Data Structure\n\n#### Intuition\n\nWe can use one max heap data structure and keep all distinct numbers of our array in sorted order.    \n\n> A max heap is a complete binary tree, in which the key present at the root node must be greatest among the keys present at all of it’s children. And the same property must be recursively true for all sub-trees in that tree.         \nIf you are not familiar with heaps and priority queues, you can learn about them in our [explore card](https://leetcode.com/explore/featured/card/heap/643/heap/4018/).      \n\nThe max heap will keep the largest number on the top, thus we can get the $3^{rd}$ largest number from it.  \n\nBut we can further optimize this method.      \n\nWe are keeping all array numbers in the heap instead while iterating the given array we can keep the three largest numbers till now in the heap and when a new number comes which is larger than any one of those three numbers, we remove the smallest among them and push this new number in the heap.    \nAt any moment, the heap will only have three numbers in it.\n\nBut we need to tell which is the smallest number among all numbers in the heap, thus we have to use a **min heap**.\n\nIf after iterating over the given array, the heap does not contain three elements, it means that three distinct elements were not present in the array, thus in that case we return the maximum element among the elements stored in the min heap.\n\nAlso, we can keep one hash set to prevent the insertion of already used numbers in the min heap and the hash set can also maintain a size of three elements just like the min heap.        \nIf a number is removed from the min heap it can also be removed from the hash set as all the numbers in the min heap are greater than the removed number and it will never be inserted again in the heap.\n\n\nYou can better understand the whole approach with the following slideshow:\n\n!?!../Documents/414/slideshow1.json:960,540!?!\n\n<br />\n\n#### Algorithm\n\n1. Initialize variables:\n    - `minHeap`, a min heap to keep the smallest element on top.\n    - `taken`, a hash set to track inserted numbers in min heap. \n\n2. Iterate on all numbers of `nums` array:\n    - If the current number is already in the min heap, we skip it.\n    - If the min heap has three numbers in it, and if the current number is greater than the smallest in the min heap, then remove the smallest number and push the current number in both the min heap and the hash set.\n   - Otherwise, if the min heap has less than three elements, then just push the current number in the min heap and the hash set.\n\n3. If the min heap has less than three elements at the end, return the maximum element among all elements present in the min heap, which will be the largest number of the `nums` array.\n\n4. Otherwise, return the top element of the min heap, which will be the third largest number.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/MuSCYiN9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"MuSCYiN9\"></iframe>\n\n\n#### Complexity Analysis\n\nIf $N$ is the number of elements in the input array.\n\n* Time complexity: $O(N)$.\n\n  - We iterate on `nums` array and can push each element in the min heap and hash set once. \n\n  - Time taken to push and pop elements from min heap depends on number of elements in the heap (or height of the heap), and as here the heap will have at most three elements in it, those operations are considered constant time operations.\n\n  - Thus, overall it takes $O(N)$ time.\n\n\n* Space complexity: $O(1)$.\n    - Both the min heap and hashset will only have at most three elements in them  thus, it is considered as constant space usage.\n\n\n---\n\n### Approach 3: Ordered Set\n\n#### Intuition\n\nA set is a data structure that only keeps unique elements in it and an ordered set keeps those unique elements in sorted order.     \n> **Note:** If you don't know, the inner implementation of this data structure is basically a self-balancing binary search tree. Thus, insertions, deletions, searching, etc. basically take logarithmic time.        \nNot going into much detail about their implementation we will now focus on the problem statement.\n\nSimilar to the previous approach, instead of priority queue, we can use an ordered set to keep track of largest three elements of the array at any time. And as we can search any element in the set we don't have to use any other data structure to track already used elements.      \n\n\n#### Algorithm\n\n1. Initialize variables:\n    - `sortedNums`, an ordered set to store elements\n\n2. Iterate on all numbers of the `nums` array:\n    - If the current number is already in the ordered set, we skip it.\n    - If the ordered set has three numbers in it, and if the current number is greater than the smallest number in it, then remove the smallest number and push the current number in it.\n   - Otherwise, if the ordered set has less than three elements, then just push the current number in it.\n\n3. If the ordered set has three elements in it, return the smallest element among all elements present in the set, which will be the third largest number of the `nums` array.\n\n4. Otherwise, return the biggest element of the ordered set, which will be the largest number of the `nums` array.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/ZNuNqpBp/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ZNuNqpBp\"></iframe>\n\n\n#### Complexity Analysis\n\nIf $N$ is the number of elements in the input array.\n\n* Time complexity: $O(N)$.\n\n  - We iterate on the `nums` array and can push each element in the ordered set once. \n\n  - Time is taken to push and pop elements from the ordered set depends on the number of elements in it, and as here the ordered set will have at most three elements in it, those operations are considered constant time operations.\n\n  - Thus, overall it takes $O(N)$ time.\n\n\n* Space complexity: $O(1)$.\n    - The ordered set will only have at most three elements in it, thus, it is considered as constant space usage.\n\n---\n\n### Approach 4: 3 Pointers\n\n#### Intuition\n\nWe know that when traversing an array, we only need to keep track of the first three largest numbers in the array.     \nThis could also be done by using three variables, `firstMax`, which stores the largest number in the array till now, `secondMax`, which stores the second largest number till now, and, `thirdMax`, which stores the third largest number.\n\nWe will use long integer variable because the minimum possible value in the input array is $-2^{31}$, and initially, we need to store a value lower than this.\nIn the end we compared if the `thirdMax` variable is equal to the initial value, to check if we had three different numbers in our array or not.\nBut if we store $-2^{31}$ as the initial value then, it will not give the correct answer.\n\nFor example, consider a case where the array is $[1, 2, -2^{31}]$.     \nNow at the end, we have $\\text{firstMax} = 2$, $\\text{secondMax} = 1$, and $\\text{thirdMax} = -2^{31}$.     \nThus, now we will think `thirdMax` still has the initial value thus this variable is not changed and we will assume the array doesn't have 3 different numbers and will return the wrong answer.\n\n\nNow, if while traversing the array:\n  - the current number is already stored in any of the three variables, it means we will not use it again.\n  - the current number is greater than `firstMax`, then, the current number will become the largest of all numbers and `firstMax` will become the second largest, and `secondMax` will become the third largest number.\n  - the current number is not greater than `firstMax` but greater than `secondMax`, then, the current number will become the second largest, and `secondMax` will become the third largest number.\n  - the current number is smaller than `firstMax` and `secondMax`, but greater than `thirdMax`, then, the current number will become the third largest number.\n  - the current number is smaller than all three, then it will have no effect on those three variables.\n\nSo, while traversing the array we update these three variables based on the current number.\n\nYou can better understand it with the following slideshow:\n\n!?!../Documents/414/slideshow2.json:960,540!?!\n\n<br />\n\n#### Algorithm\n\n1. Initialize variables:\n    - `firstMax`, `secondMax`, and `thirdMax`, to a value less than the minimum possible integer in the array.\n\n2. Iterate on all numbers of the `nums` array:\n    - If the current number is already stored in any of three variables we will skip this number.\n    - If the current number is greater than, `firstMax`, update all three variables.\n    - Otherwise, if the current number if greater than, `secondMax`, update `secondMax` and `thirdMax`.\n    - Otherwise, if the current number if greater than, `thirdMax`, update `thirdMax`. \n\n3. If `thirdMax` still has the initial value it means we, never had three distinct numbers, return `firstMax`, the largest number.\n\n4. Otherwise, return the third largest number, `thirdMax`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/R2Lpv2rH/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"R2Lpv2rH\"></iframe>\n\n\n#### Complexity Analysis\n\nIf $N$ is the number of elements in the input array.\n\n* Time complexity: $O(N)$.\n\n  - We iterate on the `nums` array once and update some variables.       \n    Thus, overall it takes $O(N)$ time.\n\n* Space complexity: $O(1)$.\n    - We only used three extra variables.\n\n---\n\n\n### Approach 5: 3 Pointers (Follow-Up)\n\n#### Intuition\n\nAfter giving the previous approach, the interviewer might come up with a restriction, that our environment doesn't support long, big integers, etc.            \nWe used long integer variable because the minimum possible value in the input array was $-2^{31}$, and initially, we need to store a value lower than this and used it to check if `thirdMax` was updated or not.\n\nBut, we can also keep some boolean variables to indicate if `firstMax`, `secondMax`, `thirdMax` were ever changed or not.     \nThus, here we keep pairs of int (to store the int variable) and boolean (to show if the number was ever updated).\n\n#### Algorithm\n\n1. Initialize variables:\n    - `firstMax`, `secondMax`, and `thirdMax`, pairs of int and bool, where bool must be `false` to show they are not updated.\n\n2. Iterate on all numbers of the `nums` array:\n    - If the current number is already stored in any of three variables we will skip this number.\n    - If `firstMax` was never updated or the current number is greater than `firstMax`, update all three variables. And mark `firstMax` updated as `true`.\n    - Otherwise, if `secondMax` was never updated or the current number is greater than `secondMax`, update `secondMax` and `thirdMax`. And mark `secondMax` updated as `true`. \n    - Otherwise, if `thirdMax` was never updated or the current number is greater than `thirdMax`, update `thirdMax`. And mark `thirdMax` updated as `true`.   \n\n3. If `thirdMax` was not updated, then return the largest number stored in `firstMax`.\n\n4. Otherwise, return the third largest number stored in `thirdMax`.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/8FiVXfzh/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8FiVXfzh\"></iframe>\n\n\n#### Complexity Analysis\n\nIf $N$ is the number of elements in the input array.\n\n* Time complexity: $O(N)$.\n  - We iterate on the `nums` array once. Thus, overall it takes $O(N)$ time.\n\n* Space complexity: $O(1)$.\n    - We only used three extra variables.",
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int thirdMax(vector<int>& nums) {\n    priority_queue<int, vector<int>, greater<>> minHeap;\n    unordered_set<int> seen;\n\n    for (const int num : nums)\n      if (!seen.count(num)) {\n        seen.insert(num);\n        minHeap.push(num);\n        if (minHeap.size() > 3)\n          minHeap.pop();\n      }\n\n    if (minHeap.size() == 2)\n      minHeap.pop();\n\n    return minHeap.top();\n  }\n};",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  public int thirdMax(int[] nums) {\n    long max1 = Long.MIN_VALUE; // The maximum\n    long max2 = Long.MIN_VALUE; // 2nd maximum\n    long max3 = Long.MIN_VALUE; // 3rd maximum\n\n    for (final int num : nums)\n      if (num > max1) {\n        max3 = max2;\n        max2 = max1;\n        max1 = num;\n      } else if (max1 > num && num > max2) {\n        max3 = max2;\n        max2 = num;\n      } else if (max2 > num && num > max3) {\n        max3 = num;\n      }\n\n    return max3 == Long.MIN_VALUE ? (int) max1 : (int) max3;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int thirdMax(vector<int>& nums) {\n    long max1 = LONG_MIN;  // The maximum\n    long max2 = LONG_MIN;  // 2nd maximum\n    long max3 = LONG_MIN;  // 3rd maximum\n\n    for (const int num : nums)\n      if (num > max1) {\n        max3 = max2;\n        max2 = max1;\n        max1 = num;\n      } else if (max1 > num && num > max2) {\n        max3 = max2;\n        max2 = num;\n      } else if (max2 > num && num > max3) {\n        max3 = num;\n      }\n\n    return max3 == LONG_MIN ? max1 : max3;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/414.html",
    "category": "Algorithms",
    "acceptance_rate": 37.02588414788303,
    "topics": [
      "Array",
      "Sorting"
    ],
    "hints": [],
    "likes": 3240,
    "dislikes": 3347,
    "similar_questions": "[{\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Neither Minimum nor Maximum\", \"titleSlug\": \"neither-minimum-nor-maximum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"673.7K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 673680, \"totalSubmissionRaw\": 1819488, \"acRate\": \"37.0%\"}",
    "title_pt": "Terceiro Número Máximo",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o <strong>terceiro máximo distinto</strong> número neste array. Se o terceiro máximo não existir, retorne o número <strong>máximo</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,2,1]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong>\nO primeiro máximo distinto é 3.\nO segundo máximo distinto é 2.\nO terceiro máximo distinto é 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong>\nO primeiro máximo distinto é 2.\nO segundo máximo distinto é 1.\nO terceiro máximo distinto não existe, então o máximo (2) é retornado em seu lugar.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,2,3,1]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong>\nO primeiro máximo distinto é 3.\nO segundo máximo distinto é 2 (ambos os 2 são contados juntos, pois têm o mesmo valor).\nO terceiro máximo distinto é 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue encontrar uma solução em <code>O(n)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "415",
    "paidOnly": false,
    "title": "Add Strings",
    "titleSlug": "add-strings",
    "url": "https://leetcode.com/problems/add-strings",
    "description_url": "https://leetcode.com/problems/add-strings/description/",
    "description": "<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p>\n\n<p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot;\n<strong>Output:</strong> &quot;134&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot;\n<strong>Output:</strong> &quot;533&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot;\n<strong>Output:</strong> &quot;0&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>num1</code> and <code>num2</code> consist of only digits.</li>\n\t<li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/add-strings/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addStrings(self, num1: str, num2: str) -> str:\n    ans = []\n    carry = 0\n    i = len(num1) - 1\n    j = len(num2) - 1\n\n    while i >= 0 or j >= 0 or carry:\n      if i >= 0:\n        carry += int(num1[i])\n      if j >= 0:\n        carry += int(num2[j])\n      ans.append(str(carry % 10))\n      carry //= 10\n      i -= 1\n      j -= 1\n\n    return ''.join(reversed(ans))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String addStrings(String num1, String num2) {\n    StringBuilder sb = new StringBuilder();\n    int carry = 0;\n    int i = num1.length() - 1;\n    int j = num2.length() - 1;\n\n    while (i >= 0 || j >= 0 || carry > 0) {\n      if (i >= 0)\n        carry += num1.charAt(i--) - '0';\n      if (j >= 0)\n        carry += num2.charAt(j--) - '0';\n      sb.append(carry % 10);\n      carry /= 10;\n    }\n\n    return sb.reverse().toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string addStrings(string num1, string num2) {\n    string ans;\n    int carry = 0;\n    int i = num1.length() - 1;\n    int j = num2.length() - 1;\n\n    while (i >= 0 || j >= 0 || carry) {\n      if (i >= 0)\n        carry += num1[i--] - '0';\n      if (j >= 0)\n        carry += num2[j--] - '0';\n      ans += carry % 10 + '0';\n      carry /= 10;\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/415.html",
    "category": "Algorithms",
    "acceptance_rate": 51.86827325326081,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 5232,
    "dislikes": 799,
    "similar_questions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Multiply Strings\", \"titleSlug\": \"multiply-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add to Array-Form of Integer\", \"titleSlug\": \"add-to-array-form-of-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"807.9K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 807891, \"totalSubmissionRaw\": 1557585, \"acRate\": \"51.9%\"}",
    "title_pt": "Somar Strings",
    "description_pt": "<p>Dado dois inteiros não negativos, <code>num1</code> e <code>num2</code>, representados como string, retorne <em>a soma de</em> <code>num1</code> <em>e</em> <code>num2</code> <em>como uma string</em>.</p>\n\n<p>Você deve resolver o problema sem usar nenhuma biblioteca embutida para manipulação de inteiros grandes (como <code>BigInteger</code>). Você também não deve converter as entradas para inteiros diretamente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot;\n<strong>Saída:</strong> &quot;134&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot;\n<strong>Saída:</strong> &quot;533&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot;\n<strong>Saída:</strong> &quot;0&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>num1</code> e <code>num2</code> consistem apenas de dígitos.</li>\n\t<li><code>num1</code> e <code>num2</code> não têm zeros à esquerda, exceto o próprio zero.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "416",
    "paidOnly": false,
    "title": "Partition Equal Subset Sum",
    "titleSlug": "partition-equal-subset-sum",
    "url": "https://leetcode.com/problems/partition-equal-subset-sum",
    "description_url": "https://leetcode.com/problems/partition-equal-subset-sum/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <code>true</code> <em>if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,11,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The array can be partitioned as [1, 5, 5] and [11].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,5]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The array cannot be partitioned into equal sum subsets.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/partition-equal-subset-sum/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canPartition(self, nums: List[int]) -> bool:\n    summ = sum(nums)\n    if summ & 1:\n      return False\n    return self.knapsack_(nums, summ // 2)\n\n  def knapsack_(self, nums: List[int], subsetSum: int) -> bool:\n    n = len(nums)\n    # dp[i][j] := True if j can be formed by nums[0..i)\n    dp = [[False] * (subsetSum + 1) for _ in range(n + 1)]\n    dp[0][0] = True\n\n    for i in range(1, n + 1):\n      num = nums[i - 1]\n      for j in range(subsetSum + 1):\n        if j < num:\n          dp[i][j] = dp[i - 1][j]\n        else:\n          dp[i][j] = dp[i - 1][j] or dp[i - 1][j - num]\n\n    return dp[n][subsetSum]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canPartition(int[] nums) {\n    final int sum = Arrays.stream(nums).sum();\n    if (sum % 2 == 1)\n      return false;\n    return knapsack(nums, sum / 2);\n  }\n\n  private boolean knapsack(int[] nums, int subsetSum) {\n    final int n = nums.length;\n    // dp[i][j] := true if j can be formed by nums[0..i)\n    boolean[][] dp = new boolean[n + 1][subsetSum + 1];\n    dp[0][0] = true;\n\n    for (int i = 1; i <= n; ++i) {\n      final int num = nums[i - 1];\n      for (int j = 0; j <= subsetSum; ++j)\n        if (j < num)\n          dp[i][j] = dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num];\n    }\n\n    return dp[n][subsetSum];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canPartition(vector<int>& nums) {\n    const int sum = accumulate(begin(nums), end(nums), 0);\n    if (sum & 1)\n      return false;\n    return knapsack(nums, sum / 2);\n  }\n\n private:\n  bool knapsack(const vector<int>& nums, int subsetSum) {\n    const int n = nums.size();\n    // dp[i][j] := true if j can be formed by nums[0..i)\n    vector<vector<bool>> dp(n + 1, vector<bool>(subsetSum + 1));\n    dp[0][0] = true;\n\n    for (int i = 1; i <= n; ++i) {\n      const int num = nums[i - 1];\n      for (int j = 0; j <= subsetSum; ++j)\n        if (j < num)\n          dp[i][j] = dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j] || dp[i - 1][j - num];\n    }\n\n    return dp[n][subsetSum];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/416.html",
    "category": "Algorithms",
    "acceptance_rate": 48.28454166227586,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 13175,
    "dislikes": 279,
    "similar_questions": "[{\"title\": \"Partition to K Equal Sum Subsets\", \"titleSlug\": \"partition-to-k-equal-sum-subsets\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimize the Difference Between Target and Chosen Elements\", \"titleSlug\": \"minimize-the-difference-between-target-and-chosen-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Ways to Partition an Array\", \"titleSlug\": \"maximum-number-of-ways-to-partition-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Partition Array Into Two Arrays to Minimize Sum Difference\", \"titleSlug\": \"partition-array-into-two-arrays-to-minimize-sum-difference\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Subarrays With Equal Sum\", \"titleSlug\": \"find-subarrays-with-equal-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Great Partitions\", \"titleSlug\": \"number-of-great-partitions\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Split With Minimum Sum\", \"titleSlug\": \"split-with-minimum-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1205050, \"totalSubmissionRaw\": 2495729, \"acRate\": \"48.3%\"}",
    "title_pt": "Partição em Subconjuntos de Soma Igual",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <code>true</code> <em>se você puder particionar o array em dois subconjuntos de modo que a soma dos elementos em ambos os subconjuntos seja igual ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,11,5]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O array pode ser particionado como [1, 5, 5] e [11].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,5]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> O array não pode ser particionado em subconjuntos com soma igual.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 200</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "417",
    "paidOnly": false,
    "title": "Pacific Atlantic Water Flow",
    "titleSlug": "pacific-atlantic-water-flow",
    "url": "https://leetcode.com/problems/pacific-atlantic-water-flow",
    "description_url": "https://leetcode.com/problems/pacific-atlantic-water-flow/description/",
    "description": "<p>There is an <code>m x n</code> rectangular island that borders both the <strong>Pacific Ocean</strong> and <strong>Atlantic Ocean</strong>. The <strong>Pacific Ocean</strong> touches the island&#39;s left and top edges, and the <strong>Atlantic Ocean</strong> touches the island&#39;s right and bottom edges.</p>\n\n<p>The island is partitioned into a grid of square cells. You are given an <code>m x n</code> integer matrix <code>heights</code> where <code>heights[r][c]</code> represents the <strong>height above sea level</strong> of the cell at coordinate <code>(r, c)</code>.</p>\n\n<p>The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell&#39;s height is <strong>less than or equal to</strong> the current cell&#39;s height. Water can flow from any cell adjacent to an ocean into the ocean.</p>\n\n<p>Return <em>a <strong>2D list</strong> of grid coordinates </em><code>result</code><em> where </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denotes that rain water can flow from cell </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> to <strong>both</strong> the Pacific and Atlantic oceans</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg\" style=\"width: 400px; height: 400px;\" />\n<pre>\n<strong>Input:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\n<strong>Output:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\n<strong>Explanation:</strong> The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -&gt; Pacific Ocean \n&nbsp;      [0,4] -&gt; Atlantic Ocean\n[1,3]: [1,3] -&gt; [0,3] -&gt; Pacific Ocean \n&nbsp;      [1,3] -&gt; [1,4] -&gt; Atlantic Ocean\n[1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Pacific Ocean \n&nbsp;      [1,4] -&gt; Atlantic Ocean\n[2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Pacific Ocean \n&nbsp;      [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Atlantic Ocean\n[3,0]: [3,0] -&gt; Pacific Ocean \n&nbsp;      [3,0] -&gt; [4,0] -&gt; Atlantic Ocean\n[3,1]: [3,1] -&gt; [3,0] -&gt; Pacific Ocean \n&nbsp;      [3,1] -&gt; [4,1] -&gt; Atlantic Ocean\n[4,0]: [4,0] -&gt; Pacific Ocean \n       [4,0] -&gt; Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> heights = [[1]]\n<strong>Output:</strong> [[0,0]]\n<strong>Explanation:</strong> The water can flow from the only cell to the Pacific and Atlantic oceans.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == heights.length</code></li>\n\t<li><code>n == heights[r].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/pacific-atlantic-water-flow/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n    m = len(heights)\n    n = len(heights[0])\n    dirs = [0, 1, 0, -1, 0]\n    qP = deque()\n    qA = deque()\n    seenP = [[False] * n for _ in range(m)]\n    seenA = [[False] * n for _ in range(m)]\n\n    for i in range(m):\n      qP.append((i, 0))\n      qA.append((i, n - 1))\n      seenP[i][0] = True\n      seenA[i][n - 1] = True\n\n    for j in range(n):\n      qP.append((0, j))\n      qA.append((m - 1, j))\n      seenP[0][j] = True\n      seenA[m - 1][j] = True\n\n    def bfs(q: deque, seen: List[List[bool]]):\n      while q:\n        i, j = q.popleft()\n        h = heights[i][j]\n        for k in range(4):\n          x = i + dirs[k]\n          y = j + dirs[k + 1]\n          if x < 0 or x == m or y < 0 or y == n:\n            continue\n          if seen[x][y] or heights[x][y] < h:\n            continue\n          q.append((x, y))\n          seen[x][y] = True\n\n    bfs(qP, seenP)\n    bfs(qA, seenA)\n\n    return [[i, j] for i in range(m) for j in range(n) if seenP[i][j] and seenA[i][j]]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> pacificAtlantic(int[][] heights) {\n    final int m = heights.length;\n    final int n = heights[0].length;\n    List<List<Integer>> ans = new ArrayList<>();\n    Queue<int[]> qP = new ArrayDeque<>();\n    Queue<int[]> qA = new ArrayDeque<>();\n    boolean[][] seenP = new boolean[m][n];\n    boolean[][] seenA = new boolean[m][n];\n\n    for (int i = 0; i < m; ++i) {\n      qP.offer(new int[] {i, 0});\n      qA.offer(new int[] {i, n - 1});\n      seenP[i][0] = true;\n      seenA[i][n - 1] = true;\n    }\n\n    for (int j = 0; j < n; ++j) {\n      qP.offer(new int[] {0, j});\n      qA.offer(new int[] {m - 1, j});\n      seenP[0][j] = true;\n      seenA[m - 1][j] = true;\n    }\n\n    bfs(heights, qP, seenP);\n    bfs(heights, qA, seenA);\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (seenP[i][j] && seenA[i][j])\n          ans.add(new ArrayList<>(Arrays.asList(i, j)));\n\n    return ans;\n  }\n\n  private static final int[] dirs = {0, 1, 0, -1, 0};\n\n  private void bfs(int[][] heights, Queue<int[]> q, boolean[][] seen) {\n    while (!q.isEmpty()) {\n      final int i = q.peek()[0];\n      final int j = q.poll()[1];\n      final int h = heights[i][j];\n      for (int k = 0; k < 4; ++k) {\n        final int x = i + dirs[k];\n        final int y = j + dirs[k + 1];\n        if (x < 0 || x == heights.length || y < 0 || y == heights[0].length)\n          continue;\n        if (seen[x][y] || heights[x][y] < h)\n          continue;\n        q.offer(new int[] {x, y});\n        seen[x][y] = true;\n      }\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {\n    const int m = heights.size();\n    const int n = heights[0].size();\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    vector<vector<int>> ans;\n    queue<pair<int, int>> qP;\n    queue<pair<int, int>> qA;\n    vector<vector<bool>> seenP(m, vector<bool>(n));\n    vector<vector<bool>> seenA(m, vector<bool>(n));\n\n    auto bfs = [&](queue<pair<int, int>>& q, vector<vector<bool>>& seen) {\n      while (!q.empty()) {\n        const auto [i, j] = q.front();\n        q.pop();\n        const int h = heights[i][j];\n        for (int k = 0; k < 4; ++k) {\n          const int x = i + dirs[k];\n          const int y = j + dirs[k + 1];\n          if (x < 0 || x == m || y < 0 || y == n)\n            continue;\n          if (seen[x][y] || heights[x][y] < h)\n            continue;\n          q.emplace(x, y);\n          seen[x][y] = true;\n        }\n      }\n    };\n\n    for (int i = 0; i < m; ++i) {\n      qP.emplace(i, 0);\n      qA.emplace(i, n - 1);\n      seenP[i][0] = true;\n      seenA[i][n - 1] = true;\n    }\n\n    for (int j = 0; j < n; ++j) {\n      qP.emplace(0, j);\n      qA.emplace(m - 1, j);\n      seenP[0][j] = true;\n      seenA[m - 1][j] = true;\n    }\n\n    bfs(qP, seenP);\n    bfs(qA, seenA);\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (seenP[i][j] && seenA[i][j])\n          ans.push_back({i, j});\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/417.html",
    "category": "Algorithms",
    "acceptance_rate": 57.30326194251859,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 7822,
    "dislikes": 1593,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"591.5K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 591536, \"totalSubmissionRaw\": 1032289, \"acRate\": \"57.3%\"}",
    "title_pt": "Fluxo de Água no Pacífico e no Atlântico",
    "description_pt": "<p>Existe uma ilha retangular de <code>m x n</code> que faz fronteira com os oceanos <strong>Pacífico</strong> e <strong>Atlântico</strong>. O <strong>Oceano Pacífico</strong> toca as bordas esquerda e superior da ilha, e o <strong>Oceano Atlântico</strong> toca as bordas direita e inferior da ilha.</p>\n\n<p>A ilha está particionada em uma grade de células quadradas. Você recebe uma matriz inteira <code>m x n</code> <code>heights</code> em que <code>heights[r][c]</code> representa a <strong>altura acima do nível do mar</strong> da célula na coordenada <code>(r, c)</code>.</p>\n\n<p>A ilha recebe muita chuva, e a água da chuva pode fluir para células vizinhas diretamente ao norte, sul, leste e oeste se a altura da célula vizinha for <strong>menor ou igual a</strong> a altura da célula atual. A água pode fluir de qualquer célula adjacente a um oceano para dentro do oceano.</p>\n\n<p>Retorne <em>uma <strong>lista 2D</strong> de coordenadas da grade </em><code>result</code><em> em que </em><code>result[i] = [r<sub>i</sub>, c<sub>i</sub>]</code><em> denota que a água da chuva pode fluir da célula </em><code>(r<sub>i</sub>, c<sub>i</sub>)</code><em> para <strong>ambos</strong> os oceanos Pacífico e Atlântico</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/08/waterflow-grid.jpg\" style=\"width: 400px; height: 400px;\" />\n<pre>\n<strong>Entrada:</strong> heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\n<strong>Saída:</strong> [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\n<strong>Explicação:</strong> As seguintes células podem fluir para os oceanos Pacífico e Atlântico, como mostrado abaixo:\n[0,4]: [0,4] -&gt; Oceano Pacífico \n&nbsp;      [0,4] -&gt; Oceano Atlântico\n[1,3]: [1,3] -&gt; [0,3] -&gt; Oceano Pacífico \n&nbsp;      [1,3] -&gt; [1,4] -&gt; Oceano Atlântico\n[1,4]: [1,4] -&gt; [1,3] -&gt; [0,3] -&gt; Oceano Pacífico \n&nbsp;      [1,4] -&gt; Oceano Atlântico\n[2,2]: [2,2] -&gt; [1,2] -&gt; [0,2] -&gt; Oceano Pacífico \n&nbsp;      [2,2] -&gt; [2,3] -&gt; [2,4] -&gt; Oceano Atlântico\n[3,0]: [3,0] -&gt; Oceano Pacífico \n&nbsp;      [3,0] -&gt; [4,0] -&gt; Oceano Atlântico\n[3,1]: [3,1] -&gt; [3,0] -&gt; Oceano Pacífico \n&nbsp;      [3,1] -&gt; [4,1] -&gt; Oceano Atlântico\n[4,0]: [4,0] -&gt; Oceano Pacífico \n       [4,0] -&gt; Oceano Atlântico\nObserve que existem outros caminhos possíveis para que essas células fluam para os oceanos Pacífico e Atlântico.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> heights = [[1]]\n<strong>Saída:</strong> [[0,0]]\n<strong>Explicação:</strong> A água pode fluir da única célula para os oceanos Pacífico e Atlântico.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == heights.length</code></li>\n\t<li><code>n == heights[r].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= heights[r][c] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "419",
    "paidOnly": false,
    "title": "Battleships in a Board",
    "titleSlug": "battleships-in-a-board",
    "url": "https://leetcode.com/problems/battleships-in-a-board",
    "description_url": "https://leetcode.com/problems/battleships-in-a-board/description/",
    "description": "<p>Given an <code>m x n</code> matrix <code>board</code> where each cell is a battleship <code>&#39;X&#39;</code> or empty <code>&#39;.&#39;</code>, return <em>the number of the <strong>battleships</strong> on</em> <code>board</code>.</p>\n\n<p><strong>Battleships</strong> can only be placed horizontally or vertically on <code>board</code>. In other words, they can only be made of the shape <code>1 x k</code> (<code>1</code> row, <code>k</code> columns) or <code>k x 1</code> (<code>k</code> rows, <code>1</code> column), where <code>k</code> can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img height=\"333\" src=\"https://assets.leetcode.com/uploads/2024/06/21/image.png\" width=\"333\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> board = [[&quot;.&quot;]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>board[i][j]</code> is either <code>&#39;.&#39;</code> or <code>&#39;X&#39;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you do it in one-pass, using only <code>O(1)</code> extra memory and without modifying the values <code>board</code>?</p>\n",
    "solution_url": "https://leetcode.com/problems/battleships-in-a-board/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countBattleships(char[][] board) {\n    int ans = 0;\n\n    for (int i = 0; i < board.length; ++i)\n      for (int j = 0; j < board[0].length; ++j) {\n        if (board[i][j] == '.')\n          continue;\n        if (i > 0 && board[i - 1][j] == 'X')\n          continue;\n        if (j > 0 && board[i][j - 1] == 'X')\n          continue;\n        ++ans;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countBattleships(vector<vector<char>>& board) {\n    int ans = 0;\n\n    for (int i = 0; i < board.size(); ++i)\n      for (int j = 0; j < board[0].size(); ++j) {\n        if (board[i][j] == '.')\n          continue;\n        if (i > 0 && board[i - 1][j] == 'X')\n          continue;\n        if (j > 0 && board[i][j - 1] == 'X')\n          continue;\n        ++ans;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/419.html",
    "category": "Algorithms",
    "acceptance_rate": 76.44585476946759,
    "topics": [
      "Array",
      "Depth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 2393,
    "dislikes": 1010,
    "similar_questions": "[{\"title\": \"Number of Islands\", \"titleSlug\": \"number-of-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Walls and Gates\", \"titleSlug\": \"walls-and-gates\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Max Area of Island\", \"titleSlug\": \"max-area-of-island\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Rotting Oranges\", \"titleSlug\": \"rotting-oranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"242.4K\", \"totalSubmission\": \"317K\", \"totalAcceptedRaw\": 242352, \"totalSubmissionRaw\": 317025, \"acRate\": \"76.4%\"}",
    "title_pt": "Navios de Batalha em um Tabuleiro",
    "description_pt": "<p>Dada uma matriz <code>m x n</code> <code>board</code> em que cada célula é um navio de batalha <code>&#39;X&#39;</code> ou vazia <code>&#39;.&#39;</code>, retorne <em>o número de <strong>navios de batalha</strong> em</em> <code>board</code>.</p>\n\n<p><strong>Navios de batalha</strong> só podem ser posicionados horizontalmente ou verticalmente em <code>board</code>. Em outras palavras, eles só podem ter o formato <code>1 x k</code> (<code>1</code> linha, <code>k</code> colunas) ou <code>k x 1</code> (<code>k</code> linhas, <code>1</code> coluna), em que <code>k</code> pode ter qualquer tamanho. Pelo menos uma célula horizontal ou vertical separa dois navios de batalha (isto é, não há navios de batalha adjacentes).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img height=\"333\" src=\"https://assets.leetcode.com/uploads/2024/06/21/image.png\" width=\"333\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;X&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;],[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;X&quot;]]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> board = [[&quot;.&quot;]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>board[i][j]</code> é ou <code>&#39;.&#39;</code> ou <code>&#39;X&#39;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue fazer isso em uma única passada, usando apenas memória extra <code>O(1)</code> e sem modificar os valores de <code>board</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "420",
    "paidOnly": false,
    "title": "Strong Password Checker",
    "titleSlug": "strong-password-checker",
    "url": "https://leetcode.com/problems/strong-password-checker",
    "description_url": "https://leetcode.com/problems/strong-password-checker/description/",
    "description": "<p>A password is considered strong if the below conditions are all met:</p>\n\n<ul>\n\t<li>It has at least <code>6</code> characters and at most <code>20</code> characters.</li>\n\t<li>It contains at least <strong>one lowercase</strong> letter, at least <strong>one uppercase</strong> letter, and at least <strong>one digit</strong>.</li>\n\t<li>It does not contain three repeating characters in a row (i.e., <code>&quot;B<u><strong>aaa</strong></u>bb0&quot;</code> is weak, but <code>&quot;B<strong><u>aa</u></strong>b<u><strong>a</strong></u>0&quot;</code> is strong).</li>\n</ul>\n\n<p>Given a string <code>password</code>, return <em>the minimum number of steps required to make <code>password</code> strong. if <code>password</code> is already strong, return <code>0</code>.</em></p>\n\n<p>In one step, you can:</p>\n\n<ul>\n\t<li>Insert one character to <code>password</code>,</li>\n\t<li>Delete one character from <code>password</code>, or</li>\n\t<li>Replace one character of <code>password</code> with another character.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> password = \"a\"\n<strong>Output:</strong> 5\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> password = \"aA1\"\n<strong>Output:</strong> 3\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> password = \"1337C0d3\"\n<strong>Output:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= password.length &lt;= 50</code></li>\n\t<li><code>password</code> consists of letters, digits, dot&nbsp;<code>&#39;.&#39;</code> or exclamation mark <code>&#39;!&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/strong-password-checker/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int strongPasswordChecker(String s) {\n    final int n = s.length();\n    final char[] chars = s.toCharArray();\n    final int missing = getMissing(chars);\n    // # of replacements to deal with 3 repeating characters\n    int replaces = 0;\n    // # of seqs that can be substituted with 1 deletions, (3k)-seqs\n    int oneSeq = 0;\n    // # of seqs that can be substituted with 2 deletions, (3k + 1)-seqs\n    int twoSeq = 0;\n\n    for (int i = 2; i < n;)\n      if (chars[i] == chars[i - 1] && chars[i - 1] == chars[i - 2]) {\n        int length = 2; // Length of repeating chars\n        while (i < n && chars[i] == chars[i - 1]) {\n          ++length;\n          ++i;\n        }\n        replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa'\n        if (length % 3 == 0)\n          ++oneSeq;\n        if (length % 3 == 1)\n          ++twoSeq;\n      } else {\n        ++i;\n      }\n\n    if (n < 6)\n      return Math.max(6 - n, missing);\n    if (n <= 20)\n      return Math.max(replaces, missing);\n\n    final int deletes = n - 20;\n    // Each replacement in (3k)-seqs can be substituted with 1 deletions\n    replaces -= Math.min(oneSeq, deletes);\n    // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions\n    replaces -= Math.min(Math.max(deletes - oneSeq, 0), twoSeq * 2) / 2;\n    // Each replacement in other seqs can be substituted with 3 deletions\n    replaces -= Math.max(deletes - oneSeq - twoSeq * 2, 0) / 3;\n    return deletes + Math.max(replaces, missing);\n  }\n\n  private int getMissing(final char[] chars) {\n    int missing = 3;\n\n    for (final char c : chars)\n      if (Character.isUpperCase(c)) {\n        --missing;\n        break;\n      }\n\n    for (final char c : chars)\n      if (Character.isLowerCase(c)) {\n        --missing;\n        break;\n      }\n\n    for (final char c : chars)\n      if (Character.isDigit(c)) {\n        --missing;\n        break;\n      }\n\n    return missing;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int strongPasswordChecker(string s) {\n    const int n = s.length();\n    const int missing = getMissing(s);\n    // # of replacements to deal with 3 repeating characters\n    int replaces = 0;\n    // # of seqs that can be substituted with 1 deletions, (3k)-seqs\n    int oneSeq = 0;\n    // # of seqs that can be substituted with 2 deletions, (3k + 1)-seqs\n    int twoSeq = 0;\n\n    for (int i = 2; i < n;)\n      if (s[i] == s[i - 1] && s[i - 1] == s[i - 2]) {\n        int length = 2;  // Length of repeating s\n        while (i < n && s[i] == s[i - 1]) {\n          ++length;\n          ++i;\n        }\n        replaces += length / 3;  // 'aaaaaaa' -> 'aaxaaxa'\n        if (length % 3 == 0)\n          ++oneSeq;\n        if (length % 3 == 1)\n          ++twoSeq;\n      } else {\n        ++i;\n      }\n\n    if (n < 6)\n      return max(6 - n, missing);\n    if (n <= 20)\n      return max(replaces, missing);\n\n    const int deletes = n - 20;\n    // Each replacement in (3k)-seqs can be substituted with 1 deletions\n    replaces -= min(oneSeq, deletes);\n    // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions\n    replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) / 2;\n    // Each replacement in other seqs can be substituted with 3 deletions\n    replaces -= max(deletes - oneSeq - twoSeq * 2, 0) / 3;\n    return deletes + max(replaces, missing);\n  }\n\n private:\n  int getMissing(const string& s) {\n    int missing = 3;\n    if (any_of(begin(s), end(s), [](char c) { return isupper(c); }))\n      --missing;\n    if (any_of(begin(s), end(s), [](char c) { return islower(c); }))\n      --missing;\n    if (any_of(begin(s), end(s), [](char c) { return isdigit(c); }))\n      --missing;\n    return missing;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/420.html",
    "category": "Algorithms",
    "acceptance_rate": 14.542406952669845,
    "topics": [
      "String",
      "Greedy",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 921,
    "dislikes": 1742,
    "similar_questions": "[{\"title\": \"Strong Password Checker II\", \"titleSlug\": \"strong-password-checker-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"48.3K\", \"totalSubmission\": \"332.3K\", \"totalAcceptedRaw\": 48324, \"totalSubmissionRaw\": 332303, \"acRate\": \"14.5%\"}",
    "title_pt": "Verificador de Senha Forte",
    "description_pt": "<p>Uma senha é considerada forte se todas as condições abaixo forem atendidas:</p>\n\n<ul>\n\t<li>Ela tem pelo menos <code>6</code> caracteres e no máximo <code>20</code> caracteres.</li>\n\t<li>Ela contém pelo menos <strong>uma letra minúscula</strong>, pelo menos <strong>uma letra maiúscula</strong> e pelo menos <strong>um dígito</strong>.</li>\n\t<li>Ela não contém três caracteres repetidos em sequência (ou seja, <code>&quot;B<u><strong>aaa</strong></u>bb0&quot;</code> é fraca, mas <code>&quot;B<strong><u>aa</u></strong>b<u><strong>a</strong></u>0&quot;</code> é forte).</li>\n</ul>\n\n<p>Dada uma string <code>password</code>, retorne <em>o número mínimo de etapas necessárias para tornar <code>password</code> forte. Se <code>password</code> já for forte, retorne <code>0</code>.</em></p>\n\n<p>Em uma etapa, você pode:</p>\n\n<ul>\n\t<li>Inserir um caractere em <code>password</code>,</li>\n\t<li>Excluir um caractere de <code>password</code>, ou</li>\n\t<li>Substituir um caractere de <code>password</code> por outro caractere.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> password = \"a\"\n<strong>Saída:</strong> 5\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> password = \"aA1\"\n<strong>Saída:</strong> 3\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> password = \"1337C0d3\"\n<strong>Saída:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= password.length &lt;= 50</code></li>\n\t<li><code>password</code> consiste de letras, dígitos, ponto&nbsp;<code>&#39;.&#39;</code> ou ponto de exclamação <code>&#39;!&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "421",
    "paidOnly": false,
    "title": "Maximum XOR of Two Numbers in an Array",
    "titleSlug": "maximum-xor-of-two-numbers-in-an-array",
    "url": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array",
    "description_url": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the maximum result of </em><code>nums[i] XOR nums[j]</code>, where <code>0 &lt;= i &lt;= j &lt; n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,10,5,25,2,8]\n<strong>Output:</strong> 28\n<strong>Explanation:</strong> The maximum result is 5 XOR 25 = 28.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70]\n<strong>Output:</strong> 127\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMaximumXOR(int[] nums) {\n    int ans = 0;\n    int mask = 0;\n\n    for (int i = 31; i >= 0; --i) {\n      mask |= 1 << i;\n      Set<Integer> prefixes = new HashSet<>();\n      for (final int num : nums)\n        prefixes.add(num & mask);\n      final int candidate = ans | 1 << i;\n      for (final int prefix : prefixes)\n        if (prefixes.contains(prefix ^ candidate)) {\n          ans = candidate;\n          break;\n        }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMaximumXOR(vector<int>& nums) {\n    int ans = 0;\n    int mask = 0;\n\n    // If ans is 11100 at i = 2, it means before we reach the last two bits,\n    // 11100 is the maximum XOR we have, and we're going to explore if we can\n    // Get another two '1's and put them into ans\n    for (int i = 31; i >= 0; --i) {\n      // Mask grows like: 100...000, 110...000, 111...000, ..., 111...111\n      mask |= 1 << i;\n      unordered_set<int> prefixes;\n      // We only care about the left parts,\n      // If i = 2, nums = {1110, 1011, 0111}\n      // -> prefixes = {1100, 1000, 0100}\n      for (const int num : nums)\n        prefixes.insert(num & mask);\n      // If i = 1 and before this iteration, the ans is 1100,\n      // We hope to grow ans to 1110, so find a candidate\n      // Which can give a greedy try\n      const int candidate = ans | 1 << i;\n      for (const int prefix : prefixes)\n        if (prefixes.count(prefix ^ candidate)) {\n          ans = candidate;\n          break;\n        }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/421.html",
    "category": "Algorithms",
    "acceptance_rate": 53.17841512950866,
    "topics": [
      "Array",
      "Hash Table",
      "Bit Manipulation",
      "Trie"
    ],
    "hints": [],
    "likes": 5727,
    "dislikes": 413,
    "similar_questions": "[{\"title\": \"Maximum XOR With an Element From Array\", \"titleSlug\": \"maximum-xor-with-an-element-from-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum XOR After Operations \", \"titleSlug\": \"maximum-xor-after-operations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Prefix Scores of Strings\", \"titleSlug\": \"sum-of-prefix-scores-of-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimize XOR\", \"titleSlug\": \"minimize-xor\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Strong Pair XOR I\", \"titleSlug\": \"maximum-strong-pair-xor-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Strong Pair XOR II\", \"titleSlug\": \"maximum-strong-pair-xor-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"189.4K\", \"totalSubmission\": \"356.2K\", \"totalAcceptedRaw\": 189438, \"totalSubmissionRaw\": 356231, \"acRate\": \"53.2%\"}",
    "title_pt": "Máximo XOR de Dois Números em um Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o resultado máximo de </em><code>nums[i] XOR nums[j]</code>, onde <code>0 &lt;= i &lt;= j &lt; n</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,10,5,25,2,8]\n<strong>Saída:</strong> 28\n<strong>Explicação:</strong> O resultado máximo é 5 XOR 25 = 28.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [14,70,53,83,49,91,36,80,92,51,66,70]\n<strong>Saída:</strong> 127\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "423",
    "paidOnly": false,
    "title": "Reconstruct Original Digits from English",
    "titleSlug": "reconstruct-original-digits-from-english",
    "url": "https://leetcode.com/problems/reconstruct-original-digits-from-english",
    "description_url": "https://leetcode.com/problems/reconstruct-original-digits-from-english/description/",
    "description": "<p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"owoztneoer\"\n<strong>Output:</strong> \"012\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"fviefuro\"\n<strong>Output:</strong> \"45\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is one of the characters <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li>\n\t<li><code>s</code> is <strong>guaranteed</strong> to be valid.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reconstruct-original-digits-from-english/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def originalDigits(self, s: str) -> str:\n    count = [0] * 10\n\n    for c in s:\n      if c == 'z':\n        count[0] += 1\n      if c == 'o':\n        count[1] += 1\n      if c == 'w':\n        count[2] += 1\n      if c == 'h':\n        count[3] += 1\n      if c == 'u':\n        count[4] += 1\n      if c == 'f':\n        count[5] += 1\n      if c == 'x':\n        count[6] += 1\n      if c == 's':\n        count[7] += 1\n      if c == 'g':\n        count[8] += 1\n      if c == 'i':\n        count[9] += 1\n\n    count[1] -= count[0] + count[2] + count[4]\n    count[3] -= count[8]\n    count[5] -= count[4]\n    count[7] -= count[6]\n    count[9] -= count[5] + count[6] + count[8]\n\n    return ''.join(chr(i + ord('0')) for i, c in enumerate(count) for j in range(c))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String originalDigits(String s) {\n    StringBuilder sb = new StringBuilder();\n    int[] count = new int[10];\n\n    for (final char c : s.toCharArray()) {\n      if (c == 'z')\n        ++count[0];\n      if (c == 'o')\n        ++count[1];\n      if (c == 'w')\n        ++count[2];\n      if (c == 'h')\n        ++count[3];\n      if (c == 'u')\n        ++count[4];\n      if (c == 'f')\n        ++count[5];\n      if (c == 'x')\n        ++count[6];\n      if (c == 's')\n        ++count[7];\n      if (c == 'g')\n        ++count[8];\n      if (c == 'i')\n        ++count[9];\n    }\n\n    count[1] -= count[0] + count[2] + count[4];\n    count[3] -= count[8];\n    count[5] -= count[4];\n    count[7] -= count[6];\n    count[9] -= count[5] + count[6] + count[8];\n\n    for (int i = 0; i < 10; ++i)\n      for (int j = 0; j < count[i]; ++j)\n        sb.append(i);\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string originalDigits(string s) {\n    string ans;\n    vector<int> count(10);\n\n    for (const char c : s) {\n      if (c == 'z')\n        ++count[0];\n      if (c == 'o')\n        ++count[1];\n      if (c == 'w')\n        ++count[2];\n      if (c == 'h')\n        ++count[3];\n      if (c == 'u')\n        ++count[4];\n      if (c == 'f')\n        ++count[5];\n      if (c == 'x')\n        ++count[6];\n      if (c == 's')\n        ++count[7];\n      if (c == 'g')\n        ++count[8];\n      if (c == 'i')\n        ++count[9];\n    }\n\n    count[1] -= count[0] + count[2] + count[4];\n    count[3] -= count[8];\n    count[5] -= count[4];\n    count[7] -= count[6];\n    count[9] -= count[5] + count[6] + count[8];\n\n    for (int i = 0; i < 10; ++i)\n      for (int j = 0; j < count[i]; ++j)\n        ans += i + '0';\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/423.html",
    "category": "Algorithms",
    "acceptance_rate": 51.55542061749732,
    "topics": [
      "Hash Table",
      "Math",
      "String"
    ],
    "hints": [],
    "likes": 855,
    "dislikes": 2770,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"88.3K\", \"totalSubmission\": \"171.3K\", \"totalAcceptedRaw\": 88300, \"totalSubmissionRaw\": 171272, \"acRate\": \"51.6%\"}",
    "title_pt": "Reconstituir Dígitos Originais a partir do Inglês",
    "description_pt": "<p>Dada uma string <code>s</code> contendo uma representação em inglês fora de ordem dos dígitos <code>0-9</code>, retorne <em>os dígitos em ordem <strong>crescente</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"owoztneoer\"\n<strong>Saída:</strong> \"012\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"fviefuro\"\n<strong>Saída:</strong> \"45\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> é um dos caracteres <code>[&quot;e&quot;,&quot;g&quot;,&quot;f&quot;,&quot;i&quot;,&quot;h&quot;,&quot;o&quot;,&quot;n&quot;,&quot;s&quot;,&quot;r&quot;,&quot;u&quot;,&quot;t&quot;,&quot;w&quot;,&quot;v&quot;,&quot;x&quot;,&quot;z&quot;]</code>.</li>\n\t<li><code>s</code> é <strong>garantidamente</strong> válido.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "424",
    "paidOnly": false,
    "title": "Longest Repeating Character Replacement",
    "titleSlug": "longest-repeating-character-replacement",
    "url": "https://leetcode.com/problems/longest-repeating-character-replacement",
    "description_url": "https://leetcode.com/problems/longest-repeating-character-replacement/description/",
    "description": "<p>You are given a string <code>s</code> and an integer <code>k</code>. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most <code>k</code> times.</p>\n\n<p>Return <em>the length of the longest substring containing the same letter you can get after performing the above operations</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;ABAB&quot;, k = 2\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Replace the two &#39;A&#39;s with two &#39;B&#39;s or vice versa.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;AABABBA&quot;, k = 1\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Replace the one &#39;A&#39; in the middle with &#39;B&#39; and form &quot;AABBBBA&quot;.\nThe substring &quot;BBBB&quot; has the longest repeating letters, which is 4.\nThere may exists other ways to achieve this answer too.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of only uppercase English letters.</li>\n\t<li><code>0 &lt;= k &lt;= s.length</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-repeating-character-replacement/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def characterReplacement(self, s: str, k: int) -> int:\n    ans = 0\n    maxCount = 0\n    count = Counter()\n\n    l = 0\n    for r, c in enumerate(s):\n      count[c] += 1\n      maxCount = max(maxCount, count[c])\n      while maxCount + k < r - l + 1:\n        count[s[l]] -= 1\n        l += 1\n      ans = max(ans, r - l + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int characterReplacement(String s, int k) {\n    int ans = 0;\n    int maxCount = 0;\n    int[] count = new int[128];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      maxCount = Math.max(maxCount, ++count[s.charAt(r)]);\n      while (maxCount + k < r - l + 1)\n        --count[s.charAt(l++)];\n      ans = Math.max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int characterReplacement(string s, int k) {\n    int ans = 0;\n    int maxCount = 0;\n    vector<int> count(128);\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      maxCount = max(maxCount, ++count[s[r]]);\n      while (maxCount + k < r - l + 1)\n        --count[s[l++]];\n      ans = max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/424.html",
    "category": "Algorithms",
    "acceptance_rate": 56.92548570606279,
    "topics": [
      "Hash Table",
      "String",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 11659,
    "dislikes": 640,
    "similar_questions": "[{\"title\": \"Longest Substring with At Most K Distinct Characters\", \"titleSlug\": \"longest-substring-with-at-most-k-distinct-characters\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Max Consecutive Ones III\", \"titleSlug\": \"max-consecutive-ones-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Make Array Continuous\", \"titleSlug\": \"minimum-number-of-operations-to-make-array-continuous\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximize the Confusion of an Exam\", \"titleSlug\": \"maximize-the-confusion-of-an-exam\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Substring of One Repeating Character\", \"titleSlug\": \"longest-substring-of-one-repeating-character\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1091808, \"totalSubmissionRaw\": 1917960, \"acRate\": \"56.9%\"}",
    "title_pt": "Substituição da Maior Substring com Caracteres Repetidos",
    "description_pt": "<p>Você recebe uma string <code>s</code> e um inteiro <code>k</code>. Você pode escolher qualquer caractere da string e alterá-lo para qualquer outro caractere maiúsculo do alfabeto inglês. Você pode realizar essa operação no máximo <code>k</code> vezes.</p>\n\n<p>Retorne <em>o comprimento da maior substring contendo a mesma letra que você pode obter após realizar as operações acima</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;ABAB&quot;, k = 2\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Substitua os dois &#39;A&#39;s por dois &#39;B&#39;s ou vice-versa.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;AABABBA&quot;, k = 1\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Substitua o &#39;A&#39; do meio por &#39;B&#39; e forme &quot;AABBBBA&quot;.\nA substring &quot;BBBB&quot; tem o maior número de letras repetidas, que é 4.\nPode existir outras maneiras de obter essa resposta também.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras maiúsculas do alfabeto inglês.</li>\n\t<li><code>0 &lt;= k &lt;= s.length</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "427",
    "paidOnly": false,
    "title": "Construct Quad Tree",
    "titleSlug": "construct-quad-tree",
    "url": "https://leetcode.com/problems/construct-quad-tree",
    "description_url": "https://leetcode.com/problems/construct-quad-tree/description/",
    "description": "<p>Given a <code>n * n</code> matrix <code>grid</code> of <code>0&#39;s</code> and <code>1&#39;s</code> only. We want to represent <code>grid</code> with a Quad-Tree.</p>\n\n<p>Return <em>the root of the Quad-Tree representing </em><code>grid</code>.</p>\n\n<p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p>\n\n<ul>\n\t<li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s. Notice that you can assign the <code>val</code> to True or False when <code>isLeaf</code> is False, and both are accepted in the answer.</li>\n\t<li><code>isLeaf</code>: True if the node is a leaf node on the tree or False if the node has four children.</li>\n</ul>\n\n<pre>\nclass Node {\n    public boolean val;\n    public boolean isLeaf;\n    public Node topLeft;\n    public Node topRight;\n    public Node bottomLeft;\n    public Node bottomRight;\n}</pre>\n\n<p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p>\n\n<ol>\n\t<li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li>\n\t<li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li>\n\t<li>Recurse for each of the children with the proper sub-grid.</li>\n</ol>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/new_top.png\" style=\"width: 777px; height: 181px;\" />\n<p>If you want to know more about the Quad-Tree, you can refer to the <a href=\"https://en.wikipedia.org/wiki/Quadtree\">wiki</a>.</p>\n\n<p><strong>Quad-Tree format:</strong></p>\n\n<p>You don&#39;t need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p>\n\n<p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p>\n\n<p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/grid1.png\" style=\"width: 777px; height: 99px;\" />\n<pre>\n<strong>Input:</strong> grid = [[0,1],[1,0]]\n<strong>Output:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]]\n<strong>Explanation:</strong> The explanation of this example is shown below:\nNotice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e1tree.png\" style=\"width: 777px; height: 186px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e2mat.png\" style=\"width: 777px; height: 343px;\" /></p>\n\n<pre>\n<strong>Input:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\n<strong>Output:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\n<strong>Explanation:</strong> All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e2tree.png\" style=\"width: 777px; height: 328px;\" />\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == grid.length == grid[i].length</code></li>\n\t<li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 6</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/construct-quad-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node construct(int[][] grid) {\n    return helper(grid, 0, 0, grid.length);\n  }\n\n  private Node helper(int[][] grid, int i, int j, int w) {\n    if (allSame(grid, i, j, w))\n      return new Node(grid[i][j] == 1 ? true : false, true);\n\n    Node node = new Node(true, false);\n    node.topLeft = helper(grid, i, j, w / 2);\n    node.topRight = helper(grid, i, j + w / 2, w / 2);\n    node.bottomLeft = helper(grid, i + w / 2, j, w / 2);\n    node.bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2);\n    return node;\n  }\n\n  private boolean allSame(int[][] grid, int i, int j, int w) {\n    for (int x = i; x < i + w; ++x)\n      for (int y = j; y < j + w; ++y)\n        if (grid[x][y] != grid[i][j])\n          return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* construct(vector<vector<int>>& grid) {\n    return helper(grid, 0, 0, grid.size());\n  }\n\n private:\n  Node* helper(const vector<vector<int>>& grid, int i, int j, int w) {\n    if (allSame(grid, i, j, w))\n      return new Node(grid[i][j], true);\n\n    Node* node = new Node(true, false);\n    node->topLeft = helper(grid, i, j, w / 2);\n    node->topRight = helper(grid, i, j + w / 2, w / 2);\n    node->bottomLeft = helper(grid, i + w / 2, j, w / 2);\n    node->bottomRight = helper(grid, i + w / 2, j + w / 2, w / 2);\n    return node;\n  }\n\n  bool allSame(const vector<vector<int>>& grid, int i, int j, int w) {\n    return all_of(begin(grid) + i, begin(grid) + i + w,\n                  [&](const vector<int>& row) {\n      return all_of(begin(row) + j, begin(row) + j + w,\n                    [&](int num) { return num == grid[i][j]; });\n    });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/427.html",
    "category": "Algorithms",
    "acceptance_rate": 76.97542461513707,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Tree",
      "Matrix"
    ],
    "hints": [],
    "likes": 1633,
    "dislikes": 1903,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"162.7K\", \"totalSubmission\": \"211.3K\", \"totalAcceptedRaw\": 162656, \"totalSubmissionRaw\": 211309, \"acRate\": \"77.0%\"}",
    "title_pt": "Construir Árvore Quad",
    "description_pt": "<p>Dada uma matriz <code>n * n</code> <code>grid</code> contendo apenas <code>0&#39;s</code> e <code>1&#39;s</code>. Queremos representar <code>grid</code> com uma Quad-Tree.</p>\n\n<p>Retorne <em>a raiz da Quad-Tree que representa </em><code>grid</code>.</p>\n\n<p>Uma Quad-Tree é uma estrutura de dados em árvore na qual cada nó interno possui exatamente quatro filhos. Além disso, cada nó tem dois atributos:</p>\n\n<ul>\n\t<li><code>val</code>: True se o nó representa um grid de <code>1&#39;s</code> ou False se o nó representa um grid de <code>0&#39;s</code>. Observe que você pode atribuir <code>val</code> como True ou False quando <code>isLeaf</code> for False, e ambos são aceitos na resposta.</li>\n\t<li><code>isLeaf</code>: True se o nó for um nó folha na árvore ou False se o nó tiver quatro filhos.</li>\n</ul>\n\n<pre>\nclass Node {\n    public boolean val;\n    public boolean isLeaf;\n    public Node topLeft;\n    public Node topRight;\n    public Node bottomLeft;\n    public Node bottomRight;\n}</pre>\n\n<p>Podemos construir uma Quad-Tree a partir de uma área bidimensional usando os seguintes passos:</p>\n\n<ol>\n\t<li>Se o grid atual tiver o mesmo valor (ou seja, todos <code>1&#39;s</code> ou todos <code>0&#39;s</code>), defina <code>isLeaf</code> como True e defina <code>val</code> como o valor do grid e defina os quatro filhos como Null e pare.</li>\n\t<li>Se o grid atual tiver valores diferentes, defina <code>isLeaf</code> como False e defina <code>val</code> como qualquer valor e divida o grid atual em quatro sub-grids, como mostrado na foto.</li>\n\t<li>Recursione para cada um dos filhos com o sub-grid apropriado.</li>\n</ol>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/new_top.png\" style=\"width: 777px; height: 181px;\" />\n<p>Se você quiser saber mais sobre a Quad-Tree, pode consultar a <a href=\"https://en.wikipedia.org/wiki/Quadtree\">wiki</a>.</p>\n\n<p><strong>Formato da Quad-Tree:</strong></p>\n\n<p>Você não precisa ler esta seção para resolver o problema. Isto é apenas se você quiser entender o formato de saída aqui. A saída representa o formato serializado de uma Quad-Tree usando travessia em ordem de nível, onde <code>null</code> significa um terminador de caminho no qual não existe nenhum nó abaixo.</p>\n\n<p>É muito semelhante à serialização da árvore binária. A única diferença é que o nó é representado como uma lista <code>[isLeaf, val]</code>.</p>\n\n<p>Se o valor de <code>isLeaf</code> ou <code>val</code> for True, nós o representamos como <strong>1</strong> na lista <code>[isLeaf, val]</code> e se o valor de <code>isLeaf</code> ou <code>val</code> for False, nós o representamos como <strong>0</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/grid1.png\" style=\"width: 777px; height: 99px;\" />\n<pre>\n<strong>Entrada:</strong> grid = [[0,1],[1,0]]\n<strong>Saída:</strong> [[0,1],[1,0],[1,1],[1,1],[1,0]]\n<strong>Explicação:</strong> A explicação deste exemplo é mostrada abaixo:\nObserve que 0 representa False e 1 representa True na imagem que representa a Quad-Tree.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e1tree.png\" style=\"width: 777px; height: 186px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e2mat.png\" style=\"width: 777px; height: 343px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\n<strong>Saída:</strong> [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\n<strong>Explicação:</strong> Todos os valores no grid não são iguais. Dividimos o grid em quatro sub-grids.\nO topLeft, bottomLeft e bottomRight têm cada um o mesmo valor.\nO topRight tem valores diferentes, então o dividimos em 4 sub-grids, em que cada um tem o mesmo valor.\nA explicação é mostrada na foto abaixo:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/12/e2tree.png\" style=\"width: 777px; height: 328px;\" />\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == grid.length == grid[i].length</code></li>\n\t<li><code>n == 2<sup>x</sup></code> onde <code>0 &lt;= x &lt;= 6</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "429",
    "paidOnly": false,
    "title": "N-ary Tree Level Order Traversal",
    "titleSlug": "n-ary-tree-level-order-traversal",
    "url": "https://leetcode.com/problems/n-ary-tree-level-order-traversal",
    "description_url": "https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/",
    "description": "<p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes&#39; values.</p>\n\n<p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Output:</strong> [[1],[3,2,4],[5,6]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The height of the n-ary tree is less than or equal to <code>1000</code></li>\n\t<li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/n-ary-tree-level-order-traversal/solutions/",
    "solution": null,
    "solution_code_python": null,
    "solution_code_java": null,
    "solution_code_cpp": null,
    "solution_code_url": "https://leetcodehelp.github.io/429.html",
    "category": "Algorithms",
    "acceptance_rate": 71.2204045675073,
    "topics": [
      "Tree",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 3686,
    "dislikes": 140,
    "similar_questions": "[{\"title\": \"Binary Tree Level Order Traversal\", \"titleSlug\": \"binary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Preorder Traversal\", \"titleSlug\": \"n-ary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Postorder Traversal\", \"titleSlug\": \"n-ary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"The Time When the Network Becomes Idle\", \"titleSlug\": \"the-time-when-the-network-becomes-idle\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"337.9K\", \"totalSubmission\": \"474.5K\", \"totalAcceptedRaw\": 337928, \"totalSubmissionRaw\": 474482, \"acRate\": \"71.2%\"}",
    "title_pt": "Percurso em Ordem por Nível de Árvore N-ária",
    "description_pt": "<p>Dada uma árvore n-ária, retorne o percurso em <em>ordem por nível</em> dos valores de seus nós.</p>\n\n<p><em>A serialização de entrada da Nary-Tree é representada em seu percurso em ordem por nível, e cada grupo de filhos é separado pelo valor null (Veja os exemplos).</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Saída:</strong> [[1],[3,2,4],[5,6]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Saída:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>A altura da árvore n-ária é menor ou igual a <code>1000</code></li>\n\t<li>O número total de nós está entre <code>[0, 10<sup>4</sup>]</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "430",
    "paidOnly": false,
    "title": "Flatten a Multilevel Doubly Linked List",
    "titleSlug": "flatten-a-multilevel-doubly-linked-list",
    "url": "https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list",
    "description_url": "https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/description/",
    "description": "<p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p>\n\n<p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p>\n\n<p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg\" style=\"width: 700px; height: 339px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n<strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6]\n<strong>Explanation:</strong> The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n<img src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg\" style=\"width: 1000px; height: 69px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg\" style=\"width: 200px; height: 200px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,null,3]\n<strong>Output:</strong> [1,3,2]\n<strong>Explanation:</strong> The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n<img src=\"https://assets.leetcode.com/uploads/2021/11/24/list.jpg\" style=\"width: 300px; height: 87px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> head = []\n<strong>Output:</strong> []\n<strong>Explanation:</strong> There could be empty list in the input.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of Nodes will not exceed <code>1000</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>How the multilevel linked list is represented in test cases:</strong></p>\n\n<p>We use the multilevel linked list from <strong>Example 1</strong> above:</p>\n\n<pre>\n 1---2---3---4---5---6--NULL\n         |\n         7---8---9---10--NULL\n             |\n             11--12--NULL</pre>\n\n<p>The serialization of each level is as follows:</p>\n\n<pre>\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\n</pre>\n\n<p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p>\n\n<pre>\n[1,    2,    3, 4, 5, 6, null]\n             |\n[null, null, 7,    8, 9, 10, null]\n                   |\n[            null, 11, 12, null]\n</pre>\n\n<p>Merging the serialization of each level and removing trailing nulls we obtain:</p>\n\n<pre>\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def flatten(self, head: 'Node') -> 'Node':\n    def flatten(head: 'Node', rest: 'Node') -> 'Node':\n      if not head:\n        return rest\n\n      head.next = flatten(head.child, flatten(head.next, rest))\n      if head.next:\n        head.next.prev = head\n      head.child = None\n      return head\n\n    return flatten(head, None)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node flatten(Node head) {\n    return flatten(head, null);\n  }\n\n  private Node flatten(Node head, Node rest) {\n    if (head == null)\n      return rest;\n\n    head.next = flatten(head.child, flatten(head.next, rest));\n    if (head.next != null)\n      head.next.prev = head;\n    head.child = null;\n    return head;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* flatten(Node* head, Node* rest = nullptr) {\n    if (head == nullptr)\n      return rest;\n\n    head->next = flatten(head->child, flatten(head->next, rest));\n    if (head->next)\n      head->next->prev = head;\n    head->child = nullptr;\n    return head;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/430.html",
    "category": "Algorithms",
    "acceptance_rate": 61.18225679094223,
    "topics": [
      "Linked List",
      "Depth-First Search",
      "Doubly-Linked List"
    ],
    "hints": [],
    "likes": 5218,
    "dislikes": 335,
    "similar_questions": "[{\"title\": \"Flatten Binary Tree to Linked List\", \"titleSlug\": \"flatten-binary-tree-to-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Correct a Binary Tree\", \"titleSlug\": \"correct-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"372.7K\", \"totalSubmission\": \"609.2K\", \"totalAcceptedRaw\": 372692, \"totalSubmissionRaw\": 609153, \"acRate\": \"61.2%\"}",
    "title_pt": "Achatar uma Lista Duplamente Encadeada Multinível",
    "description_pt": "<p>Você recebe uma lista duplamente encadeada, que contém nós que possuem um ponteiro next, um ponteiro previous e um <strong>ponteiro child adicional</strong>. Esse ponteiro child pode ou não apontar para uma lista duplamente encadeada separada, também contendo esses nós especiais. Essas listas child podem ter um ou mais children próprios, e assim por diante, para produzir uma <strong>estrutura de dados multinível</strong>, como mostrado no exemplo abaixo.</p>\n\n<p>Dado o <code>head</code> do primeiro nível da lista, <strong>achate</strong> a lista de modo que todos os nós apareçam em uma lista duplamente encadeada de nível único. Seja <code>curr</code> um nó com uma lista child. Os nós na lista child devem aparecer <strong>depois</strong> de <code>curr</code> e <strong>antes</strong> de <code>curr.next</code> na lista achatada.</p>\n\n<p>Retorne o <em> </em><code>head</code><em> da lista achatada. Os nós na lista devem ter <strong>todos</strong> os seus ponteiros child definidos como </em><code>null</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg\" style=\"width: 700px; height: 339px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n<strong>Saída:</strong> [1,2,3,7,8,11,12,9,10,4,5,6]\n<strong>Explicação:</strong> A lista encadeada multinível na entrada é mostrada.\nDepois de achatar a lista encadeada multinível, ela se torna:\n<img src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg\" style=\"width: 1000px; height: 69px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg\" style=\"width: 200px; height: 200px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,null,3]\n<strong>Saída:</strong> [1,3,2]\n<strong>Explicação:</strong> A lista encadeada multinível na entrada é mostrada.\nDepois de achatar a lista encadeada multinível, ela se torna:\n<img src=\"https://assets.leetcode.com/uploads/2021/11/24/list.jpg\" style=\"width: 300px; height: 87px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> head = []\n<strong>Saída:</strong> []\n<strong>Explicação:</strong> Pode haver uma lista vazia na entrada.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de Nodes não excederá <code>1000</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Como a lista encadeada multinível é representada nos casos de teste:</strong></p>\n\n<p>Usamos a lista encadeada multinível do <strong>Exemplo 1</strong> acima:</p>\n\n<pre>\n 1---2---3---4---5---6--NULL\n         |\n         7---8---9---10--NULL\n             |\n             11--12--NULL</pre>\n\n<p>A serialização de cada nível é a seguinte:</p>\n\n<pre>\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\n</pre>\n\n<p>Para serializar todos os níveis juntos, adicionaremos nulls em cada nível para indicar que nenhum nó se conecta ao nó superior do nível anterior. A serialização se torna:</p>\n\n<pre>\n[1,    2,    3, 4, 5, 6, null]\n             |\n[null, null, 7,    8, 9, 10, null]\n                   |\n[            null, 11, 12, null]\n</pre>\n\n<p>Ao mesclar a serialização de cada nível e remover os nulls finais, obtemos:</p>\n\n<pre>\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "432",
    "paidOnly": false,
    "title": "All O`one Data Structure",
    "titleSlug": "all-oone-data-structure",
    "url": "https://leetcode.com/problems/all-oone-data-structure",
    "description_url": "https://leetcode.com/problems/all-oone-data-structure/description/",
    "description": "<p>Design a data structure to store the strings&#39; count with the ability to return the strings with minimum and maximum counts.</p>\n\n<p>Implement the <code>AllOne</code> class:</p>\n\n<ul>\n\t<li><code>AllOne()</code> Initializes the object of the data structure.</li>\n\t<li><code>inc(String key)</code> Increments the count of the string <code>key</code> by <code>1</code>. If <code>key</code> does not exist in the data structure, insert it with count <code>1</code>.</li>\n\t<li><code>dec(String key)</code> Decrements the count of the string <code>key</code> by <code>1</code>. If the count of <code>key</code> is <code>0</code> after the decrement, remove it from the data structure. It is guaranteed that <code>key</code> exists in the data structure before the decrement.</li>\n\t<li><code>getMaxKey()</code> Returns one of the keys with the maximal count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li>\n\t<li><code>getMinKey()</code> Returns one of the keys with the minimum count. If no element exists, return an empty string <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p><strong>Note</strong> that each function must run in <code>O(1)</code> average time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;AllOne&quot;, &quot;inc&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;]\n[[], [&quot;hello&quot;], [&quot;hello&quot;], [], [], [&quot;leet&quot;], [], []]\n<strong>Output</strong>\n[null, null, null, &quot;hello&quot;, &quot;hello&quot;, null, &quot;hello&quot;, &quot;leet&quot;]\n\n<strong>Explanation</strong>\nAllOne allOne = new AllOne();\nallOne.inc(&quot;hello&quot;);\nallOne.inc(&quot;hello&quot;);\nallOne.getMaxKey(); // return &quot;hello&quot;\nallOne.getMinKey(); // return &quot;hello&quot;\nallOne.inc(&quot;leet&quot;);\nallOne.getMaxKey(); // return &quot;hello&quot;\nallOne.getMinKey(); // return &quot;leet&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= key.length &lt;= 10</code></li>\n\t<li><code>key</code> consists of lowercase English letters.</li>\n\t<li>It is guaranteed that for each call to <code>dec</code>, <code>key</code> is existing in the data structure.</li>\n\t<li>At most <code>5 * 10<sup>4</sup></code>&nbsp;calls will be made to <code>inc</code>, <code>dec</code>, <code>getMaxKey</code>, and <code>getMinKey</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/all-oone-data-structure/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview:\n\nWe need to create a specialized data structure that efficiently handles the following operations on strings and their associated counts:\n\n- Increase the count of a specified string.\n- Decrease the count of a specified string.\n- Retrieve the string with the highest count.\n- Retrieve the string with the lowest count.\n\nA key requirement is that each of these operations must be performed in constant time, $Θ(1)$ on average.\n\n![AllOone](../Figures/432/432_allOone.png)\n\n### Approach: Using Doubly Linked List\n\n#### Intuition\n\nTo manage a collection of keys and their frequencies, we need a structure that updates easily and provides quick access to maximum and minimum frequencies. We start with a hashmap to look up each key’s frequency quickly.\n\nHowever, a hashmap alone does not track frequencies well. We need a way to group keys by their frequencies and find keys with the same frequency. We use a doubly linked list for this. Each node represents a frequency and holds all keys linked to that frequency. This setup allows us to add and remove keys efficiently as their frequencies change.\n\nTo handle edge cases better, we include dummy head and tail nodes in the list. These nodes make it easier to manage operations when the list is empty or when we add or remove nodes at the ends.\n\nWhen we increment a key, we first check if it exists in the hashmap. If the key is new, we look at the node after the dummy head. If that node does not have a frequency of 1, we create a new node for frequency 1. We add the key to this node and update the hashmap. If the key already exists, we find its current frequency node and check the next node, which shows the next higher frequency. If that next node is the tail or does not have the expected frequency, we create a new node with the increased frequency. We then move the key to the right node, remove it from the old node, and delete the old node if it becomes empty.\n\nWhen we decrement a key, we first check if it is in the hashmap. If it is, we remove it from its current node. If the key’s frequency is greater than one, we check the previous node. If needed, we create a new node for the decreased frequency and add the key to the appropriate previous node, updating the hashmap. If the frequency is one, we remove the key from the hashmap completely.\n\nTo find the key with the maximum frequency, we return one of the keys from the last node in the list. For the minimum frequency key, we get a key from the first node after the dummy head. If there are no keys, we return an empty string.\n\n#### Algorithm\n\n - `Node` Class:\n  - Each `Node` contains:\n    - `freq`: the frequency of the keys.\n    - `prev`: a pointer to the previous node.\n    - `next`: a pointer to the next node.\n    - `keys`: a set of strings representing the keys with this frequency.\n  - The constructor initializes the `freq`, and sets `prev` and `next` to `nullptr`.\n\n- `AllOne` Class:\n  - Create a dummy head node and a dummy tail node.\n  - Link the dummy head to the dummy tail and vice versa.\n\n  - Incrementing a Key (`inc` function):\n    - If the key already exists:\n      - Retrieve the corresponding `node` from the `map`.\n      - Erase the key from the current `node`.\n      - Check the next node:\n        - If it doesn’t exist or its frequency is not `freq + 1`:\n          - Create a new node with frequency `freq + 1`.\n          - Insert the key into this new node.\n          - Link the new node with the current and next nodes.\n          - Update the `map` to point to the new node.\n        - Otherwise, insert the key into the existing next node.\n      - If the current node has no keys left, remove it.\n      \n    - If the key does not exist:\n      - Check the first node after the head:\n        - If it doesn’t exist or its frequency is greater than `1`:\n          - Create a new node with frequency `1`.\n          - Insert the key into this new node.\n          - Link this new node with the head and the first node.\n        - Otherwise, insert the key into the first node.\n\n  - Decrementing a Key (`dec` function):\n    - If the key does not exist in the `map`, return immediately.\n    - Retrieve the node corresponding to the key.\n    - Erase the key from the current node.\n    - If the frequency is `1`:\n      - Remove the key from the `map`.\n    - Otherwise, check the previous node:\n      - If it doesn’t exist or its frequency is not `freq - 1`:\n        - Create a new node with frequency `freq - 1`.\n        - Insert the key into this new node and link it with the current node and the previous node.\n      - Otherwise, insert the key into the existing previous node.\n    - If the node has no keys left, remove it.\n\n  - Getting the Maximum Key (`getMaxKey` function):\n    - If there are no keys (i.e., the tail's previous node points to the head), return an empty string.\n    - Return one of the keys from the tail's previous node.\n\n  - Getting the Minimum Key (`getMinKey` function):\n    - If there are no keys (i.e., the head's next node points to the tail), return an empty string.\n    - Return one of the keys from the head's next node.\n\n- Removing a Node (`removeNode` function):\n  - Link the previous node to the next node and vice versa to remove the specified node from the linked list.\n  - Delete the removed node to free its memory.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/eRAv3tYP/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"eRAv3tYP\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of unique keys.\n\n- Time complexity: $O(1)$\n\n    The `inc` and `dec` methods both perform operations that are constant time. In `inc`, whether inserting a new key or updating an existing one, the operations primarily involve updating pointers in the linked list and updating the hash map, which are $O(1)$ operations.\n    \n    Similarly, in `dec`, removing a key, updating the hash map, and possibly creating a new node or modifying the previous node also take constant time. Therefore, both operations run in $O(1)$.\n    \n    The `getMaxKey` and `getMinKey` methods return a key from the front or back of the linked list, which is also $O(1)$ since it involves accessing the first or last element of the list.\n\n> This assumes that map operations typically run in \"average-case $Θ(1)$\". However, in the worst case, where many hash collisions occur, these operations can degrade to $O(N)$.\n\n- Space complexity: $O(N)$\n\n    The space used by the `AllOne` data structure is primarily due to the hash map and the linked list of `Node`s. \n\n    The hash map stores pointers to nodes for each unique key, requiring $O(N)$ space where $N$ is the number of unique keys.\n\n    Each `Node` contains a set of `keys`, which can also grow with the number of unique keys in the worst case. Hence, the total space consumed by the linked list of nodes will also contribute to $O(N)$.\n\n---\n\n</br>\n\n<details>\n<summary>Further Thoughts: Understanding Hashmap Time Complexity [Click Here]</summary>\n\n</br>\n\nA common question that always arises is: why are hashmap lookups considered $O(1)$ in terms of time complexity, even in worst-case scenarios? This seems counterintuitive, especially considering that hash collisions can occur.\n\nIf we use a predetermined hash function, the worst-case time for hashmap operations could indeed be $O(n)$. Why? Because someone could craft a set of keys that all hash to the same value, causing a chain of collisions. This would force the lookup to scan through all $n$ elements, resulting in $O(n)$ time complexity.\n\nThe key to achieving $O(1)$ time complexity lies in randomization. Instead of using a fixed hash function like `h(x) = (constant_a . x + constant_b) % constant_prime`, we can use a randomized approach. For example, we might choose random values for the parameters in our hash function each time we initialize our hashmap, such as `h(x) = (random_a . x + random_b) % random_prime`. (This is just one way to construct a hash function; there are many other types you can design.)\n\nThis randomization makes it virtually impossible for someone to predict and exploit the hash function's behavior.\n\nFrom a mathematical perspective, when analyzing the \"expected runtime\" of hashmap operations using a randomized hash function, it averages out to $O(1)$. While some individual operations might take longer due to collisions, the overall average remains constant.\n\nIt's crucial to understand that when we say \"expected worst-case time is $O(1)$\", we're referring to the average over all possible random choices of the hash function, for any given input.\n\nThis isn't just theoretical—it’s applied in practice. For instance, Google’s Abseil library randomizes hash functions at the program start. This helps prevent attacks that exploit hash collisions and makes systems more secure. Randomization also ensures that software doesn't become dependent on a specific hash function. Hardcoding a hash function and never changing it makes future updates to improve security or performance challenging.\n\nThis concept illustrates a broader principle in system design: the power of introducing controlled randomness to improve system performance and security. It also relates to Hyrum's Law, which suggests that all observable behaviors of a system will eventually be depended on by somebody. By randomizing hash functions, we prevent dependencies on specific hash behaviors, making systems more robust and flexible.\n\nAdditionally, when we say \"expected value,\" it's not just a random term; it is formally defined, similar to worst-case and average-case scenarios. You can read the definition and understand the concept here in [probability theory: Expected value](https://en.m.wikipedia.org/wiki/Expected_value).\n\n</details>",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass AllOne {\n public:\n  void inc(string key) {\n    const auto it = keyToIterator.find(key);\n\n    // doesn't find the key\n    if (it == cend(keyToIterator)) {\n      if (l.empty() || l.front().value > 1)\n        l.push_front({1, {key}});\n      else\n        l.front().keys.insert(key);\n      keyToIterator[key] = begin(l);\n      return;\n    }\n\n    const auto lit = it->second;  // List iterator\n    auto nit = next(lit);         // Next iterator\n\n    if (nit == end(l) || nit->value > lit->value + 1)\n      nit = l.insert(nit, {lit->value + 1, {key}});\n    else  // Nit->value == lit->value + 1\n      nit->keys.insert(key);\n    keyToIterator[key] = nit;  // Reset the mapping\n\n    // Remove the key in keys set\n    lit->keys.erase(key);\n    if (lit->keys.empty())\n      l.erase(lit);\n  }\n\n  void dec(string key) {\n    const auto it = keyToIterator.find(key);\n\n    // doens't find the key\n    if (it == cend(keyToIterator))\n      return;\n\n    const auto lit = it->second;  // List iterator\n\n    if (lit->value == 1) {  // No need to find prev iterator in this case\n      keyToIterator.erase(key);\n    } else {\n      auto pit = prev(lit);  // Prev iterator\n\n      if (lit == begin(l) || pit->value < lit->value - 1)\n        pit = l.insert(lit, {lit->value - 1, {key}});\n      else  // Pit->value == lit-value - 1\n        pit->keys.insert(key);\n      keyToIterator[key] = pit;  // Reset the mapping\n    }\n\n    // Remove the key in keys set\n    lit->keys.erase(key);\n    if (lit->keys.empty())\n      l.erase(lit);\n  }\n\n  string getMaxKey() {\n    return l.empty() ? \"\" : *cbegin(l.back().keys);\n  }\n\n  string getMinKey() {\n    return l.empty() ? \"\" : *cbegin(l.front().keys);\n  }\n\n private:\n  struct Node {\n    int value;\n    unordered_set<string> keys;\n  };\n\n  list<Node> l;\n  unordered_map<string, list<Node>::iterator> keyToIterator;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/432.html",
    "category": "Algorithms",
    "acceptance_rate": 44.160515847842795,
    "topics": [
      "Hash Table",
      "Linked List",
      "Design",
      "Doubly-Linked List"
    ],
    "hints": [],
    "likes": 2123,
    "dislikes": 212,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"177.5K\", \"totalSubmission\": \"402K\", \"totalAcceptedRaw\": 177516, \"totalSubmissionRaw\": 401979, \"acRate\": \"44.2%\"}",
    "title_pt": "Estrutura de Dados All O`one",
    "description_pt": "<p>Projete uma estrutura de dados para armazenar a contagem das strings, com a capacidade de retornar as strings com as contagens mínima e máxima.</p>\n\n<p>Implemente a classe <code>AllOne</code>:</p>\n\n<ul>\n\t<li><code>AllOne()</code> Inicializa o objeto da estrutura de dados.</li>\n\t<li><code>inc(String key)</code> Incrementa a contagem da string <code>key</code> em <code>1</code>. Se <code>key</code> não existir na estrutura de dados, insira-a com contagem <code>1</code>.</li>\n\t<li><code>dec(String key)</code> Decrementa a contagem da string <code>key</code> em <code>1</code>. Se a contagem de <code>key</code> for <code>0</code> após o decremento, remova-a da estrutura de dados. É garantido que <code>key</code> existe na estrutura de dados antes do decremento.</li>\n\t<li><code>getMaxKey()</code> Retorna uma das chaves com a contagem máxima. Se nenhum elemento existir, retorne uma string vazia <code>&quot;&quot;</code>.</li>\n\t<li><code>getMinKey()</code> Retorna uma das chaves com a contagem mínima. Se nenhum elemento existir, retorne uma string vazia <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p><strong>Nota</strong> que cada função deve executar em complexidade de tempo médio <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;AllOne&quot;, &quot;inc&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;, &quot;inc&quot;, &quot;getMaxKey&quot;, &quot;getMinKey&quot;]\n[[], [&quot;hello&quot;], [&quot;hello&quot;], [], [], [&quot;leet&quot;], [], []]\n<strong>Saída</strong>\n[null, null, null, &quot;hello&quot;, &quot;hello&quot;, null, &quot;hello&quot;, &quot;leet&quot;]\n\n<strong>Explicação</strong>\nAllOne allOne = new AllOne();\nallOne.inc(&quot;hello&quot;);\nallOne.inc(&quot;hello&quot;);\nallOne.getMaxKey(); // return &quot;hello&quot;\nallOne.getMinKey(); // return &quot;hello&quot;\nallOne.inc(&quot;leet&quot;);\nallOne.getMaxKey(); // return &quot;hello&quot;\nallOne.getMinKey(); // return &quot;leet&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= key.length &lt;= 10</code></li>\n\t<li><code>key</code> consiste em letras minúsculas do inglês.</li>\n\t<li>É garantido que, para cada chamada de <code>dec</code>, <code>key</code> existe na estrutura de dados.</li>\n\t<li>No máximo <code>5 * 10<sup>4</sup></code>&nbsp;chamadas serão feitas para <code>inc</code>, <code>dec</code>, <code>getMaxKey</code> e <code>getMinKey</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "433",
    "paidOnly": false,
    "title": "Minimum Genetic Mutation",
    "titleSlug": "minimum-genetic-mutation",
    "url": "https://leetcode.com/problems/minimum-genetic-mutation",
    "description_url": "https://leetcode.com/problems/minimum-genetic-mutation/description/",
    "description": "<p>A gene string can be represented by an 8-character long string, with choices from <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;T&#39;</code>.</p>\n\n<p>Suppose we need to investigate a mutation from a gene string <code>startGene</code> to a gene string <code>endGene</code> where one mutation is defined as one single character changed in the gene string.</p>\n\n<ul>\n\t<li>For example, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> is one mutation.</li>\n</ul>\n\n<p>There is also a gene bank <code>bank</code> that records all the valid gene mutations. A gene must be in <code>bank</code> to make it a valid gene string.</p>\n\n<p>Given the two gene strings <code>startGene</code> and <code>endGene</code> and the gene bank <code>bank</code>, return <em>the minimum number of mutations needed to mutate from </em><code>startGene</code><em> to </em><code>endGene</code>. If there is no such a mutation, return <code>-1</code>.</p>\n\n<p>Note that the starting point is assumed to be valid, so it might not be included in the bank.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;]\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= bank.length &lt;= 10</code></li>\n\t<li><code>startGene.length == endGene.length == bank[i].length == 8</code></li>\n\t<li><code>startGene</code>, <code>endGene</code>, and <code>bank[i]</code> consist of only the characters <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-genetic-mutation/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minMutation(String start, String end, String[] bank) {\n    Set<String> bankSet = new HashSet<>(Arrays.asList(bank));\n    if (!bankSet.contains(end))\n      return -1;\n\n    int ans = 0;\n    Queue<String> q = new ArrayDeque<>(Arrays.asList(start));\n\n    while (!q.isEmpty()) {\n      ++ans;\n      for (int sz = q.size(); sz > 0; --sz) {\n        StringBuilder sb = new StringBuilder(q.poll());\n        for (int j = 0; j < sb.length(); ++j) {\n          final char cache = sb.charAt(j);\n          for (final char c : new char[] {'A', 'C', 'G', 'T'}) {\n            sb.setCharAt(j, c);\n            final String word = sb.toString();\n            if (word.equals(end))\n              return ans;\n            if (bankSet.contains(word)) {\n              bankSet.remove(word);\n              q.offer(word);\n            }\n          }\n          sb.setCharAt(j, cache);\n        }\n      }\n    }\n\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minMutation(string start, string end, vector<string>& bank) {\n    unordered_set<string> bankSet{bank.begin(), bank.end()};\n    if (!bankSet.count(end))\n      return -1;\n\n    int ans = 0;\n    queue<string> q{{start}};\n\n    while (!q.empty()) {\n      ++ans;\n      for (int sz = q.size(); sz > 0; --sz) {\n        string word = q.front();\n        q.pop();\n        for (int j = 0; j < word.length(); ++j) {\n          const char cache = word[j];\n          for (const char c : {'A', 'C', 'G', 'T'}) {\n            word[j] = c;\n            if (word == end)\n              return ans;\n            if (bankSet.count(word)) {\n              bankSet.erase(word);\n              q.push(word);\n            }\n          }\n          word[j] = cache;\n        }\n      }\n    }\n\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/433.html",
    "category": "Algorithms",
    "acceptance_rate": 55.32049388983397,
    "topics": [
      "Hash Table",
      "String",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 3130,
    "dislikes": 341,
    "similar_questions": "[{\"title\": \"Word Ladder\", \"titleSlug\": \"word-ladder\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"226.7K\", \"totalSubmission\": \"409.7K\", \"totalAcceptedRaw\": 226662, \"totalSubmissionRaw\": 409726, \"acRate\": \"55.3%\"}",
    "title_pt": "Mutação Genética Mínima",
    "description_pt": "<p>Uma string de gene pode ser representada por uma string de 8 caracteres, com escolhas entre <code>&#39;A&#39;</code>, <code>&#39;C&#39;</code>, <code>&#39;G&#39;</code> e <code>&#39;T&#39;</code>.</p>\n\n<p>Suponha que precisamos investigar uma mutação de uma string de gene <code>startGene</code> para uma string de gene <code>endGene</code>, em que uma mutação é definida como uma única alteração de um caractere na string de gene.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;AACCGGTT&quot; --&gt; &quot;AACCGGTA&quot;</code> é uma mutação.</li>\n</ul>\n\n<p>Há também um banco de genes <code>bank</code> que registra todas as mutações genéticas válidas. Um gene deve estar em <code>bank</code> para que seja uma string de gene válida.</p>\n\n<p>Dadas as duas strings de gene <code>startGene</code> e <code>endGene</code> e o banco de genes <code>bank</code>, retorne <em>o número mínimo de mutações necessário para mutar de </em><code>startGene</code><em> para </em><code>endGene</code>. Se não houver tal mutação, retorne <code>-1</code>.</p>\n\n<p>Observe que o ponto de partida é assumido como válido, então ele pode não estar incluído no banco.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AACCGGTA&quot;, bank = [&quot;AACCGGTA&quot;]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> startGene = &quot;AACCGGTT&quot;, endGene = &quot;AAACGGTA&quot;, bank = [&quot;AACCGGTA&quot;,&quot;AACCGCTA&quot;,&quot;AAACGGTA&quot;]\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= bank.length &lt;= 10</code></li>\n\t<li><code>startGene.length == endGene.length == bank[i].length == 8</code></li>\n\t<li><code>startGene</code>, <code>endGene</code> e <code>bank[i]</code> consistem apenas dos caracteres <code>[&#39;A&#39;, &#39;C&#39;, &#39;G&#39;, &#39;T&#39;]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "434",
    "paidOnly": false,
    "title": "Number of Segments in a String",
    "titleSlug": "number-of-segments-in-a-string",
    "url": "https://leetcode.com/problems/number-of-segments-in-a-string",
    "description_url": "https://leetcode.com/problems/number-of-segments-in-a-string/description/",
    "description": "<p>Given a string <code>s</code>, return <em>the number of segments in the string</em>.</p>\n\n<p>A <strong>segment</strong> is defined to be a contiguous sequence of <strong>non-space characters</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Hello, my name is John&quot;\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The five segments are [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Hello&quot;\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 300</code></li>\n\t<li><code>s</code> consists of lowercase and uppercase English letters, digits, or one of the following characters <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li>\n\t<li>The only space character in <code>s</code> is <code>&#39; &#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-segments-in-a-string/solutions/",
    "solution": "[TOC]\n\n### Approach #1 Using Language Builtins [Accepted]\n\n**Intuition**\n\nIn a situation where raw efficiency is less important than code legibility,\nit is likely better to use language-idiomatic builtin functions to solve this\nproblem.\n\n**Algorithm**\n\nThere are a few corner cases that you can get snagged on in this problem, at\nleast in Java. First, one or more leading spaces will cause `split` to deduce\nan erroneous `\"\"` token at the beginning of the string, so we use the builtin\n`trim` method to remove leading and trailing spaces. Then, if the resulting\nstring is the empty string, then we can simply output `0`. This is necessary due\nto the following behavior of the `split` method:\n\n```java\nString[] tokens = \"\".split(\"\\\\s++\");\ntokens.length; // 1\ntokens[0]; // \"\"\n```\n\nIf we reach the final return statement, we `split` the trimmed string on\nsequences of one or more whitespace characters (`split` can take a regular\nexpression) and return the length of the resulting array.\n\nThe Python solution is trivially short because Python's `split` has a lot of\ndefault behavior that makes it perfect for this sort of problem. Notably, it\nreturns an empty list when `split`ting an empty string, it splits on\nwhitespace by default, and it implicitly `trim`s (`strip`s, in Python lingo)\nthe string beforehand.\n\n<iframe src=\"https://leetcode.com/playground/9TKJamrA/shared\" frameBorder=\"0\" width=\"100%\" height=\"208\" name=\"9TKJamrA\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$\\mathcal{O}(n)$$\n\n    All builtin language functionality used here (in both the Java and Python\n    examples) runs in either $$\\mathcal{O}(n)$$ or $$\\mathcal{O}(1)$$ time, so the entire algorithm\n    runs in linear time.\n\n* Space complexity : $$\\mathcal{O}(n)$$\n\n    `split` (in both languages) returns an array/list of $$\\mathcal{O}(n)$$ length, so\n    the algorithm uses linear additional space.\n\n---\n\n### Approach #2 In-place [Accepted]\n\n**Intuition**\n\nIf we cannot afford to allocate linear additional space, a fairly simple\nalgorithm can deduce the number of segments in linear time and constant\nspace.\n\n**Algorithm**\n\nTo count the number of segments, it is equivalent to count the number of\nstring indices at which a segment begins. Therefore, by formally defining the\ncharacteristics of such an index, we can simply iterate over the string and\ntest each index in turn. Such a definition is as follows: a string index\nbegins a segment if it is preceded by whitespace (or is the first index) and\nis not whitespace itself, which can be checked in constant time. Finally, we\nsimply return the number of indices for which the condition is satisfied.\n\n<iframe src=\"https://leetcode.com/playground/Vm2hu6P3/shared\" frameBorder=\"0\" width=\"100%\" height=\"276\" name=\"Vm2hu6P3\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$\\mathcal{O}(n)$$\n\n    We do a constant time check for each of the string's $$n$$ indices, so the\n    runtime is overall linear.\n\n* Space complexity : $$\\mathcal{O}(1)$$\n\n    There are only a few integers allocated, so the memory footprint is\n    constant.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countSegments(self, s: str) -> int:\n    return len(s.split())",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countSegments(String s) {\n    int ans = 0;\n\n    for (int i = 0; i < s.length(); ++i)\n      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' '))\n        ++ans;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countSegments(string s) {\n    int ans = 0;\n\n    for (int i = 0; i < s.length(); ++i)\n      if (s[i] != ' ' && (i == 0 || s[i - 1] == ' '))\n        ++ans;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/434.html",
    "category": "Algorithms",
    "acceptance_rate": 36.34266907672672,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 834,
    "dislikes": 1303,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"224.4K\", \"totalSubmission\": \"617.4K\", \"totalAcceptedRaw\": 224384, \"totalSubmissionRaw\": 617410, \"acRate\": \"36.3%\"}",
    "title_pt": "Número de Segmentos em uma String",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne <em>o número de segmentos na string</em>.</p>\n\n<p>Um <strong>segmento</strong> é definido como uma sequência contígua de <strong>caracteres que não são espaços</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Hello, my name is John&quot;\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Os cinco segmentos são [&quot;Hello,&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;John&quot;]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Hello&quot;\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= s.length &lt;= 300</code></li>\n\t<li><code>s</code> consiste em letras inglesas minúsculas e maiúsculas, dígitos, ou um dos seguintes caracteres <code>&quot;!@#$%^&amp;*()_+-=&#39;,.:&quot;</code>.</li>\n\t<li>O único caractere de espaço em <code>s</code> é <code>&#39; &#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "435",
    "paidOnly": false,
    "title": "Non-overlapping Intervals",
    "titleSlug": "non-overlapping-intervals",
    "url": "https://leetcode.com/problems/non-overlapping-intervals",
    "description_url": "https://leetcode.com/problems/non-overlapping-intervals/description/",
    "description": "<p>Given an array of intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping</em>.</p>\n\n<p><strong>Note</strong> that intervals which only touch at a point are <strong>non-overlapping</strong>. For example, <code>[1, 2]</code> and <code>[2, 3]</code> are non-overlapping.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> [1,3] can be removed and the rest of the intervals are non-overlapping.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,2],[1,2],[1,2]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> You need to remove two [1,2] to make the rest of the intervals non-overlapping.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,2],[2,3]]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> You don&#39;t need to remove any of the intervals since they&#39;re already non-overlapping.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/non-overlapping-intervals/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n    ans = 0\n    currentEnd = -math.inf\n\n    for interval in sorted(intervals, key=lambda x: x[1]):\n      if interval[0] >= currentEnd:\n        currentEnd = interval[1]\n      else:\n        ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int eraseOverlapIntervals(int[][] intervals) {\n    if (intervals.length == 0)\n      return 0;\n\n    Arrays.sort(intervals, (a, b) -> a[1] - b[1]);\n\n    int ans = 0;\n    int currentEnd = intervals[0][1];\n\n    for (int i = 1; i < intervals.length; ++i)\n      if (intervals[i][0] >= currentEnd)\n        currentEnd = intervals[i][1];\n      else\n        ++ans;\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int eraseOverlapIntervals(vector<vector<int>>& intervals) {\n    if (intervals.empty())\n      return 0;\n\n    sort(begin(intervals), end(intervals),\n         [](const auto& a, const auto& b) { return a[1] < b[1]; });\n\n    int ans = 0;\n    int currentEnd = intervals[0][1];\n\n    for (int i = 1; i < intervals.size(); ++i)\n      if (intervals[i][0] >= currentEnd)\n        currentEnd = intervals[i][1];\n      else\n        ++ans;\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/435.html",
    "category": "Algorithms",
    "acceptance_rate": 55.307454924707834,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 8613,
    "dislikes": 236,
    "similar_questions": "[{\"title\": \"Minimum Number of Arrows to Burst Balloons\", \"titleSlug\": \"minimum-number-of-arrows-to-burst-balloons\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Determine if Two Events Have Conflict\", \"titleSlug\": \"determine-if-two-events-have-conflict\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"774.2K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 774224, \"totalSubmissionRaw\": 1399862, \"acRate\": \"55.3%\"}",
    "title_pt": "Intervalos Não Sobrepostos",
    "description_pt": "<p>Dado um array de intervalos <code>intervals</code> em que <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, retorne <em>o número mínimo de intervalos que você precisa remover para tornar o restante dos intervalos não sobrepostos</em>.</p>\n\n<p><strong>Nota</strong> que intervalos que apenas se tocam em um ponto são <strong>não sobrepostos</strong>. Por exemplo, <code>[1, 2]</code> e <code>[2, 3]</code> são não sobrepostos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,2],[2,3],[3,4],[1,3]]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> [1,3] pode ser removido e o restante dos intervalos são não sobrepostos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,2],[1,2],[1,2]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Você precisa remover dois [1,2] para tornar o restante dos intervalos não sobrepostos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,2],[2,3]]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Você não precisa remover nenhum dos intervalos, pois eles já são não sobrepostos.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>-5 * 10<sup>4</sup> &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 5 * 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "436",
    "paidOnly": false,
    "title": "Find Right Interval",
    "titleSlug": "find-right-interval",
    "url": "https://leetcode.com/problems/find-right-interval",
    "description_url": "https://leetcode.com/problems/find-right-interval/description/",
    "description": "<p>You are given an array of <code>intervals</code>, where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> and each <code>start<sub>i</sub></code> is <strong>unique</strong>.</p>\n\n<p>The <strong>right interval</strong> for an interval <code>i</code> is an interval <code>j</code> such that <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> and <code>start<sub>j</sub></code> is <strong>minimized</strong>. Note that <code>i</code> may equal <code>j</code>.</p>\n\n<p>Return <em>an array of <strong>right interval</strong> indices for each interval <code>i</code></em>. If no <strong>right interval</strong> exists for interval <code>i</code>, then put <code>-1</code> at index <code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,2]]\n<strong>Output:</strong> [-1]\n<strong>Explanation:</strong> There is only one interval in the collection, so it outputs -1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[3,4],[2,3],[1,2]]\n<strong>Output:</strong> [-1,0,1]\n<strong>Explanation:</strong> There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start<sub>0</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3.\nThe right interval for [1,2] is [2,3] since start<sub>1</sub> = 2 is the smallest start that is &gt;= end<sub>2</sub> = 2.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> intervals = [[1,4],[2,3],[3,4]]\n<strong>Output:</strong> [-1,2,-1]\n<strong>Explanation:</strong> There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start<sub>2</sub> = 3 is the smallest start that is &gt;= end<sub>1</sub> = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li>The start point of each interval is <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-right-interval/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] findRightInterval(int[][] intervals) {\n    final int n = intervals.length;\n\n    int[] ans = new int[n];\n    java.util.NavigableMap<Integer, Integer> startToIndex = new TreeMap<>();\n\n    for (int i = 0; i < n; ++i)\n      startToIndex.put(intervals[i][0], i);\n\n    for (int i = 0; i < n; ++i) {\n      Map.Entry<Integer, Integer> entry = startToIndex.ceilingEntry(intervals[i][1]);\n      if (entry == null)\n        ans[i] = -1;\n      else\n        ans[i] = entry.getValue();\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findRightInterval(vector<vector<int>>& intervals) {\n    vector<int> ans;\n    map<int, int> startToIndex;\n\n    for (int i = 0; i < intervals.size(); ++i)\n      startToIndex[intervals[i][0]] = i;\n\n    for (const vector<int>& interval : intervals) {\n      const auto it = startToIndex.lower_bound(interval[1]);\n      if (it == cend(startToIndex))\n        ans.push_back(-1);\n      else\n        ans.push_back(it->second);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/436.html",
    "category": "Algorithms",
    "acceptance_rate": 53.71709849480065,
    "topics": [
      "Array",
      "Binary Search",
      "Sorting"
    ],
    "hints": [],
    "likes": 2259,
    "dislikes": 380,
    "similar_questions": "[{\"title\": \"Data Stream as Disjoint Intervals\", \"titleSlug\": \"data-stream-as-disjoint-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"135.8K\", \"totalSubmission\": \"252.7K\", \"totalAcceptedRaw\": 135756, \"totalSubmissionRaw\": 252724, \"acRate\": \"53.7%\"}",
    "title_pt": "Encontrar o Intervalo à Direita",
    "description_pt": "<p>Você recebe um array de <code>intervals</code>, onde <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code> e cada <code>start<sub>i</sub></code> é <strong>único</strong>.</p>\n\n<p>O <strong>intervalo à direita</strong> de um intervalo <code>i</code> é um intervalo <code>j</code> tal que <code>start<sub>j</sub> &gt;= end<sub>i</sub></code> e <code>start<sub>j</sub></code> é <strong>minimizado</strong>. Observe que <code>i</code> pode ser igual a <code>j</code>.</p>\n\n<p>Retorne <em>um array de índices de <strong>intervalos à direita</strong> para cada intervalo <code>i</code></em>. Se não existir nenhum <strong>intervalo à direita</strong> para o intervalo <code>i</code>, então coloque <code>-1</code> no índice <code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,2]]\n<strong>Saída:</strong> [-1]\n<strong>Explicação:</strong> Há apenas um intervalo na coleção, então ele produz -1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[3,4],[2,3],[1,2]]\n<strong>Saída:</strong> [-1,0,1]\n<strong>Explicação:</strong> Não há intervalo à direita para [3,4].\nO intervalo à direita para [2,3] é [3,4] pois start<sub>0</sub> = 3 é o menor start que é &gt;= end<sub>1</sub> = 3.\nO intervalo à direita para [1,2] é [2,3] pois start<sub>1</sub> = 2 é o menor start que é &gt;= end<sub>2</sub> = 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> intervals = [[1,4],[2,3],[3,4]]\n<strong>Saída:</strong> [-1,2,-1]\n<strong>Explicação:</strong> Não há intervalo à direita para [1,4] e [3,4].\nO intervalo à direita para [2,3] é [3,4] pois start<sub>2</sub> = 3 é o menor start que é &gt;= end<sub>1</sub> = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= intervals.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>intervals[i].length == 2</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= start<sub>i</sub> &lt;= end<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n\t<li>O ponto inicial de cada intervalo é <strong>único</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "437",
    "paidOnly": false,
    "title": "Path Sum III",
    "titleSlug": "path-sum-iii",
    "url": "https://leetcode.com/problems/path-sum-iii",
    "description_url": "https://leetcode.com/problems/path-sum-iii/description/",
    "description": "<p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p>\n\n<p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg\" style=\"width: 450px; height: 386px;\" />\n<pre>\n<strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The paths that sum to 8 are shown.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/path-sum-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def pathSum(self, root: TreeNode, summ: int) -> int:\n    if not root:\n      return 0\n\n    def dfs(root: TreeNode, summ: int) -> int:\n      if not root:\n        return 0\n      return (summ == root.val) + \\\n          dfs(root.left, summ - root.val) + \\\n          dfs(root.right, summ - root.val)\n\n    return dfs(root, summ) + \\\n        self.pathSum(root.left, summ) + \\\n        self.pathSum(root.right, summ)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int pathSum(TreeNode root, int sum) {\n    if (root == null)\n      return 0;\n    return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);\n  }\n\n  private int dfs(TreeNode root, int sum) {\n    if (root == null)\n      return 0;\n    return (sum == root.val ? 1 : 0) +\n        dfs(root.left, sum - root.val) +\n        dfs(root.right, sum - root.val);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int pathSum(TreeNode* root, int sum) {\n    if (root == nullptr)\n      return 0;\n    return dfs(root, sum) +\n           pathSum(root->left, sum) +\n           pathSum(root->right, sum);\n  }\n\n private:\n  int dfs(TreeNode* root, int sum) {\n    if (root == nullptr)\n      return 0;\n    return (sum == root->val) +\n           dfs(root->left, sum - root->val) +\n           dfs(root->right, sum - root->val);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/437.html",
    "category": "Algorithms",
    "acceptance_rate": 46.06568750698309,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 11474,
    "dislikes": 551,
    "similar_questions": "[{\"title\": \"Path Sum\", \"titleSlug\": \"path-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Path Sum II\", \"titleSlug\": \"path-sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum IV\", \"titleSlug\": \"path-sum-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Univalue Path\", \"titleSlug\": \"longest-univalue-path\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"688.5K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 688530, \"totalSubmissionRaw\": 1494674, \"acRate\": \"46.1%\"}",
    "title_pt": "Soma de Caminho III",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária e um inteiro <code>targetSum</code>, retorne <em>o número de caminhos cuja soma dos valores&nbsp;ao longo do caminho é igual a</em>&nbsp;<code>targetSum</code>.</p>\n\n<p>O caminho não precisa começar ou terminar na raiz ou em uma folha, mas deve seguir para baixo (isto é, viajando apenas de nós pai para nós filho).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg\" style=\"width: 450px; height: 386px;\" />\n<pre>\n<strong>Entrada:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os caminhos que somam 8 são mostrados.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 1000]</code>.</li>\n\t<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "438",
    "paidOnly": false,
    "title": "Find All Anagrams in a String",
    "titleSlug": "find-all-anagrams-in-a-string",
    "url": "https://leetcode.com/problems/find-all-anagrams-in-a-string",
    "description_url": "https://leetcode.com/problems/find-all-anagrams-in-a-string/description/",
    "description": "<p>Given two strings <code>s</code> and <code>p</code>, return an array of all the start indices of <code>p</code>&#39;s <span data-keyword=\"anagram\">anagrams</span> in <code>s</code>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot;\n<strong>Output:</strong> [0,6]\n<strong>Explanation:</strong>\nThe substring with start index = 0 is &quot;cba&quot;, which is an anagram of &quot;abc&quot;.\nThe substring with start index = 6 is &quot;bac&quot;, which is an anagram of &quot;abc&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abab&quot;, p = &quot;ab&quot;\n<strong>Output:</strong> [0,1,2]\n<strong>Explanation:</strong>\nThe substring with start index = 0 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;.\nThe substring with start index = 1 is &quot;ba&quot;, which is an anagram of &quot;ab&quot;.\nThe substring with start index = 2 is &quot;ab&quot;, which is an anagram of &quot;ab&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> and <code>p</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-all-anagrams-in-a-string/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findAnagrams(self, s: str, p: str) -> List[int]:\n    ans = []\n    count = Counter(p)\n    required = len(p)\n\n    for r, c in enumerate(s):\n      count[c] -= 1\n      if count[c] >= 0:\n        required -= 1\n      if r >= len(p):\n        count[s[r - len(p)]] += 1\n        if count[s[r - len(p)]] > 0:\n          required += 1\n      if required == 0:\n        ans.append(r - len(p) + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findAnagrams(String s, String p) {\n    List<Integer> ans = new ArrayList<>();\n    int[] count = new int[128];\n    int required = p.length();\n\n    for (final char c : p.toCharArray())\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (--count[s.charAt(r)] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 == p.length())\n          ans.add(l);\n        if (++count[s.charAt(l++)] > 0)\n          ++required;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findAnagrams(string s, string p) {\n    vector<int> ans;\n    vector<int> count(128);\n    int required = p.length();\n\n    for (const char c : p)\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s.length(); ++r) {\n      if (--count[s[r]] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 == p.length())\n          ans.push_back(l);\n        if (++count[s[l++]] > 0)\n          ++required;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/438.html",
    "category": "Algorithms",
    "acceptance_rate": 52.082743497217685,
    "topics": [
      "Hash Table",
      "String",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 12713,
    "dislikes": 353,
    "similar_questions": "[{\"title\": \"Valid Anagram\", \"titleSlug\": \"valid-anagram\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Permutation in String\", \"titleSlug\": \"permutation-in-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1011765, \"totalSubmissionRaw\": 1942615, \"acRate\": \"52.1%\"}",
    "title_pt": "Encontrar Todos os Anagramas em uma String",
    "description_pt": "<p>Dadas duas strings <code>s</code> e <code>p</code>, retorne um array com todos os índices iniciais dos <span data-keyword=\"anagram\">anagramas</span> de <code>p</code> em <code>s</code>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cbaebabacd&quot;, p = &quot;abc&quot;\n<strong>Saída:</strong> [0,6]\n<strong>Explicação:</strong>\nA substring com índice inicial = 0 é &quot;cba&quot;, que é um anagrama de &quot;abc&quot;.\nA substring com índice inicial = 6 é &quot;bac&quot;, que é um anagrama de &quot;abc&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abab&quot;, p = &quot;ab&quot;\n<strong>Saída:</strong> [0,1,2]\n<strong>Explicação:</strong>\nA substring com índice inicial = 0 é &quot;ab&quot;, que é um anagrama de &quot;ab&quot;.\nA substring com índice inicial = 1 é &quot;ba&quot;, que é um anagrama de &quot;ab&quot;.\nA substring com índice inicial = 2 é &quot;ab&quot;, que é um anagrama de &quot;ab&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length, p.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> e <code>p</code> consistem de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "440",
    "paidOnly": false,
    "title": "K-th Smallest in Lexicographical Order",
    "titleSlug": "k-th-smallest-in-lexicographical-order",
    "url": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order",
    "description_url": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/description/",
    "description": "<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 13, k = 2\n<strong>Output:</strong> 10\n<strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, k = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe need to find the `K`-th smallest number in lexicographical order within the range `[1, n]`. At first, this might seem like a simple sorting problem. We could list all the numbers, sort them in lexicographical order, and pick the `K`-th number. However, for large values of `n`, this becomes impractical due to the sheer size of the list we'd need to create.\n\nInstead of generating and sorting all the numbers, we can treat numbers as trees, where each node represents a number and its children represent numbers with the same prefix. Structuring numbers this way allows us to find the `K`-th smallest more efficiently.\n\nFor example, the number `1` has children `10`, `11`, `12`, ..., up to `19`. Similarly, `2` has children `20`, `21`,  ..., up to `29` and so on for other numbers. This gives us a prefix tree like structure where each node corresponds to a number and branches out to other numbers by appending digits. If we traverse this tree in lexicographical order, it’s as if we’re listing all numbers in their proper order.\n\n![digit tree](../Figures/440/lexico_number_tree.png)\n\n---\n\n### Approach: Prefix Tree\n\n#### Intuition\n\nWe begin by selecting the smallest lexicographical number, which is `1`. Since we've already counted `1` as the first number, we subtract `1` from `k` to account for that.\n\nNext, we calculate how many numbers exist in the subtree rooted at `curr` by defining a helper function `countSteps`, which counts the numbers between two prefixes [`curr` and `curr + 1`). It calculates numbers at each level, expanding the prefix as we go deeper.\n\nWe know the `k`-th number is not in this subtree if the number of steps (or numbers) under `curr` is smaller than or equal to `k`. Under these circumstances, we skip to the next sibling (`curr++`) and subtract the number of steps from `k` because we've skipped those numbers. \n\nOn the other hand, if the number of steps is larger than `k`, we know the `k`-th number is in the subtree rooted at `curr`. In that case, we move down one level by multiplying `curr` by 10, effectively moving to the next digit in the lexicographical tree. We also decrease `k` by 1 because we've taken one step deeper into the tree.\n\nWe repeat this process until `k` becomes zero, at which point we've found the `k`-th number, and we return `curr`.\n\n#### Algorithm\n\n- Initialize `curr` to 1 (current prefix) and decrement `k` by 1.\n- While `k` is greater than 0:\n  - Calculate the number of steps in the subtree rooted at `curr` using `countSteps(n, curr, curr + 1)`.\n  - If the number of steps is less than or equal to `k`:\n    - Increment `curr` by 1 to move to the next prefix.\n    - Decrement `k` by the number of skipped steps (i.e., `k -= step`).\n  - Otherwise:\n    - Multiply `curr` by 10 to move to the next level in the tree (i.e., `curr *= 10`).\n    - Decrement `k` by 1 to account for the current level.\n- Return the value of `curr` as the `k`-th smallest number in lexicographical order.\n\n- `countSteps` function:\n  - Initialize `steps` to 0 to keep track of the count of numbers in the range.\n  - While `prefix1` is less than or equal to `n`:\n    - Add the number of integers between `prefix1` and `prefix2` to `steps` using `steps += Math.min(n + 1, prefix2) - prefix1`. This ensures the count does not exceed `n` by capping `prefix2` at `n + 1` if `prefix2` is larger than `n`.\n    - Multiply `prefix1` and `prefix2` by 10 to move to the next level in the tree.\n  - Return the total number of steps counted.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/KYViuAd9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"KYViuAd9\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the input number.\n\n- Time complexity: $O(\\log(n)^2)$\n\n    The outer `while` loop runs as long as `k > 0`. In the worst case, it runs $O(\\log n)$ times, because at each step, we either move to the next prefix or move deeper into the tree (multiplying the current prefix by 10).\n\n    The `countSteps` function, which calculates the number of steps between two prefixes, runs in $O(\\log n)$ time, as it traverses deeper levels of the number range by multiplying the prefixes by 10 in each iteration.\n\n    Since the `countSteps` function is called inside the `while` loop, which also runs $O(\\log n)$ times, the overall time complexity is $O(\\log(n) \\times \\log(n)) = O(\\log(n)^2)$.\n\n- Space complexity: $O(1)$\n\n    The space complexity is $O(1)$ because we're only using a constant amount of additional space for variables like `curr`, `k`, `step`, `prefix1`, `prefix2`, etc. We're not using any data structures that grow with the input size.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findKthNumber(int n, int k) {\n    long currNum = 1;\n\n    for (int i = 1; i < k;) {\n      long gap = getGap(currNum, currNum + 1, n);\n      if (i + gap <= k) {\n        i += gap;\n        ++currNum;\n      } else {\n        ++i;\n        currNum *= 10;\n      }\n    }\n\n    return (int) currNum;\n  }\n\n  private long getGap(long a, long b, long n) {\n    long gap = 0;\n    while (a <= n) {\n      gap += Math.min(n + 1, b) - a;\n      a *= 10;\n      b *= 10;\n    }\n    return gap;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findKthNumber(long n, int k) {\n    auto getGap = [&n](long a, long b) {\n      long gap = 0;\n      while (a <= n) {\n        gap += min(n + 1, b) - a;\n        a *= 10;\n        b *= 10;\n      }\n      return gap;\n    };\n\n    long currNum = 1;\n\n    for (int i = 1; i < k;) {\n      long gap = getGap(currNum, currNum + 1);\n      if (i + gap <= k) {\n        i += gap;\n        ++currNum;\n      } else {\n        ++i;\n        currNum *= 10;\n      }\n    }\n\n    return currNum;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/440.html",
    "category": "Algorithms",
    "acceptance_rate": 41.99771728390856,
    "topics": [
      "Trie"
    ],
    "hints": [],
    "likes": 1325,
    "dislikes": 128,
    "similar_questions": "[{\"title\": \"Count Special Integers\", \"titleSlug\": \"count-special-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"98.6K\", \"totalSubmission\": \"234.8K\", \"totalAcceptedRaw\": 98614, \"totalSubmissionRaw\": 234808, \"acRate\": \"42.0%\"}",
    "title_pt": "K-ésimo Menor em Ordem Lexicográfica",
    "description_pt": "<p>Dados dois inteiros <code>n</code> e <code>k</code>, retorne <em>o</em> <code>k<sup>ésimo</sup></code> <em>inteiro lexicograficamente menor no intervalo</em> <code>[1, n]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 13, k = 2\n<strong>Saída:</strong> 10\n<strong>Explicação:</strong> A ordem lexicográfica é [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], então o segundo menor número é 10.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, k = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "441",
    "paidOnly": false,
    "title": "Arranging Coins",
    "titleSlug": "arranging-coins",
    "url": "https://leetcode.com/problems/arranging-coins",
    "description_url": "https://leetcode.com/problems/arranging-coins/description/",
    "description": "<p>You have <code>n</code> coins and you want to build a staircase with these coins. The staircase consists of <code>k</code> rows where the <code>i<sup>th</sup></code> row has exactly <code>i</code> coins. The last row of the staircase <strong>may be</strong> incomplete.</p>\n\n<p>Given the integer <code>n</code>, return <em>the number of <strong>complete rows</strong> of the staircase you will build</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> n = 5\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Because the 3<sup>rd</sup> row is incomplete, we return 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg\" style=\"width: 333px; height: 333px;\" />\n<pre>\n<strong>Input:</strong> n = 8\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Because the 4<sup>th</sup> row is incomplete, we return 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/arranging-coins/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def arrangeCoins(self, n: int) -> int:\n    return int((-1 + sqrt(8 * n + 1)) // 2)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int arrangeCoins(long n) {\n    return (int) (-1 + Math.sqrt(8 * n + 1)) / 2;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int arrangeCoins(long n) {\n    return (-1 + sqrt(8 * n + 1)) / 2;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/441.html",
    "category": "Algorithms",
    "acceptance_rate": 47.28342650732927,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [],
    "likes": 4097,
    "dislikes": 1353,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"527.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 527266, \"totalSubmissionRaw\": 1115118, \"acRate\": \"47.3%\"}",
    "title_pt": "Arrumando Moedas",
    "description_pt": "<p>Você tem <code>n</code> moedas e quer construir uma escada com essas moedas. A escada consiste em <code>k</code> linhas, onde a <code>i<sup>ésima</sup></code> linha tem exatamente <code>i</code> moedas. A última linha da escada <strong>pode ser</strong> incompleta.</p>\n\n<p>Dado o inteiro <code>n</code>, retorne <em>o número de <strong>linhas completas</strong> da escada que você construirá</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/arrangecoins1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Como a 3<sup>ª</sup> linha está incompleta, retornamos 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/arrangecoins2-grid.jpg\" style=\"width: 333px; height: 333px;\" />\n<pre>\n<strong>Entrada:</strong> n = 8\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Como a 4<sup>ª</sup> linha está incompleta, retornamos 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "442",
    "paidOnly": false,
    "title": "Find All Duplicates in an Array",
    "titleSlug": "find-all-duplicates-in-an-array",
    "url": "https://leetcode.com/problems/find-all-duplicates-in-an-array",
    "description_url": "https://leetcode.com/problems/find-all-duplicates-in-an-array/description/",
    "description": "<p>Given an integer array <code>nums</code> of length <code>n</code> where all the integers of <code>nums</code> are in the range <code>[1, n]</code> and each integer appears <strong>at most</strong> <strong>twice</strong>, return <em>an array of all the integers that appears <strong>twice</strong></em>.</p>\n\n<p>You must write an algorithm that runs in <code>O(n)</code> time and uses only <em>constant</em> auxiliary space, excluding the space needed to store the output</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1]\n<strong>Output:</strong> [2,3]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1,2]\n<strong>Output:</strong> [1]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [1]\n<strong>Output:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n\t<li>Each element in <code>nums</code> appears <strong>once</strong> or <strong>twice</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-all-duplicates-in-an-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findDuplicates(self, nums: List[int]) -> List[int]:\n    ans = []\n\n    for num in nums:\n      nums[abs(num) - 1] *= -1\n      if nums[abs(num) - 1] > 0:\n        ans.append(abs(num))\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findDuplicates(int[] nums) {\n    List<Integer> ans = new ArrayList<>();\n\n    for (final int num : nums) {\n      nums[Math.abs(num) - 1] *= -1;\n      if (nums[Math.abs(num) - 1] > 0)\n        ans.add(Math.abs(num));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findDuplicates(vector<int>& nums) {\n    vector<int> ans;\n\n    for (const int num : nums) {\n      nums[abs(num) - 1] *= -1;\n      if (nums[abs(num) - 1] > 0)\n        ans.push_back(abs(num));\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/442.html",
    "category": "Algorithms",
    "acceptance_rate": 76.34636183940626,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [],
    "likes": 10765,
    "dislikes": 423,
    "similar_questions": "[{\"title\": \"Find All Numbers Disappeared in an Array\", \"titleSlug\": \"find-all-numbers-disappeared-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Distances\", \"titleSlug\": \"sum-of-distances\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Two Sneaky Numbers of Digitville\", \"titleSlug\": \"the-two-sneaky-numbers-of-digitville\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"900.7K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 900712, \"totalSubmissionRaw\": 1179771, \"acRate\": \"76.3%\"}",
    "title_pt": "Encontrar Todos os Duplicados em um Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> de comprimento <code>n</code>, em que todos os inteiros de <code>nums</code> estão no intervalo <code>[1, n]</code> e cada inteiro aparece <strong>no máximo</strong> <strong>duas vezes</strong>, retorne <em>um array com todos os inteiros que aparecem <strong>duas vezes</strong></em>.</p>\n\n<p>Você deve escrever um algoritmo que execute em tempo <code>O(n)</code> e use apenas espaço auxiliar <em>constante</em>, excluindo o espaço necessário para armazenar a saída</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [4,3,2,7,8,2,3,1]\n<strong>Saída:</strong> [2,3]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1,2]\n<strong>Saída:</strong> [1]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n\t<li>Cada elemento em <code>nums</code> aparece <strong>uma vez</strong> ou <strong>duas vezes</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "443",
    "paidOnly": false,
    "title": "String Compression",
    "titleSlug": "string-compression",
    "url": "https://leetcode.com/problems/string-compression",
    "description_url": "https://leetcode.com/problems/string-compression/description/",
    "description": "<p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p>\n\n<p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p>\n\n<ul>\n\t<li>If the group&#39;s length is <code>1</code>, append the character to <code>s</code>.</li>\n\t<li>Otherwise, append the character followed by the group&#39;s length.</li>\n</ul>\n\n<p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p>\n\n<p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p>\n\n<p>You must write an algorithm that uses only constant extra space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;]\n<strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;]\n<strong>Explanation:</strong> The groups are &quot;aa&quot;, &quot;bb&quot;, and &quot;ccc&quot;. This compresses to &quot;a2b2c3&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> chars = [&quot;a&quot;]\n<strong>Output:</strong> Return 1, and the first character of the input array should be: [&quot;a&quot;]\n<strong>Explanation:</strong> The only group is &quot;a&quot;, which remains uncompressed since it&#39;s a single character.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;]\n<strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;].\n<strong>Explanation:</strong> The groups are &quot;a&quot; and &quot;bbbbbbbbbbbb&quot;. This compresses to &quot;ab12&quot;.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= chars.length &lt;= 2000</code></li>\n\t<li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/string-compression/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n#### Intuition\n\nFirst, we make the following observation. Consider a group `t` of consecutive repeating characters. The length of compressed `t` is less than or equal to the length of `t`. For example, `d` tranforms into `d`, `cc` into `c2`, `aaaa` into `a4`, `bbbbbbbbbbbb` into `b12`.\n\nThis observation allows processing groups in the array `chars` from left to right.\n\n!?!../Documents/443/slideshow.json:960,540!?!\n\nIn the slideshow above, we compress the array `chars = [\"c\",\"c\",\"b\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\",\"a\"]`. First, we process the group `cc`, then `b`, and finally `aaaaaaaaaa`.\n\nUnprocessed characters are in white cells.\n\nProcessed characters that we may overwrite in the future are in blue cells.\n\nCharacters that belong to the answer and will not change are in green cells.\n\nWhen processing a group, we first find its size `groupLength` and paint its cells blue. Then we append the character of the group to the answer. If `groupLength` is greater than $1$, we also append the string representation of `groupLength` to the answer. Because the problem wants us to form the answer in place, instead of \"appending\" to the answer we will overwrite the corresponding blue cells by repainting them green.\n\nWhite cells will eventually become blue and blue ones may become green. Since the compressed group takes up fewer cells than the uncompressed, the white cell cannot immediately become green.\n\n#### Algorithm\n\n1. Declare the variables `i` – the first index of the current group, and `res` – the length of the answer (of the compressed string). Initialize `i = 0`, `res = 0`.\n2. While `i` is less than the length of `chars`:\n\t* Find the length of the current group of consecutive repeating characters `groupLength`.\n\t* Add `chars[i]` to the answer (`chars[res++] = chars[i]`).\n\t* If `groupLength > 1`, add the string representation of `groupLength` to the answer and increase `res` accordingly.\n\t* Increase `i` by `groupLength` and proceed to the next group.\n3. Return `res`.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/6To4QHZq/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"6To4QHZq\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $n$ be the length of `chars`.\n\n* Time complexity: $O(n)$.\n\n\tAll cells are initially white. We will repaint each white cell blue, and we may repaint some blue cells green. Thus each cell will be repainted at most twice. Since there are $n$ cells, the total number of repaintings is $O(n)$.\n\n* Space complexity: $O(1)$.\n\n\tWe store only a few integer variables and the string representation of `groupLength` which takes up $O(1)$ space.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def compress(self, chars: List[str]) -> int:\n    ans = 0\n    i = 0\n\n    while i < len(chars):\n      letter = chars[i]\n      count = 0\n      while i < len(chars) and chars[i] == letter:\n        count += 1\n        i += 1\n      chars[ans] = letter\n      ans += 1\n      if count > 1:\n        for c in str(count):\n          chars[ans] = c\n          ans += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int compress(char[] chars) {\n    int ans = 0;\n\n    for (int i = 0; i < chars.length;) {\n      final char letter = chars[i];\n      int count = 0;\n      while (i < chars.length && chars[i] == letter) {\n        ++count;\n        ++i;\n      }\n      chars[ans++] = letter;\n      if (count > 1)\n        for (final char c : String.valueOf(count).toCharArray())\n          chars[ans++] = c;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int compress(vector<char>& chars) {\n    int ans = 0;\n\n    for (int i = 0; i < chars.size();) {\n      const char letter = chars[i];\n      int count = 0;\n      while (i < chars.size() && chars[i] == letter) {\n        ++count;\n        ++i;\n      }\n      chars[ans++] = letter;\n      if (count > 1)\n        for (const char c : to_string(count))\n          chars[ans++] = c;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/443.html",
    "category": "Algorithms",
    "acceptance_rate": 57.854405868944546,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [
      "How do you know if you are at the end of a consecutive group of characters?"
    ],
    "likes": 5614,
    "dislikes": 8504,
    "similar_questions": "[{\"title\": \"Count and Say\", \"titleSlug\": \"count-and-say\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Encode and Decode Strings\", \"titleSlug\": \"encode-and-decode-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design Compressed String Iterator\", \"titleSlug\": \"design-compressed-string-iterator\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Decompress Run-Length Encoded List\", \"titleSlug\": \"decompress-run-length-encoded-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"String Compression III\", \"titleSlug\": \"string-compression-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Better Compression of String\", \"titleSlug\": \"better-compression-of-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"848.2K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 848229, \"totalSubmissionRaw\": 1466148, \"acRate\": \"57.9%\"}",
    "title_pt": "Compressão de String",
    "description_pt": "<p>Dado um array de caracteres <code>chars</code>, comprima-o usando o seguinte algoritmo:</p>\n\n<p>Comece com uma string vazia <code>s</code>. Para cada grupo de <strong>caracteres consecutivos repetidos</strong> em <code>chars</code>:</p>\n\n<ul>\n\t<li>Se o comprimento do grupo for <code>1</code>, acrescente o caractere a <code>s</code>.</li>\n\t<li>Caso contrário, acrescente o caractere seguido do comprimento do grupo.</li>\n</ul>\n\n<p>A string comprimida <code>s</code> <strong>não deve ser retornada separadamente</strong>, mas, em vez disso, deve ser armazenada <strong>no array de caracteres de entrada <code>chars</code></strong>. Observe que comprimentos de grupo que sejam <code>10</code> ou maiores serão विभididos em múltiplos caracteres em <code>chars</code>.</p>\n\n<p>Depois de terminar de <strong>modificar o array de entrada,</strong> retorne <em>o novo comprimento do array</em>.</p>\n\n<p>Você deve লিখar um algoritmo que use apenas espaço extra constante.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> chars = [&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;c&quot;,&quot;c&quot;,&quot;c&quot;]\n<strong>Saída:</strong> Retorne 6, e os primeiros 6 caracteres do array de entrada devem ser: [&quot;a&quot;,&quot;2&quot;,&quot;b&quot;,&quot;2&quot;,&quot;c&quot;,&quot;3&quot;]\n<strong>Explicação:</strong> Os grupos são &quot;aa&quot;, &quot;bb&quot; e &quot;ccc&quot;. Isso se comprime para &quot;a2b2c3&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> chars = [&quot;a&quot;]\n<strong>Saída:</strong> Retorne 1, e o primeiro caractere do array de entrada deve ser: [&quot;a&quot;]\n<strong>Explicação:</strong> O único grupo é &quot;a&quot;, que permanece descomprimido pois é um único caractere.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> chars = [&quot;a&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;,&quot;b&quot;]\n<strong>Saída:</strong> Retorne 4, e os primeiros 4 caracteres do array de entrada devem ser: [&quot;a&quot;,&quot;b&quot;,&quot;1&quot;,&quot;2&quot;].\n<strong>Explicação:</strong> Os grupos são &quot;a&quot; e &quot;bbbbbbbbbbbb&quot;. Isso se comprime para &quot;ab12&quot;.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= chars.length &lt;= 2000</code></li>\n\t<li><code>chars[i]</code> é uma letra minúscula do inglês, letra maiúscula do inglês, dígito ou símbolo.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Como você sabe se está no final de um grupo consecutivo de caracteres?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "445",
    "paidOnly": false,
    "title": "Add Two Numbers II",
    "titleSlug": "add-two-numbers-ii",
    "url": "https://leetcode.com/problems/add-two-numbers-ii",
    "description_url": "https://leetcode.com/problems/add-two-numbers-ii/description/",
    "description": "<p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p>\n\n<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg\" style=\"width: 523px; height: 342px;\" />\n<pre>\n<strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4]\n<strong>Output:</strong> [7,8,0,7]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4]\n<strong>Output:</strong> [8,0,7]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> l1 = [0], l2 = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>It is guaranteed that the list represents a number that does not have leading zeros.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>\n",
    "solution_url": "https://leetcode.com/problems/add-two-numbers-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Reverse Given Linked Lists\n\n#### Intuition\n\nWe are told that the most significant digit comes first, and that each of their nodes includes a single digit. To do a basic addition of two numbers using a sum of two digits and a carry, we must start with the least significant digits (the lowest place) and work our way up to the most significant digits.\n\nTo get the order of digits from the least significant digits to the the most significant digits, we can reverse the given lists so the least significant digits come first.\n\nWe can then iterate over the reversed lists to perform the addition of digits at corresponding places similar to the first approach.\n\nLet's understand how to reverse a linked list. This is a classical problem that you can try [here](https://leetcode.com/problems/reverse-linked-list/).\n\nTo reverse a linked list, we need three pointers. The first pointer `head` points to the current node under consideration, `temp` points to the next node, and `prev` points to the previous node. This is because while traversing the list, we change the current node's (`head`) next pointer to point to its previous element (`prev`). Since a node does not have reference to its previous node, we must store its previous element beforehand. We also need another pointer to store the next node (`temp`) before changing the reference so we don't lose it after changing `head.next`.\n\nWe start with initializing `prev` to `null`. We then loop until `head` is null, i.e., until we iterate over all the elements. We store `head.next` in `temp` to store the next node we will go to. After storing the next node, we reverse `next` of `head` to the previous element, i.e., `head.next = prev`. We then move `prev` to `head` as this becomes the previous node for the next node and also move `head` to `temp` as this becomes the new node under consideration.\n\nHere's an animation visually showing how the approach works:\n\n!?!../Documents/445/445-slides.json:601,301!?!\n\n#### Algorithm\n\n1. Create two linked lists `r1` and `r2` to store the reverse of the linked lists `l1` and `l2` respectively. \n2. Create two integers `totalSum` and `carry` to store the sum and carry of current digits.\n3. Create a new `ListNode`, `ans` that will store the sum of current digits. \n4. We will add the two numbers using the reverse list by adding the digits one by one. We continue until we cover all the nodes in `r1` and `r2`:\n    - If `r1` is not `null`, we add `r1.val` to `totalSum`.\n    - If `r2` is not `null`, we add `r2.val` to `totalSum`.\n    - Set `ans.val = totalSum % 10`.  \n    - Store the `carry` as `totalSum / 10`. \n    - Create a new `ListNode`, `newNode` that will have `val` as `carry`. Set `next` of `newNode` to `ans`. Update `ans = newNode` to use the same variable `ans` for the next iteration.\n    - Update `totalSum = carry`.\n7. If `carry == 0`, it means the `newNode` that we created in the final iteration of while loop has `val = 0`. Because we perform `ans = newNode` at the end of each while loop iteration while loop, to avoid returning a linked list with a head of `0` (leading zero), we return the next element, i.e., we return `ans.next`. Otherwise, if `carry` is not equal to `0`, the value of `ans` is non-zero. Hence, we just return `ans`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/SxRyzmP8/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"SxRyzmP8\"></iframe>\n\n#### Complexity Analysis\n\nHere, $m$ and $n$ are is the number of nodes in `l1` and `l2` respectively\n\n* Time complexity: $O(m + n)$\n\n    - Reversing the list `l1` and `l2`  take $O(m)$ and $O(n)$ time respectively.\n    - We then iterate over digits of the both lists. We iterate until both the lists are fully traversed. We iterate in the while loop `max(m, n)` times. We compute `totalSum`, `carry` and create a new node in each iteration which takes $O(1)$ time. Hence, the complexity of all the while loop can be written as $O(m + n)$ time.\n\n* Space complexity: $O(m + n)$\n\n    - As we have reversed the input linked lists, we will count the space consumed by the reversed lists. The `r1` linked list takes $O(m)$ space and `r2` takes $O(n)$ space.\n    - Note: one could argue that because `r1` and `r2` are only referencing the input lists and not making copies of them, we are using $O(1)$ space. In most problems, you wouldn't count the input as part of the space complexity because the input doesn't contribute toward the algorithm. In this approach, the input is used heavily by our algorithm in terms of logic, and thus, we are counting it as part of the space complexity.\n\n---\n\n### Approach 2: Stack\n\n#### Intuition\n\nOur task is to do a basic addition of two numbers starting with the least significant digits and working our way up to the most significant digits. In the previous approach, we reversed the linked lists to access the least significant digits first. We can also use **stacks** to access the least significant digits first.\n\nThe advantage of using a stack is that when we loop over a given linked list from the first node to the last and push all the digits in the stack, the top of the stack will have the least significant digit and the bottom will contain the most significant digit.\n\nWe can add the digits at corresponding places of the linked lists using the two stacks moving from the least to the most significant digits using the stack's `pop` method.\n\nHere's a brief visual representation explaining the approach:\n\n![img](../Figures/445/445-stack.png)\n\n#### Algorithm\n\n1. Create two integer stacks `s1` and `s2` to store the integers of the linked lists `l1` and `l2` respectively. \n2. Push all the integers of `l1` in `s1` starting from the integer at the first node. The most significant comes first in the list, so it will be stored at the bottom of the stack and the least significant digit will stored at the top.\n3. Similarly, push all the integers of `l2` in `s2`.\n4. Create two integers `totalSum` and `carry` to store the sum and carry of current digits.\n5. Create a new `ListNode`, `ans` that will store the answer. \n6. We will add the two numbers present in the linked list now by adding the digits one by one. We continue until both `s1` and `s2` are empty:\n    - If `s1` is not empty, pop the first element from the stack and add it to `totalSum`.\n    - If `s2` is not empty, pop the first element from the stack and add it to `totalSum`.\n    - Set `ans.val = totalSum % 10`.  \n    - Store the `carry` as `totalSum / 10`. \n    - Create a new `ListNode`, `newNode` that will have `val` as `carry`. Set `next` of `newNode` to `ans`. Update `ans = newNode` to use the same variable `ans` for the next iteration.\n    - Update `totalSum = carry`.\n7. If `carry == 0`, it means the `newNode` that we created in the final iteration of while loop has `val = 0`. Because we perform `ans = newNode` at the end of each while loop, to avoid returning a linked list with a head of `0` (leading zero), we return the next element, i.e., we return `ans.next`. Otherwise, if `carry` is not equal to `0`, the value of `ans` is non-zero. Hence, we just return `ans`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/3xMD2Xjx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3xMD2Xjx\"></iframe>\n\n#### Complexity Analysis\n\nHere, $m$ and $n$ are is the number of nodes in `l1` and `l2` respectively\n\n* Time complexity: $O(m + n)$\n\n    - Iterating over both the lists and pushing all the values in the respective stacks take $O(m + n)$ time.\n    - We then iterate over digits of the both lists. We iterate until both the stacks are empty. We iterate in the while loop `max(m, n)` times. We compute `sum`, `carry` and create a new node in each iteration which takes $O(1)$ time. Hence, the complexity of all the while loop can be written as $O(m + n)$ time.\n\n* Space complexity: $O(m + n)$\n\n    - The `s1` stack takes $O(m)$ space and the `s2` stack takes $O(n)$ space.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n    stack1 = []\n    stack2 = []\n\n    while l1:\n      stack1.append(l1)\n      l1 = l1.next\n\n    while l2:\n      stack2.append(l2)\n      l2 = l2.next\n\n    head = None\n    carry = 0\n\n    while carry or stack1 or stack2:\n      if stack1:\n        carry += stack1.pop().val\n      if stack2:\n        carry += stack2.pop().val\n      node = ListNode(carry % 10)\n      node.next = head\n      head = node\n      carry //= 10\n\n    return head",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n    Deque<ListNode> stack1 = new ArrayDeque<>();\n    Deque<ListNode> stack2 = new ArrayDeque<>();\n\n    while (l1 != null) {\n      stack1.push(l1);\n      l1 = l1.next;\n    }\n\n    while (l2 != null) {\n      stack2.push(l2);\n      l2 = l2.next;\n    }\n\n    ListNode head = null;\n    int carry = 0;\n\n    while (carry > 0 || !stack1.isEmpty() || !stack2.isEmpty()) {\n      if (!stack1.isEmpty())\n        carry += stack1.pop().val;\n      if (!stack2.isEmpty())\n        carry += stack2.pop().val;\n      ListNode node = new ListNode(carry % 10);\n      node.next = head;\n      head = node;\n      carry /= 10;\n    }\n\n    return head;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n    stack<ListNode*> stack1;\n    stack<ListNode*> stack2;\n\n    while (l1) {\n      stack1.push(l1);\n      l1 = l1->next;\n    }\n\n    while (l2) {\n      stack2.push(l2);\n      l2 = l2->next;\n    }\n\n    ListNode* head = nullptr;\n    int carry = 0;\n\n    while (carry || !stack1.empty() || !stack2.empty()) {\n      if (!stack1.empty())\n        carry += stack1.top()->val, stack1.pop();\n      if (!stack2.empty())\n        carry += stack2.top()->val, stack2.pop();\n      ListNode* node = new ListNode(carry % 10);\n      node->next = head;\n      head = node;\n      carry /= 10;\n    }\n\n    return head;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/445.html",
    "category": "Algorithms",
    "acceptance_rate": 61.688347633545526,
    "topics": [
      "Linked List",
      "Math",
      "Stack"
    ],
    "hints": [],
    "likes": 6023,
    "dislikes": 297,
    "similar_questions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Two Polynomials Represented as Linked Lists\", \"titleSlug\": \"add-two-polynomials-represented-as-linked-lists\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"523.8K\", \"totalSubmission\": \"849K\", \"totalAcceptedRaw\": 523763, \"totalSubmissionRaw\": 849050, \"acRate\": \"61.7%\"}",
    "title_pt": "Adicionar Dois Números II",
    "description_pt": "<p>Você recebe duas linked lists <strong>não vazias</strong> representando dois inteiros não negativos. O dígito mais significativo vem primeiro e cada um de seus nós contém um único dígito. Some os dois números e retorne a soma como uma linked list.</p>\n\n<p>Você pode assumir que os dois números não contêm nenhum zero à esquerda, exceto o próprio número 0.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg\" style=\"width: 523px; height: 342px;\" />\n<pre>\n<strong>Entrada:</strong> l1 = [7,2,4,3], l2 = [5,6,4]\n<strong>Saída:</strong> [7,8,0,7]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> l1 = [2,4,3], l2 = [5,6,4]\n<strong>Saída:</strong> [8,0,7]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> l1 = [0], l2 = [0]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em cada linked list está no intervalo <code>[1, 100]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 9</code></li>\n\t<li>É гарантido que a lista representa um número que não possui zeros à esquerda.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong>&nbsp;Você conseguiria resolvê-lo sem inverter as listas de entrada?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "446",
    "paidOnly": false,
    "title": "Arithmetic Slices II - Subsequence",
    "titleSlug": "arithmetic-slices-ii-subsequence",
    "url": "https://leetcode.com/problems/arithmetic-slices-ii-subsequence",
    "description_url": "https://leetcode.com/problems/arithmetic-slices-ii-subsequence/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the number of all the <strong>arithmetic subsequences</strong> of</em> <code>nums</code>.</p>\n\n<p>A sequence of numbers is called arithmetic if it consists of <strong>at least three elements</strong> and if the difference between any two consecutive elements is the same.</p>\n\n<ul>\n\t<li>For example, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, and <code>[3, -1, -5, -9]</code> are arithmetic sequences.</li>\n\t<li>For example, <code>[1, 1, 2, 5, 7]</code> is not an arithmetic sequence.</li>\n</ul>\n\n<p>A <strong>subsequence</strong> of an array is a sequence that can be formed by removing some elements (possibly none) of the array.</p>\n\n<ul>\n\t<li>For example, <code>[2,5,10]</code> is a subsequence of <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li>\n</ul>\n\n<p>The test cases are generated so that the answer fits in <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,4,6,8,10]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [7,7,7,7,7]\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> Any subsequence of this array is arithmetic.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/arithmetic-slices-ii-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numberOfArithmeticSlices(int[] nums) {\n    final int n = nums.length;\n    int ans = 0;\n    // dp[i][j] := # of subseqs end w/ nums[j] nums[i]\n    int[][] dp = new int[n][n];\n    Map<Long, List<Integer>> numToIndices = new HashMap<>();\n\n    for (int i = 0; i < n; ++i) {\n      numToIndices.putIfAbsent((long) nums[i], new ArrayList<>());\n      numToIndices.get((long) nums[i]).add(i);\n    }\n\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < i; ++j) {\n        final long target = nums[j] * 2L - nums[i];\n        if (numToIndices.containsKey(target))\n          for (final int k : numToIndices.get(target))\n            if (k < j)\n              dp[i][j] += (dp[j][k] + 1);\n        ans += dp[i][j];\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numberOfArithmeticSlices(vector<int>& nums) {\n    const int n = nums.size();\n    int ans = 0;\n    // dp[i][j] := # of subseqs end w/ nums[j] nums[i]\n    vector<vector<int>> dp(n, vector<int>(n));\n    unordered_map<long, vector<int>> numToIndices;\n\n    for (int i = 0; i < n; ++i)\n      numToIndices[nums[i]].push_back(i);\n\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < i; ++j) {\n        const long target = nums[j] * 2L - nums[i];\n        if (numToIndices.count(target))\n          for (const int k : numToIndices[target])\n            if (k < j)\n              dp[i][j] += (dp[j][k] + 1);\n        ans += dp[i][j];\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/446.html",
    "category": "Algorithms",
    "acceptance_rate": 54.53045672139408,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 3414,
    "dislikes": 161,
    "similar_questions": "[{\"title\": \"Arithmetic Slices\", \"titleSlug\": \"arithmetic-slices\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Destroy Sequential Targets\", \"titleSlug\": \"destroy-sequential-targets\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Palindromic Subsequences\", \"titleSlug\": \"count-palindromic-subsequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"158K\", \"totalSubmission\": \"289.7K\", \"totalAcceptedRaw\": 157996, \"totalSubmissionRaw\": 289739, \"acRate\": \"54.5%\"}",
    "title_pt": "Somas Aritméticas II - Subsequência",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o número de todas as <strong>subsequências aritméticas</strong> de</em> <code>nums</code>.</p>\n\n<p>Uma sequência de números é chamada aritmética se consiste em <strong>pelo menos três elementos</strong> e se a diferença entre quaisquer dois elementos consecutivos é a mesma.</p>\n\n<ul>\n\t<li>Por exemplo, <code>[1, 3, 5, 7, 9]</code>, <code>[7, 7, 7, 7]</code>, e <code>[3, -1, -5, -9]</code> são sequências aritméticas.</li>\n\t<li>Por exemplo, <code>[1, 1, 2, 5, 7]</code> não é uma sequência aritmética.</li>\n</ul>\n\n<p>Uma <strong>subsequência</strong> de um array é uma sequência que pode ser formada removendo alguns elementos (possivelmente nenhum) do array.</p>\n\n<ul>\n\t<li>Por exemplo, <code>[2,5,10]</code> é uma subsequência de <code>[1,2,1,<strong><u>2</u></strong>,4,1,<u><strong>5</strong></u>,<u><strong>10</strong></u>]</code>.</li>\n</ul>\n\n<p>Os casos de teste são gerados de forma que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,4,6,8,10]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> Todas as fatias de subsequências aritméticas são:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [7,7,7,7,7]\n<strong>Saída:</strong> 16\n<strong>Explicação:</strong> Qualquer subsequência deste array é aritmética.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1&nbsp; &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "447",
    "paidOnly": false,
    "title": "Number of Boomerangs",
    "titleSlug": "number-of-boomerangs",
    "url": "https://leetcode.com/problems/number-of-boomerangs",
    "description_url": "https://leetcode.com/problems/number-of-boomerangs/description/",
    "description": "<p>You are given <code>n</code> <code>points</code> in the plane that are all <strong>distinct</strong>, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. A <strong>boomerang</strong> is a tuple of points <code>(i, j, k)</code> such that the distance between <code>i</code> and <code>j</code> equals the distance between <code>i</code> and <code>k</code> <strong>(the order of the tuple matters)</strong>.</p>\n\n<p>Return <em>the number of boomerangs</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[0,0],[1,0],[2,0]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[1,1],[2,2],[3,3]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[1,1]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == points.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 500</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>All the points are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-boomerangs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n    ans = 0\n\n    for x1, y1 in points:\n      count = defaultdict(int)\n      for x2, y2 in points:\n        ans += 2 * count[(x1 - x2)**2 + (y1 - y2)**2]\n        count[(x1 - x2)**2 + (y1 - y2)**2] += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numberOfBoomerangs(int[][] points) {\n    int ans = 0;\n\n    for (int[] p : points) {\n      Map<Integer, Integer> distCount = new HashMap<>();\n      for (int[] q : points) {\n        final int dist = (int) getDist(p, q);\n        distCount.put(dist, distCount.getOrDefault(dist, 0) + 1);\n      }\n      for (final int freq : distCount.values())\n        ans += freq * (freq - 1); // C(freq, 2)\n    }\n\n    return ans;\n  }\n\n  private double getDist(int[] p, int[] q) {\n    return Math.pow(p[0] - q[0], 2) + Math.pow(p[1] - q[1], 2);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numberOfBoomerangs(vector<vector<int>>& points) {\n    int ans = 0;\n\n    for (const vector<int>& p : points) {\n      unordered_map<int, int> distCount;\n      for (const vector<int>& q : points) {\n        const int dist = getDist(p, q);\n        ++distCount[dist];\n      }\n      for (const auto& [_, freq] : distCount)\n        ans += freq * (freq - 1);  // C(freq, 2)\n    }\n\n    return ans;\n  }\n\n private:\n  int getDist(const vector<int>& p, const vector<int>& q) {\n    return pow(p[0] - q[0], 2) + pow(p[1] - q[1], 2);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/447.html",
    "category": "Algorithms",
    "acceptance_rate": 56.32031424085234,
    "topics": [
      "Array",
      "Hash Table",
      "Math"
    ],
    "hints": [],
    "likes": 866,
    "dislikes": 1029,
    "similar_questions": "[{\"title\": \"Line Reflection\", \"titleSlug\": \"line-reflection\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"108.7K\", \"totalSubmission\": \"193K\", \"totalAcceptedRaw\": 108683, \"totalSubmissionRaw\": 192973, \"acRate\": \"56.3%\"}",
    "title_pt": "Número de Boomerangs",
    "description_pt": "<p>Você recebe <code>n</code> <code>points</code> no plano que são todos <strong>distintos</strong>, onde <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. Um <strong>boomerang</strong> é uma tupla de pontos <code>(i, j, k)</code> tal que a distância entre <code>i</code> e <code>j</code> é igual à distância entre <code>i</code> e <code>k</code> <strong>(a ordem da tupla importa)</strong>.</p>\n\n<p>Retorne <em>o número de boomerangs</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[0,0],[1,0],[2,0]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Os dois boomerangs são [[1,0],[0,0],[2,0]] e [[1,0],[2,0],[0,0]].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[1,1],[2,2],[3,3]]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[1,1]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == points.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 500</code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os pontos são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "448",
    "paidOnly": false,
    "title": "Find All Numbers Disappeared in an Array",
    "titleSlug": "find-all-numbers-disappeared-in-an-array",
    "url": "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array",
    "description_url": "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/",
    "description": "<p>Given an array <code>nums</code> of <code>n</code> integers where <code>nums[i]</code> is in the range <code>[1, n]</code>, return <em>an array of all the integers in the range</em> <code>[1, n]</code> <em>that do not appear in</em> <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [4,3,2,7,8,2,3,1]\n<strong>Output:</strong> [5,6]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1]\n<strong>Output:</strong> [2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you do it without extra space and in <code>O(n)</code> runtime? You may assume the returned list does not count as extra space.</p>\n",
    "solution_url": "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n    for num in nums:\n      index = abs(num) - 1\n      nums[index] = -abs(nums[index])\n\n    return [i + 1 for i, num in enumerate(nums) if num > 0]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findDisappearedNumbers(int[] nums) {\n    List<Integer> ans = new ArrayList<>();\n\n    for (final int num : nums) {\n      final int index = Math.abs(num) - 1;\n      nums[index] = -Math.abs(nums[index]);\n    }\n\n    for (int i = 0; i < nums.length; ++i)\n      if (nums[i] > 0)\n        ans.add(i + 1);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findDisappearedNumbers(vector<int>& nums) {\n    vector<int> ans;\n\n    for (const int num : nums) {\n      const int index = abs(num) - 1;\n      nums[index] = -abs(nums[index]);\n    }\n\n    for (int i = 0; i < nums.size(); ++i)\n      if (nums[i] > 0)\n        ans.push_back(i + 1);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/448.html",
    "category": "Algorithms",
    "acceptance_rate": 62.30346161435837,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [
      "This is a really easy problem if you decide to use additional memory. For those trying to write an initial solution using additional memory, think <b>counters!</b>",
      "However, the trick really is to not use any additional space than what is already available to use. Sometimes, multiple passes over the input array help find the solution. However, there's an interesting piece of information in this problem that makes it easy to re-use the input array itself for the solution.",
      "The problem specifies that the numbers in the array will be in the range [1, n] where n is the number of elements in the array. Can we use this information and modify the array in-place somehow to find what we need?"
    ],
    "likes": 9777,
    "dislikes": 518,
    "similar_questions": "[{\"title\": \"First Missing Positive\", \"titleSlug\": \"first-missing-positive\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find All Duplicates in an Array\", \"titleSlug\": \"find-all-duplicates-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Unique Binary String\", \"titleSlug\": \"find-unique-binary-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Append K Integers With Minimal Sum\", \"titleSlug\": \"append-k-integers-with-minimal-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Replace Elements in an Array\", \"titleSlug\": \"replace-elements-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Integers to Choose From a Range I\", \"titleSlug\": \"maximum-number-of-integers-to-choose-from-a-range-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Integers to Choose From a Range II\", \"titleSlug\": \"maximum-number-of-integers-to-choose-from-a-range-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1079784, \"totalSubmissionRaw\": 1733109, \"acRate\": \"62.3%\"}",
    "title_pt": "Encontrar Todos os Números Desaparecidos em um Array",
    "description_pt": "<p>Dado um array <code>nums</code> de <code>n</code> inteiros em que <code>nums[i]</code> está no intervalo <code>[1, n]</code>, retorne <em>um array com todos os inteiros no intervalo</em> <code>[1, n]</code> <em>que não aparecem em</em> <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [4,3,2,7,8,2,3,1]\n<strong>Saída:</strong> [5,6]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1]\n<strong>Saída:</strong> [2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= n</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria fazer isso sem espaço extra e com tempo de execução em <code>O(n)</code>? Você pode assumir que a lista retornada não conta como espaço extra.</p>",
    "hints_pt": [
      "Dica 1: Este é um problema realmente fácil se você decidir usar memória adicional. Para quem estiver tentando escrever uma solução inicial usando memória adicional, pense em <b>contadores!</b>",
      "Dica 2: No entanto, o truque realmente é não usar nenhum espaço adicional além do que já está disponível para uso. Às vezes, múltiplas passagens sobre o array de entrada ajudam a encontrar a solução. No entanto, há uma informação interessante neste problema que torna fácil reutilizar o próprio array de entrada para a solução.",
      "Dica 3: O problema especifica que os números no array estarão no intervalo [1, n], em que n é o número de elementos no array. Podemos usar essa informação e modificar o array in-place de alguma forma para encontrar o que precisamos?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "449",
    "paidOnly": false,
    "title": "Serialize and Deserialize BST",
    "titleSlug": "serialize-and-deserialize-bst",
    "url": "https://leetcode.com/problems/serialize-and-deserialize-bst",
    "description_url": "https://leetcode.com/problems/serialize-and-deserialize-bst/description/",
    "description": "<p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>\n\n<p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p>\n\n<p><b>The encoded string should be as compact as possible.</b></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> root = [2,1,3]\n<strong>Output:</strong> [2,1,3]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> root = []\n<strong>Output:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/serialize-and-deserialize-bst/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\npublic class Codec {\n  // Encodes a tree to a single string.\n  public String serialize(TreeNode root) {\n    if (root == null)\n      return \"\";\n\n    StringBuilder sb = new StringBuilder();\n\n    serialize(root, sb);\n    return sb.toString();\n  }\n\n  // Decodes your encoded data to tree.\n  public TreeNode deserialize(String data) {\n    if (data.isEmpty())\n      return null;\n\n    final String[] vals = data.split(\" \");\n    Queue<Integer> q = new ArrayDeque<>();\n\n    for (final String val : vals)\n      q.offer(Integer.parseInt(val));\n\n    return deserialize(Integer.MIN_VALUE, Integer.MAX_VALUE, q);\n  }\n\n  private void serialize(TreeNode root, StringBuilder sb) {\n    if (root == null)\n      return;\n\n    sb.append(root.val).append(\" \");\n    serialize(root.left, sb);\n    serialize(root.right, sb);\n  }\n\n  private TreeNode deserialize(int min, int max, Queue<Integer> q) {\n    if (q.isEmpty())\n      return null;\n\n    final int val = q.peek();\n    if (val < min || val > max)\n      return null;\n\n    q.poll();\n    TreeNode root = new TreeNode(val);\n    root.left = deserialize(min, val, q);\n    root.right = deserialize(val, max, q);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Codec {\n public:\n  string serialize(TreeNode* root) {\n    if (root == nullptr)\n      return \"\";\n\n    string s;\n\n    serialize(root, s);\n    return s;\n  }\n\n  TreeNode* deserialize(string data) {\n    if (data.empty())\n      return nullptr;\n\n    istringstream iss(data);\n    queue<int> q;\n\n    for (string s; iss >> s;)\n      q.push(stoi(s));\n\n    return deserialize(INT_MIN, INT_MAX, q);\n  }\n\n private:\n  void serialize(TreeNode* root, string& s) {\n    if (root == nullptr)\n      return;\n\n    s += to_string(root->val) + \" \";\n    serialize(root->left, s);\n    serialize(root->right, s);\n  }\n\n  TreeNode* deserialize(int min, int max, queue<int>& q) {\n    if (q.empty())\n      return nullptr;\n\n    const int val = q.front();\n    if (val < min || val > max)\n      return nullptr;\n\n    q.pop();\n    TreeNode* root = new TreeNode(val);\n    root->left = deserialize(min, val, q);\n    root->right = deserialize(val, max, q);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/449.html",
    "category": "Algorithms",
    "acceptance_rate": 58.50495225067761,
    "topics": [
      "String",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Design",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 3538,
    "dislikes": 176,
    "similar_questions": "[{\"title\": \"Serialize and Deserialize Binary Tree\", \"titleSlug\": \"serialize-and-deserialize-binary-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Duplicate Subtrees\", \"titleSlug\": \"find-duplicate-subtrees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Serialize and Deserialize N-ary Tree\", \"titleSlug\": \"serialize-and-deserialize-n-ary-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"254.1K\", \"totalSubmission\": \"434.2K\", \"totalAcceptedRaw\": 254055, \"totalSubmissionRaw\": 434246, \"acRate\": \"58.5%\"}",
    "title_pt": "Serializar e Desserializar BST",
    "description_pt": "<p>Serialização é a conversão de uma estrutura de dados ou objeto em uma sequência de bits para que ela possa ser armazenada em um arquivo ou buffer de memória, ou transmitida por um link de conexão de rede para ser reconstruída posteriormente no mesmo ambiente de computador ou em outro.</p>\n\n<p>Projete um algoritmo para serializar e desserializar uma <b>árvore binária de busca</b>. Não há restrição sobre como seu algoritmo de serialização/desserialização deve funcionar. Você precisa garantir que uma árvore binária de busca possa ser serializada em uma string, e que essa string possa ser desserializada para a estrutura original da árvore.</p>\n\n<p><b>A string codificada deve ser o mais compacta possível.</b></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> root = [2,1,3]\n<strong>Saída:</strong> [2,1,3]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> root = []\n<strong>Saída:</strong> []\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está na faixa de <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>A árvore de entrada é <strong>garantidamente</strong> uma árvore binária de busca.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "450",
    "paidOnly": false,
    "title": "Delete Node in a BST",
    "titleSlug": "delete-node-in-a-bst",
    "url": "https://leetcode.com/problems/delete-node-in-a-bst",
    "description_url": "https://leetcode.com/problems/delete-node-in-a-bst/description/",
    "description": "<p>Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return <em>the <strong>root node reference</strong> (possibly updated) of the BST</em>.</p>\n\n<p>Basically, the deletion can be divided into two stages:</p>\n\n<ol>\n\t<li>Search for a node to remove.</li>\n\t<li>If the node is found, delete the node.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg\" style=\"width: 800px; height: 214px;\" />\n<pre>\n<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 3\n<strong>Output:</strong> [5,4,6,2,null,null,7]\n<strong>Explanation:</strong> Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it&#39;s also accepted.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/04/del_node_supp.jpg\" style=\"width: 350px; height: 255px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [5,3,6,2,4,null,7], key = 0\n<strong>Output:</strong> [5,3,6,2,4,null,7]\n<strong>Explanation:</strong> The tree does not contain a node with value = 0.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [], key = 0\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li>Each node has a <strong>unique</strong> value.</li>\n\t<li><code>root</code> is a valid binary search tree.</li>\n\t<li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve it with time complexity <code>O(height of tree)</code>?</p>\n",
    "solution_url": "https://leetcode.com/problems/delete-node-in-a-bst/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n    if not root:\n      return None\n    if root.val == key:\n      if not root.left:\n        return root.right\n      if not root.right:\n        return root.left\n      minNode = self._getMin(root.right)\n      root.right = self.deleteNode(root.right, minNode.val)\n      minNode.left = root.left\n      minNode.right = root.right\n      root = minNode\n    elif root.val < key:\n      root.right = self.deleteNode(root.right, key)\n    else:  # Root.val > key\n      root.left = self.deleteNode(root.left, key)\n    return root\n\n  def _getMin(self, node: Optional[TreeNode]) -> Optional[TreeNode]:\n    while node.left:\n      node = node.left\n    return node",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode deleteNode(TreeNode root, int key) {\n    if (root == null)\n      return null;\n    if (root.val == key) {\n      if (root.left == null)\n        return root.right;\n      if (root.right == null)\n        return root.left;\n      TreeNode minNode = getMin(root.right);\n      root.right = deleteNode(root.right, minNode.val);\n      minNode.left = root.left;\n      minNode.right = root.right;\n      root = minNode;\n    } else if (root.val < key) {\n      root.right = deleteNode(root.right, key);\n    } else { root.val > key\n      root.left = deleteNode(root.left, key);\n    }\n    return root;\n  }\n\n  private TreeNode getMin(TreeNode node) {\n    while (node.left != null)\n      node = node.left;\n    return node;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* deleteNode(TreeNode* root, int key) {\n    if (root == nullptr)\n      return nullptr;\n    if (root->val == key) {\n      if (root->left == nullptr)\n        return root->right;\n      if (root->right == nullptr)\n        return root->left;\n      TreeNode* minNode = getMin(root->right);\n      root->right = deleteNode(root->right, minNode->val);\n      minNode->left = root->left;\n      minNode->right = root->right;\n      root = minNode;\n    } else if (root->val < key) {\n      root->right = deleteNode(root->right, key);\n    } else {\n      root->val > key root->left = deleteNode(root->left, key);\n    }\n    return root;\n  }\n\n private:\n  TreeNode* getMin(TreeNode* node) {\n    while (node->left)\n      node = node->left;\n    return node;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/450.html",
    "category": "Algorithms",
    "acceptance_rate": 52.85509566524441,
    "topics": [
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 9734,
    "dislikes": 342,
    "similar_questions": "[{\"title\": \"Split BST\", \"titleSlug\": \"split-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"686.4K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 686393, \"totalSubmissionRaw\": 1298636, \"acRate\": \"52.9%\"}",
    "title_pt": "Remover Nó em uma BST",
    "description_pt": "<p>Dado uma referência para o nó raiz de uma BST e uma chave, remova o nó com a chave fornecida na BST. Retorne <em>a <strong>referência para o nó raiz</strong> (possivelmente atualizada) da BST</em>.</p>\n\n<p>Basicamente, a remoção pode ser dividida em dois estágios:</p>\n\n<ol>\n\t<li>Procurar um nó para remover.</li>\n\t<li>Se o nó for encontrado, remova o nó.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/04/del_node_1.jpg\" style=\"width: 800px; height: 214px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,3,6,2,4,null,7], key = 3\n<strong>Saída:</strong> [5,4,6,2,null,null,7]\n<strong>Explicação:</strong> A chave a ser removida é 3. Então encontramos o nó com valor 3 e o removemos.\nUma resposta válida é [5,4,6,2,null,null,7], mostrada na BST acima.\nObserve que outra resposta válida é [5,2,6,null,4,null,7] e ela também é aceita.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/04/del_node_supp.jpg\" style=\"width: 350px; height: 255px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [5,3,6,2,4,null,7], key = 0\n<strong>Saída:</strong> [5,3,6,2,4,null,7]\n<strong>Explicação:</strong> A árvore não contém um nó com valor = 0.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [], key = 0\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n\t<li>Cada nó tem um valor <strong>único</strong>.</li>\n\t<li><code>root</code> é uma árvore binária de busca válida.</li>\n\t<li><code>-10<sup>5</sup> &lt;= key &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você consegue resolvê-lo com complexidade de tempo <code>O(height of tree)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "451",
    "paidOnly": false,
    "title": "Sort Characters By Frequency",
    "titleSlug": "sort-characters-by-frequency",
    "url": "https://leetcode.com/problems/sort-characters-by-frequency",
    "description_url": "https://leetcode.com/problems/sort-characters-by-frequency/description/",
    "description": "<p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p>\n\n<p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;tree&quot;\n<strong>Output:</strong> &quot;eert&quot;\n<strong>Explanation:</strong> &#39;e&#39; appears twice while &#39;r&#39; and &#39;t&#39; both appear once.\nSo &#39;e&#39; must appear before both &#39;r&#39; and &#39;t&#39;. Therefore &quot;eetr&quot; is also a valid answer.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cccaaa&quot;\n<strong>Output:</strong> &quot;aaaccc&quot;\n<strong>Explanation:</strong> Both &#39;c&#39; and &#39;a&#39; appear three times, so both &quot;cccaaa&quot; and &quot;aaaccc&quot; are valid answers.\nNote that &quot;cacaca&quot; is incorrect, as the same characters must be together.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Aabb&quot;\n<strong>Output:</strong> &quot;bbAa&quot;\n<strong>Explanation:</strong> &quot;bbaA&quot; is also a valid answer, but &quot;Aabb&quot; is incorrect.\nNote that &#39;A&#39; and &#39;a&#39; are treated as two different characters.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of uppercase and lowercase English letters and digits.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sort-characters-by-frequency/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def frequencySort(self, s: str) -> str:\n    ans = []\n    bucket = [[] for _ in range(len(s) + 1)]\n\n    for c, freq in Counter(s).items():\n      bucket[freq].append(c)\n\n    for freq in reversed(range(len(bucket))):\n      for c in bucket[freq]:\n        ans.append(c * freq)\n\n    return ''.join(ans)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String frequencySort(String s) {\n    final int n = s.length();\n    StringBuilder sb = new StringBuilder();\n    int[] count = new int[128];\n    // bucket[i] := stores chars that appear i times in s\n    List<Character>[] bucket = new List[n + 1];\n\n    for (final char c : s.toCharArray())\n      ++count[c];\n\n    for (int i = 0; i < 128; ++i) {\n      final int freq = count[i];\n      if (freq > 0) {\n        if (bucket[freq] == null)\n          bucket[freq] = new ArrayList<>();\n        bucket[freq].add((char) i);\n      }\n    }\n\n    for (int freq = n; freq > 0; --freq)\n      if (bucket[freq] != null)\n        for (final char c : bucket[freq])\n          for (int i = 0; i < freq; ++i)\n            sb.append(c);\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string frequencySort(string s) {\n    const int n = s.length();\n    string ans;\n    vector<int> count(128);\n    // bucket[i] := stores chars that appear i times in s\n    vector<vector<char>> bucket(n + 1);\n\n    for (const char c : s)\n      ++count[c];\n\n    for (int i = 0; i < 128; ++i) {\n      const int freq = count[i];\n      if (freq > 0)\n        bucket[freq].push_back((char)i);\n    }\n\n    for (int freq = n; freq > 0; --freq)\n      for (const char c : bucket[freq])\n        ans += string(freq, c);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/451.html",
    "category": "Algorithms",
    "acceptance_rate": 73.91447738137332,
    "topics": [
      "Hash Table",
      "String",
      "Sorting",
      "Heap (Priority Queue)",
      "Bucket Sort",
      "Counting"
    ],
    "hints": [],
    "likes": 8695,
    "dislikes": 311,
    "similar_questions": "[{\"title\": \"Top K Frequent Elements\", \"titleSlug\": \"top-k-frequent-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"First Unique Character in a String\", \"titleSlug\": \"first-unique-character-in-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sort Array by Increasing Frequency\", \"titleSlug\": \"sort-array-by-increasing-frequency\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Percentage of Letter in String\", \"titleSlug\": \"percentage-of-letter-in-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Pairs in Array\", \"titleSlug\": \"maximum-number-of-pairs-in-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Node With Highest Edge Score\", \"titleSlug\": \"node-with-highest-edge-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Pairs Of Similar Strings\", \"titleSlug\": \"count-pairs-of-similar-strings\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"900.9K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 900948, \"totalSubmissionRaw\": 1218906, \"acRate\": \"73.9%\"}",
    "title_pt": "Ordenar Caracteres por Frequência",
    "description_pt": "<p>Dada uma string <code>s</code>, ordene-a em <strong>ordem decrescente</strong> com base na <strong>frequência</strong> dos caracteres. A <strong>frequência</strong> de um caractere é o número de vezes que ele aparece na string.</p>\n\n<p>Retorne <em>a string ordenada</em>. Se houver múltiplas respostas, retorne <em>qualquer uma delas</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;tree&quot;\n<strong>Saída:</strong> &quot;eert&quot;\n<strong>Explicação:</strong> &#39;e&#39; aparece duas vezes enquanto &#39;r&#39; e &#39;t&#39; aparecem uma vez cada.\nEntão &#39;e&#39; deve aparecer antes de &#39;r&#39; e &#39;t&#39;. Portanto, &quot;eetr&quot; também é uma resposta válida.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cccaaa&quot;\n<strong>Saída:</strong> &quot;aaaccc&quot;\n<strong>Explicação:</strong> Tanto &#39;c&#39; quanto &#39;a&#39; aparecem três vezes, então tanto &quot;cccaaa&quot; quanto &quot;aaaccc&quot; são respostas válidas.\nObserve que &quot;cacaca&quot; está incorreto, pois os mesmos caracteres devem ficar juntos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Aabb&quot;\n<strong>Saída:</strong> &quot;bbAa&quot;\n<strong>Explicação:</strong> &quot;bbaA&quot; também é uma resposta válida, mas &quot;Aabb&quot; está incorreto.\nObserve que &#39;A&#39; e &#39;a&#39; são tratados como dois caracteres diferentes.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em letras inglesas maiúsculas e minúsculas e dígitos.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "452",
    "paidOnly": false,
    "title": "Minimum Number of Arrows to Burst Balloons",
    "titleSlug": "minimum-number-of-arrows-to-burst-balloons",
    "url": "https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons",
    "description_url": "https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/description/",
    "description": "<p>There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array <code>points</code> where <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denotes a balloon whose <strong>horizontal diameter</strong> stretches between <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code>. You do not know the exact y-coordinates of the balloons.</p>\n\n<p>Arrows can be shot up <strong>directly vertically</strong> (in the positive y-direction) from different points along the x-axis. A balloon with <code>x<sub>start</sub></code> and <code>x<sub>end</sub></code> is <strong>burst</strong> by an arrow shot at <code>x</code> if <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. There is <strong>no limit</strong> to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.</p>\n\n<p>Given the array <code>points</code>, return <em>the <strong>minimum</strong> number of arrows that must be shot to burst all balloons</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[10,16],[2,8],[1,6],[7,12]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[1,2],[3,4],[5,6],[7,8]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> One arrow needs to be shot for each balloon for a total of 4 arrows.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> points = [[1,2],[2,3],[3,4],[4,5]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMinArrowShots(self, points: List[List[int]]) -> int:\n    ans = 0\n    arrowX = -math.inf\n\n    for point in sorted(points, key=lambda x: x[1]):\n      if point[0] > arrowX:\n        ans += 1\n        arrowX = point[1]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMinArrowShots(int[][] points) {\n    Arrays.sort(points, (a, b) -> a[1] - b[1]);\n\n    int ans = 1;\n    int arrowX = points[0][1];\n\n    for (int i = 1; i < points.length; ++i)\n      if (points[i][0] > arrowX) {\n        arrowX = points[i][1];\n        ++ans;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMinArrowShots(vector<vector<int>>& points) {\n    sort(begin(points), end(points),\n         [](const auto& a, const auto& b) { return a[1] < b[1]; });\n\n    int ans = 1;\n    int arrowX = points[0][1];\n\n    for (int i = 1; i < points.size(); ++i)\n      if (points[i][0] > arrowX) {\n        arrowX = points[i][1];\n        ++ans;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/452.html",
    "category": "Algorithms",
    "acceptance_rate": 60.28413372329575,
    "topics": [
      "Array",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 7766,
    "dislikes": 259,
    "similar_questions": "[{\"title\": \"Meeting Rooms II\", \"titleSlug\": \"meeting-rooms-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Non-overlapping Intervals\", \"titleSlug\": \"non-overlapping-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"660.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 660816, \"totalSubmissionRaw\": 1096171, \"acRate\": \"60.3%\"}",
    "title_pt": "Número Mínimo de Flechas para Estourar Balões",
    "description_pt": "<p>Há alguns balões esféricos presos em uma parede plana que representa o plano XY. Os balões são representados por um array 2D de inteiros <code>points</code>, onde <code>points[i] = [x<sub>start</sub>, x<sub>end</sub>]</code> denota um balão cujo <strong>diâmetro horizontal</strong> se estende entre <code>x<sub>start</sub></code> e <code>x<sub>end</sub></code>. Você não conhece as coordenadas exatas em y dos balões.</p>\n\n<p>As flechas podem ser disparadas <strong>diretamente na vertical</strong> (na direção positiva de y) a partir de diferentes pontos ao longo do eixo x. Um balão com <code>x<sub>start</sub></code> e <code>x<sub>end</sub></code> é <strong>estourado</strong> por uma flecha disparada em <code>x</code> se <code>x<sub>start</sub> &lt;= x &lt;= x<sub>end</sub></code>. Não há <strong>limite</strong> para o número de flechas que podem ser disparadas. Uma flecha disparada continua viajando para cima infinitamente, estourando quaisquer balões em seu caminho.</p>\n\n<p>Dado o array <code>points</code>, retorne <em>o número <strong>mínimo</strong> de flechas que devem ser disparadas para estourar todos os balões</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[10,16],[2,8],[1,6],[7,12]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Os balões podem ser estourados por 2 flechas:\n- Dispare uma flecha em x = 6, estourando os balões [2,8] e [1,6].\n- Dispare uma flecha em x = 11, estourando os balões [10,16] e [7,12].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[1,2],[3,4],[5,6],[7,8]]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Uma flecha precisa ser disparada para cada balão, para um total de 4 flechas.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> points = [[1,2],[2,3],[3,4],[4,5]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Os balões podem ser estourados por 2 flechas:\n- Dispare uma flecha em x = 2, estourando os balões [1,2] e [2,3].\n- Dispare uma flecha em x = 4, estourando os balões [3,4] e [4,5].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= points.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>points[i].length == 2</code></li>\n\t<li><code>-2<sup>31</sup> &lt;= x<sub>start</sub> &lt; x<sub>end</sub> &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "453",
    "paidOnly": false,
    "title": "Minimum Moves to Equal Array Elements",
    "titleSlug": "minimum-moves-to-equal-array-elements",
    "url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements",
    "description_url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/",
    "description": "<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p>\n\n<p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements):\n[1,2,3]  =&gt;  [2,3,3]  =&gt;  [3,4,3]  =&gt;  [4,4,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minMoves(self, nums: List[int]) -> int:\n    mini = min(nums)\n    return sum(num - mini for num in nums)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minMoves(int[] nums) {\n    final int sum = Arrays.stream(nums).sum();\n    final int min = Arrays.stream(nums).min().getAsInt();\n    return sum - min * nums.length;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minMoves(vector<int>& nums) {\n    const int min = *min_element(begin(nums), end(nums));\n    return accumulate(begin(nums), end(nums), 0,\n                      [&](int a, int b) { return a + (b - min); });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/453.html",
    "category": "Algorithms",
    "acceptance_rate": 57.64960720546311,
    "topics": [
      "Array",
      "Math"
    ],
    "hints": [],
    "likes": 2706,
    "dislikes": 1905,
    "similar_questions": "[{\"title\": \"Minimum Moves to Equal Array Elements II\", \"titleSlug\": \"minimum-moves-to-equal-array-elements-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Running Time of N Computers\", \"titleSlug\": \"maximum-running-time-of-n-computers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Pour Water Between Buckets to Make Water Levels Equal\", \"titleSlug\": \"pour-water-between-buckets-to-make-water-levels-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Divide Players Into Teams of Equal Skill\", \"titleSlug\": \"divide-players-into-teams-of-equal-skill\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum Operations to Make All Elements Divisible by Three\", \"titleSlug\": \"find-minimum-operations-to-make-all-elements-divisible-by-three\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"195.3K\", \"totalSubmission\": \"338.9K\", \"totalAcceptedRaw\": 195347, \"totalSubmissionRaw\": 338853, \"acRate\": \"57.6%\"}",
    "title_pt": "Mínimo de Movimentos para Tornar os Elementos do Array Iguais",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> de tamanho <code>n</code>, retorne <em>o número mínimo de movimentos necessários para tornar todos os elementos do array iguais</em>.</p>\n\n<p>Em um movimento, você pode incrementar <code>n - 1</code> elementos do array em <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Apenas três movimentos são necessários (lembre-se de que cada movimento incrementa dois elementos):\n[1,2,3]  =&gt;  [2,3,3]  =&gt;  [3,4,3]  =&gt;  [4,4,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li>A resposta tem garantia de caber em um inteiro de <strong>32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "454",
    "paidOnly": false,
    "title": "4Sum II",
    "titleSlug": "4sum-ii",
    "url": "https://leetcode.com/problems/4sum-ii",
    "description_url": "https://leetcode.com/problems/4sum-ii/description/",
    "description": "<p>Given four integer arrays <code>nums1</code>, <code>nums2</code>, <code>nums3</code>, and <code>nums4</code> all of length <code>n</code>, return the number of tuples <code>(i, j, k, l)</code> such that:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j, k, l &lt; n</code></li>\n\t<li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\nThe two tuples are:\n1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums1.length</code></li>\n\t<li><code>n == nums2.length</code></li>\n\t<li><code>n == nums3.length</code></li>\n\t<li><code>n == nums4.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n\t<li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/4sum-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:\n    count = Counter(a + b for a in A for b in B)\n\n    return sum(count[-c - d] for c in C for d in D)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {\n    int ans = 0;\n    Map<Integer, Integer> count = new HashMap<>();\n\n    for (final int a : A)\n      for (final int b : B)\n        count.put(a + b, count.getOrDefault(a + b, 0) + 1);\n\n    for (final int c : C)\n      for (final int d : D)\n        if (count.containsKey(-c - d))\n          ans += count.get(-c - d);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int fourSumCount(vector<int>& A, vector<int>& B,\n                   vector<int>& C, vector<int>& D) {\n    int ans = 0;\n    unordered_map<int, int> count;\n\n    for (const int a : A)\n      for (const int b : B)\n        ++count[a + b];\n\n    for (const int c : C)\n      for (const int d : D)\n        if (count.count(-c - d))\n          ans += count[-c - d];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/454.html",
    "category": "Algorithms",
    "acceptance_rate": 57.55183168236834,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [],
    "likes": 4986,
    "dislikes": 147,
    "similar_questions": "[{\"title\": \"4Sum\", \"titleSlug\": \"4sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"356.1K\", \"totalSubmission\": \"618.8K\", \"totalAcceptedRaw\": 356146, \"totalSubmissionRaw\": 618828, \"acRate\": \"57.6%\"}",
    "title_pt": "4Soma II",
    "description_pt": "<p>Dados quatro arrays de inteiros <code>nums1</code>, <code>nums2</code>, <code>nums3</code> e <code>nums4</code>, todos de comprimento <code>n</code>, retorne o número de tuplas <code>(i, j, k, l)</code> tais que:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j, k, l &lt; n</code></li>\n\t<li><code>nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong>\nAs duas tuplas são:\n1. (0, 0, 0, 1) -&gt; nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -&gt; nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums1.length</code></li>\n\t<li><code>n == nums2.length</code></li>\n\t<li><code>n == nums3.length</code></li>\n\t<li><code>n == nums4.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n\t<li><code>-2<sup>28</sup> &lt;= nums1[i], nums2[i], nums3[i], nums4[i] &lt;= 2<sup>28</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "455",
    "paidOnly": false,
    "title": "Assign Cookies",
    "titleSlug": "assign-cookies",
    "url": "https://leetcode.com/problems/assign-cookies",
    "description_url": "https://leetcode.com/problems/assign-cookies/description/",
    "description": "<p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p>\n\n<p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> g = [1,2,3], s = [1,1]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> g = [1,2], s = [1,2,3]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as <a href=\"https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/\" target=\"_blank\"> 2410: Maximum Matching of Players With Trainers.</a></p>\n",
    "solution_url": "https://leetcode.com/problems/assign-cookies/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nOur objective is to determine the maximum number of content children given cookie sizes and greed factors.\n\nEach index `i` in `g` represents a child whose minimum cookie size is `g[i]`.\nEach index `j` in `s` represents a cookie with the size `s[j]`.\n\nA child will be content if their cookie's size `s[j]` meets or exceeds their greed `g[i]`, represented as cookie size `s[j] >= g[i]` \n\nEach child should receive at most one cookie. We must note that we could have many small cookies, but that will not satisfy a greedy child, because they want 1 large cookie. If there are lots of small cookies but no children with small greed, we can't use those cookies.\n\n### Approach: Greedy, Two-Pointer\n\n#### Intuition\n\nGiven the test case 2 `g = [1, 2]` and `s = [1, 2, 3]`, we could attempt a naive approach, iterating through both arrays and assigning cookies to the children in order. \n\nWould this approach work for all cases? With the test case `g = [2, 1]` and `s = [1, 2]` we realize we cannot assign cookies in order because the first cookie isn't large enough for the first child, and if we allocate the second cookie to the second child, we satisfy only one child when we could satisfy two.\n\nWe need to be able to ensure that each child receives the smallest cookie that meets their greed so that larger cookies can be saved for children with more greed. We also want to make sure there are no leftover cookies that could have satisfied children.\n\nThe optimal solution will satisfy these conditions:\n* Every child that receives a cookie receives the smallest cookie that meets their greed so no larger cookies are wasted on children with smaller greed\n* After cookies are assigned, no cookies are remaining that could satisfy the available children's greed\n\nHow do we ensure that we don't waste larger cookies on children with smaller greed? We notice that in the first example, both arrays are sorted in ascending order. We need to sort the cookies and children in ascending order so that we can guarantee that for each child, we always try the currently smallest available cookie.\n\nTo solve the problem, we will start by sorting both arrays. That way we can ensure the children with the smallest greed and the smallest cookies are at the beginning, and the children with the largest greed and the largest cookies are at the end.\n\nNext, we will use a while loop to iterate through our array of cookies, attempting to assign cookies to children.  We will continue while we have more cookies and children. We will create a variable `cookieIndex` that keeps track of which cookies we have assigned or passed. We will store the number of satisfied children in `contentChildren`. If the next cookie meets the current child's greed, we increment `contentChildren` and `cookieIndex` as that cookie is assigned to a child. If the next cookie doesn't meet the current child's greed, we iterate `cookieIndex` to move on to the next cookie, until we find a cookie large enough for the child or we run out of cookies. Finally, we return `contentChildren`.\n\nHow can we be sure this provides the optimal solution?\n\nWith this approach, each child is offered the smallest available cookie first. Since the cookies are offered in order of ascending size, this ensures every child receives the smallest cookie that meets their greed. While assigning cookies to children, the children are sorted in increasing order of greed, which means that when we offer a cookie that doesn't meet the current child's greed, we also know there are no children less greedy than the current child. This means that any leftover cookies will not satisfy any available children. The approach provides an optimal solution.\n\nThis is a greedy approach because the current child always receives the cookie, even if the cookie could have satisfied the next child. This is the locally optimal choice.\n\n\n#### Algorithm\n\n1. Sort arrays `g` and `s` in ascending order.\n2. Initialize variable ` contentChildren = 0` to represent the number of children who receive cookies that meet their greed.\n2. Initialize variable `cookieIndex = 0` to represent the number of cookies that have been assigned or skipped.\n3. while `cookieIndex` is less than the size of `s` and `contentChildren` is less than the size of `g`:\n    - If the current cookie's size is greater than or equal to the current child's greed: \n        - Increment `contentChildren` to allocate the cookie.\n    - Increment `cookieIndex` to move on to the next cookie.\n4. Return `contentChildren`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/aAJwA8BN/shared\" frameBorder=\"0\" width=\"100%\" height=\"327\" name=\"aAJwA8BN\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $O (n \\cdot \\log n + m \\cdot \\log m)$ where $n$ is the size of the array `g` and $m$ is the size of the array `s`. \n\n    Sorting an array of length $k$ takes $O (k \\cdot\\log k)$, we need to sort two given arrays. The while loop iterates over each cookie and child once, taking $O(m + n)$. To sum up, the overall time complexity is $O (n \\cdot \\log n + m \\cdot \\log m)$\n\n* Space Complexity:  $O(m + n)$ or $O(\\log m + \\log n)$ \n    - Some extra space is used when we sort $s$ and $g$ in place. The space complexity of the sorting algorithm depends on the programming language.\n        - In Python, the `sort` method sorts a list using the Timesort algorithm which is a combination of Merge Sort and Insertion Sort and has $$O(n + m)$$ additional space.\n        - In C++, the sort() function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of $$O(\\log n + \\log m)$$.\n        - In Java, Arrays.sort() is implemented using a variant of the Quick Sort algorithm which has a space complexity of $$O(\\log n + \\log m)$$ for sorting two arrays.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findContentChildren(int[] g, int[] s) {\n    Arrays.sort(g);\n    Arrays.sort(s);\n\n    int i = 0;\n    for (int j = 0; i < g.length && j < s.length; ++j)\n      if (g[i] <= s[j])\n        ++i;\n\n    return i;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findContentChildren(vector<int>& g, vector<int>& s) {\n    sort(begin(g), end(g));\n    sort(begin(s), end(s));\n\n    int i = 0;\n    for (int j = 0; j < s.size() && i < g.size(); ++j)\n      if (g[i] <= s[j])\n        ++i;\n\n    return i;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/455.html",
    "category": "Algorithms",
    "acceptance_rate": 53.69403797937446,
    "topics": [
      "Array",
      "Two Pointers",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 4418,
    "dislikes": 409,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"667.9K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 667945, \"totalSubmissionRaw\": 1243986, \"acRate\": \"53.7%\"}",
    "title_pt": "Atribuir Cookies",
    "description_pt": "<p>Suponha que você é um pai incrível e quer dar alguns cookies aos seus filhos. Porém, você deve dar a cada criança no máximo um cookie.</p>\n\n<p>Cada criança <code>i</code> tem um fator de ganância <code>g[i]</code>, que é o tamanho mínimo de um cookie com o qual a criança ficará satisfeita; e cada cookie <code>j</code> tem um tamanho <code>s[j]</code>. Se <code>s[j] &gt;= g[i]</code>, podemos atribuir o cookie <code>j</code> à criança <code>i</code>, e a criança <code>i</code> ficará satisfeita. Seu objetivo é maximizar o número de crianças satisfeitas e retornar esse número máximo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> g = [1,2,3], s = [1,1]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Você tem 3 crianças e 2 cookies. Os fatores de ganância das 3 crianças são 1, 2, 3. \nE embora você tenha 2 cookies, como o tamanho de ambos é 1, você só poderia satisfazer a criança cujo fator de ganância é 1.\nVocê precisa retornar 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> g = [1,2], s = [1,2,3]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Você tem 2 crianças e 3 cookies. Os fatores de ganância das 2 crianças são 1, 2. \nVocê tem 3 cookies e seus tamanhos são grandes o suficiente para satisfazer todas as crianças, \nVocê precisa retornar 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que <a href=\"https://leetcode.com/problems/maximum-matching-of-players-with-trainers/description/\" target=\"_blank\"> 2410: Maximum Matching of Players With Trainers.</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "456",
    "paidOnly": false,
    "title": "132 Pattern",
    "titleSlug": "132-pattern",
    "url": "https://leetcode.com/problems/132-pattern",
    "description_url": "https://leetcode.com/problems/132-pattern/description/",
    "description": "<p>Given an array of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p>\n\n<p>Return <code>true</code><em> if there is a <strong>132 pattern</strong> in </em><code>nums</code><em>, otherwise, return </em><code>false</code><em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> There is no 132 pattern in the sequence.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,1,4,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2].\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,3,2,0]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/132-pattern/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n### Approach 1: Brute Force\n\nThe simplest solution is to consider every triplet $$(i, j, k)$$ and check if the corresponding numbers satisfy the 132 criteria. If any such triplet is found, we can return a True value. If no such triplet is found, we need to return a False value.\n\n<iframe src=\"https://leetcode.com/playground/hGnnTJMn/shared\" frameBorder=\"0\" width=\"100%\" height=\"361\" name=\"hGnnTJMn\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. Three loops are used to consider every possible triplet. Here, $$n$$ refers to the size of $$nums$$ array.\n\n* Space complexity : $$O(1)$$. Constant extra space is used.\n<br />\n<br />\n\n---\n### Approach 2: Better Brute Force\n\n**Algorithm**\n\nWe can improve the last approach to some extent, if we make use of some observations. We can note that for a particular number $$nums[j]$$ chosen as 2nd element in the 132 pattern, if we don't consider $$nums[k]$$(the 3rd element) for the time being, our job is to find out the first element, $$nums[i]$$($$i<j$$) which is lesser than $$nums[j]$$.\n\nNow, assume that we have somehow found a $$nums[i],nums[j]$$ pair. Our task now reduces to finding out a $$nums[k]$$($$Kk>j>i)$$, which falls in the range $$(nums[i], nums[j])$$. Now, to maximize the likelihood of a $$nums[k]$$ falling in this range, we need to increase this range as much as possible.\n\nSince, we started off by fixing a $$nums[j]$$, the only option in our hand is to choose a minimum value of $$nums[i]$$ given a particular $$nums[j]$$. Once, this pair $$nums[i],nums[j]$$, has been found out, we simply need to traverse beyond the index $$j$$ to find if a $$nums[k]$$ exists for this pair satisfying the 132 criteria.\n\nBased on the above observations, while traversing over the $$nums$$ array choosing various values of $$nums[j]$$, we simultaneously keep a track of the minimum element found so far(excluding $$nums[j]$$). This minimum element always serves as the $$nums[i]$$ for the current $$nums[j]$$. Thus, we only need to traverse beyond the $$j^{th}$$ index to check the $$nums[k]$$'s to determine if any of them satisfies the 132 criteria.\n\n<iframe src=\"https://leetcode.com/playground/4Mv4ZmY8/shared\" frameBorder=\"0\" width=\"100%\" height=\"310\" name=\"4Mv4ZmY8\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. Two loops are used to find the $$nums[j],nums[k]$$ pairs. Here, $$n$$ refers to the size of $$nums$$ array.\n\n* Space complexity : $$O(1)$$. Constant extra space is used.\n<br />\n<br />\n\n---\n### Approach 3: Searching Intervals\n\n**Algorithm**\n\nAs discussed in the last approach, once we've fixed a $$nums[i],nums[j]$$ pair, we just need to determine a $$nums[k]$$ which falls in the range $$(nums[i],nums[j])$$. Further, to maximize the likelihood of any arbitrary $$nums[k]$$ falling in this range, we need to try to keep this range as much as possible. But, in the last approach, we tried to work only on $$nums[i]$$. But, it'll be a better choice, if we can somehow work out on $$nums[j]$$ as well.\n\nTo do so, we can look at the given $$nums$$ array in the form of a graph, as shown below:\n\n![Graph](../Figures/456/456_132_Pattern.PNG)\n\n\nFrom the above graph, which consists of rising and falling slopes, we know, the best qualifiers to act as the $$nums[i],nums[j]$$ pair,  as discussed above, to maximize the range $$nums[i], nums[j]$$, at any instant, while traversing the $$nums$$ array, will be the points at the endpoints of a local rising slope. Thus, once we've found such points, we can traverse over the $$nums$$ array to find a $$nums[k]$$ satisfying the given 132 criteria.\n\nTo find these points at the ends of a local rising slope, we can traverse over the given $$nums$$ array. While traversing, we can keep a track of the minimum point found after the last peak($$nums[s]$$).\n\nNow, whenever we encounter a falling slope, say, at index $$i$$, we know, that $$nums[i-1]$$ was the endpoint of the last rising slope found. Thus, we can scan over the $$k$$ indices(k>i), to find a 132 pattern.\n\nBut, instead of traversing over $$nums$$ to find a $$k$$ satisfying the 132 pattern for every such rising slope, we can store this range $$(nums[s], nums[i-1])$$(acting as $$(nums[i], nums[j])$$) in, say an $$intervals$$ array.\n\nWhile traversing over the $$nums$$ array to check the rising/falling slopes, whenever we find any rising slope, we can keep adding the endpoint pairs to this $$intervals$$ array. At the same time, we can also check if the current element falls in any of the ranges found so far. If so, this element satisfies the 132 criteria for that range.\n\nIf no such element is found till the end, we need to return a False value.\n\n<iframe src=\"https://leetcode.com/playground/Zy6HRCyV/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Zy6HRCyV\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. We traverse over the $$nums$$ array of size $$n$$ once to find the slopes. But for every element, we also need to traverse over the $$intervals$$ to check if any element falls in any range found so far. This array can contain at most $$(n/2)$$ pairs, in the case of an alternate increasing-decreasing sequence(worst case e.g.`[5 6 4 7 3 8 2 9]`).\n\n* Space complexity : $$O(n)$$. $$intervals$$ array can contain at most $$n/2$$ pairs, in the worst case(alternate increasing-decreasing sequence).\n<br />\n<br />\n\n---\n### Approach 4: Stack\n\n**Algorithm**\n\nIn Approach 2, we found out $$nums[i]$$ corresponding to a particular $$nums[j]$$ directly without having to consider every pair possible in $$nums$$ to find this $$nums[i],nums[j]$$ pair. If we do some preprocessing, we can make the process of finding a $$nums[k]$$ corresponding to this $$nums[i],nums[j]$$ pair also easy.\n\nThe preprocessing required is to just find the best $$nums[i]$$ value corresponding to every $$nums[j]$$ value. This is done in the same manner as in the second approach i.e. we find the minimum element found till the $$j^{th}$$ element which acts as the $$nums[i]$$ for the current $$nums[j]$$. We maintain thes values in a $$min$$ array. Thus, $$min[j]$$ now refers to the best $$nums[i]$$ value for a particular $$nums[j]$$.\n\nNow, we traverse back from the end of the $$nums$$ array to find the $$nums[k]$$'s. Suppose, we keep a track of the $$nums[k]$$ values which can potentially satisfy the 132 criteria for the current $$nums[j]$$. We know, one of the conditions to be satisfied by such a $$nums[k]$$ is that it must be greater than $$nums[i]$$. Or in other words, we can also say that it must be greater than $$min[j]$$ for a particular $$nums[j]$$ chosen.\n\nOnce it is ensured that the elements left for competing for the $$nums[k]$$ are all greater than $$min[j]$$(or $$nums[i]$$), our only task is to ensure that it should be lesser than $$nums[j]$$. Now, the best element from among the competitors, for satisfying this condition will be the minimum one from out of these elements.\n\nIf this element, $$nums[k]$$ satisfies $$nums[k] < nums[j]$$, we've found a 132 pattern. If not, no other element will satisfy this criteria, since they are all greater than or equal to $$nums[min]$$ and thus greater than or equal to $$nums[j]$$ as well.\n\nTo keep a track of these potential $$nums[k]$$ values for a particular $$nums[i],nums[j]$$ considered currently, we maintain a $$stack$$ on which these potential $$nums[k]$$'s satisfying the 132 criteria lie in a descending order(minimum element on the top). We need not sort these elements on the $$stack$$, but they'll be sorted automatically as we'll discuss along with the process.\n\nAfter creating a $$min$$ array, we start traversing the $$nums[j]$$ array in a backward manner. Let's say, we are currently at the $$j^{th}$$ element and let's also assume that the $$stack$$ is sorted right now. Now, firstly, we check if $$nums[j] > min[j]$$. If not, we continue with the $$(j-1)^{th}$$ element and the $$stack$$ remains sorted. If not, we keep on popping the elements from the top of the $$stack$$ till we find an element, $$stack[top]$$ such that, $$stack[top] > min[j]$$(or $$stack[top] > nums[i]$$).\n\nOnce the popping is done, we're sure that all the elements pending on the $$stack$$ are greater than $$nums[i]$$ and are thus, the potential candidates for $$nums[k]$$ satisfying the 132 criteria. We can also note that the elements which have been popped from the $$stack$$, all satisfy $$stack[top] &leq; min[j]$$.\n\nSince, in the $$min$$ array, $$min[p] &leq; min[q]$$, for every $$p > q$$, these popped elements also satisfy $$stack[top] &leq; min[k]$$, for all $$0 &leq; k < j$$. Thus, they are not the potential $$nums[k]$$ candidates for even the preceding elements. Even after  doing the popping, the $$stack$$ remains sorted.\n\nAfter the popping is done, we've got the minimum element from amongst all the potential $$nums[k]$$'s on the top of the $$stack$$(as per the assumption). We can check if it is less than or equal to $$nums[j]$$ to satisfy the 132 criteria(we've already checked $$stack[top] > nums[i]$$). If this element satisfies the 132 criteria, we can return a True value. If not, we know that for the current $$j$$, $$nums[j] > min[j]$$. Thus, the element $$nums[j]$$ could be a potential $$nums[k]$$ value, for the preceding $$nums[i]'s$$.\n\nThus, we push it over the $$stack$$. We can note that, we need to push this element $$nums[j]$$ on the $$stack$$ only when it didn't satisfy $$stack[top]<nums[j]$$. Thus, $$nums[j] &leq; stack[top]$$. Thus, even after pushing this element on the $$stack$$, the $$stack$$ remains sorted. Thus, we've seen by induction, that the $$stack$$ always remains sorted.\n\nAlso, note that in case $$nums[j] &leq; min[j]$$, we don't push $$nums[j]$$ onto the $$stack$$. This is because this $$nums[j]$$ isn't greater than even the minimum element lying towards its left and thus can't act as $$nums[k]$$ in the future.\n\nIf no element is found satisfying the 132 criteria till reaching the first element, we return a False value.\n\nThe following animation better illustrates the process.\n\n!?!../Documents/456_132_Pattern.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/kueGKV2B/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"kueGKV2B\"></iframe>\n\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. We travesre over the $$nums$$ array of size $$n$$ once to fill the $$min$$ array. After this, we traverse over $$nums$$ to find the $$nums[k]$$. During this process, we also push and pop the elements on the $$stack$$. But, we can note that at most $$n$$ elements can be pushed and popped off the $$stack$$ in total. Thus, the second traversal requires only $$O(n)$$ time.\n\n* Space complexity : $$O(n)$$. The $$stack$$ can grow upto a maximum depth of $$n$$. Furhter, $$min$$ array of size $$n$$ is used.\n<br />\n<br />\n\n---\n\n### Approach 5: Binary Search\n\n**Algorithm**\n\nIn the last approach, we've made use of a separate $$stack$$ to push and pop the $$nums[k]$$'s. But, we can also note that when we reach the index $$j$$ while scanning backwards for finding $$nums[k]$$, the $$stack$$ can contain at most $$n-j-1$$ elements. Here, $$n$$ refers to the number of elements in $$nums$$ array.\n\nWe can also note that this is the same number of elements which lie beyond the $$j^{th}$$ index in $$nums$$ array. We also know that these elements lying beyond the $$j^{th}$$ index won't be needed in the future ever again. Thus, we can make use of this space in $$nums$$ array instead of using a separate $$stack$$. The rest of the process can be carried on in the same manner as discussed in the last approach.\n\nWe can try to go for another optimization here. Since, we've got an array for storing the potential $$nums[k]$$ values now, we need not do the popping process for a $$min[j]$$ to find an element just larger than $$min[j]$$ from amongst these potential values.\n\nInstead, we can make use of Binary Search to directly find an element, which is just larger than $$min[j]$$ in the required interval, if it exists. If such an element is found, we can compare it with $$nums[j]$$ to check the 132 criteria. Otherwise, we continue the process as in the last approach.\n\n<iframe src=\"https://leetcode.com/playground/8yeXd5nB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8yeXd5nB\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O\\big(n \\log n\\big)$$. Filling $$min$$ array requires $$O(n)$$ time. The second traversal is done over the whole $$nums$$ array of length $$n$$. For every current $$nums[j]$$ we need to do the Binary Search, which requires $$O\\big(\\log n\\big)$$. In the worst case, this Binary Search will be done for all the $$n$$ elements, and the required element won't be found in any case, leading to a complexity of $$O\\big(n \\log n\\big)$$.\n\n* Space complexity : $$O(n)$$. $$min$$ array of size $$n$$ is used.\n<br />\n<br />\n\n---\n### Approach 6: Using Array as a Stack\n\n**Algorithm**\n\nIn the last approach, we've seen that in the worst case, the required element won't be found for all the $$n$$ elements and thus Binary Search is done at every step increasing the time complexity.\n\nTo remove this problem, we can follow the same steps as in Approach 4 i.e. We can remove those elements(update the index $$k$$) which aren't greater than $$nums[i]$$($$min[j]$$). Thus, in case no element is larger than $$min[j]$$ the index $$k$$ reaches the last element.\n\nNow, at every step, only $$nums[j]$$ will be added and removed from consideration in the next step, improving the time complexity in the worst case. The rest of the method remains the same as in Approach 4.\n\nThis approach is inspired by [@fun4leetcode](https://leetcode.com/fun4leetcode/)\n\n<iframe src=\"https://leetcode.com/playground/gN3j3eSo/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gN3j3eSo\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. We travesre over the $$nums$$ array of size $$n$$ once to fill the $$min$$ array. After this, we traverse over $$nums$$ to find the $$nums[k]$$. At most $$n$$ elements can be put in and out of the $$nums$$ array in total. Thus, the second traversal requires only $$O(n)$$ time.\n\n* Space complexity : $$O(n)$$. $$min$$ array of size $$n$$ is used.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean find132pattern(int[] nums) {\n    Deque<Integer> stack = new ArrayDeque<>(); // Max stack\n    int ak = Integer.MIN_VALUE;                // We want to find a seq ai < ak < aj\n\n    for (int i = nums.length - 1; i >= 0; --i) {\n      if (nums[i] < ak) // Ai < ak, we're done because ai must also smaller than aj\n        return true;\n      while (!stack.isEmpty() && stack.peek() < nums[i])\n        ak = stack.pop();\n      stack.push(nums[i]); // nums[i] is a candidate of aj\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool find132pattern(vector<int>& nums) {\n    stack<int> stack;  // Max stack\n    int ak = INT_MIN;  // We want to find a seq ai < ak < aj\n\n    for (int i = nums.size() - 1; i >= 0; --i) {\n      // Ai < ak, we're done because ai must also smaller than aj\n      if (nums[i] < ak)\n        return true;\n      while (!stack.empty() && stack.top() < nums[i])\n        ak = stack.top(), stack.pop();\n      stack.push(nums[i]);  // nums[i] is a candidate of aj\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/456.html",
    "category": "Algorithms",
    "acceptance_rate": 34.01647816200573,
    "topics": [
      "Array",
      "Binary Search",
      "Stack",
      "Monotonic Stack",
      "Ordered Set"
    ],
    "hints": [],
    "likes": 7406,
    "dislikes": 449,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"288K\", \"totalSubmission\": \"846.6K\", \"totalAcceptedRaw\": 287971, \"totalSubmissionRaw\": 846570, \"acRate\": \"34.0%\"}",
    "title_pt": "Padrão 132",
    "description_pt": "<p>Dado um array de <code>n</code> inteiros <code>nums</code>, um <strong>padrão 132</strong> é uma subsequência de três inteiros <code>nums[i]</code>, <code>nums[j]</code> e <code>nums[k]</code> tal que <code>i &lt; j &lt; k</code> e <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p>\n\n<p>Retorne <code>true</code><em> se houver um <strong>padrão 132</strong> em </em><code>nums</code><em>; caso contrário, retorne </em><code>false</code><em>.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Não há nenhum padrão 132 na sequência.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,1,4,2]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Há um padrão 132 na sequência: [1, 4, 2].\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,3,2,0]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Há três padrões 132 na sequência: [-1, 3, 2], [-1, 3, 0] e [-1, 2, 0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "457",
    "paidOnly": false,
    "title": "Circular Array Loop",
    "titleSlug": "circular-array-loop",
    "url": "https://leetcode.com/problems/circular-array-loop",
    "description_url": "https://leetcode.com/problems/circular-array-loop/description/",
    "description": "<p>You are playing a game involving a <strong>circular</strong> array of non-zero integers <code>nums</code>. Each <code>nums[i]</code> denotes the number of indices forward/backward you must move if you are located at index <code>i</code>:</p>\n\n<ul>\n\t<li>If <code>nums[i]</code> is positive, move <code>nums[i]</code> steps <strong>forward</strong>, and</li>\n\t<li>If <code>nums[i]</code> is negative, move <code>nums[i]</code> steps <strong>backward</strong>.</li>\n</ul>\n\n<p>Since the array is <strong>circular</strong>, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.</p>\n\n<p>A <strong>cycle</strong> in the array consists of a sequence of indices <code>seq</code> of length <code>k</code> where:</p>\n\n<ul>\n\t<li>Following the movement rules above results in the repeating index sequence <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li>\n\t<li>Every <code>nums[seq[j]]</code> is either <strong>all positive</strong> or <strong>all negative</strong>.</li>\n\t<li><code>k &gt; 1</code></li>\n</ul>\n\n<p>Return <code>true</code><em> if there is a <strong>cycle</strong> in </em><code>nums</code><em>, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img1.jpg\" style=\"width: 402px; height: 289px;\" />\n<pre>\n<strong>Input:</strong> nums = [2,-1,1,2,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., and all of its nodes are white (jumping in the same direction).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img2.jpg\" style=\"width: 402px; height: 390px;\" />\n<pre>\n<strong>Input:</strong> nums = [-1,-2,-3,-4,-5,6]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nThe only cycle is of size 1, so we return false.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img3.jpg\" style=\"width: 497px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> nums = [1,-1,5,1,4]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --&gt; 1 --&gt; 0 --&gt; ..., and while it is of size &gt; 1, it has a node jumping forward and a node jumping backward, so <strong>it is not a cycle</strong>.\nWe can see the cycle 3 --&gt; 4 --&gt; 3 --&gt; ..., and all of its nodes are white (jumping in the same direction).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>nums[i] != 0</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time complexity and <code>O(1)</code> extra space complexity?</p>\n",
    "solution_url": "https://leetcode.com/problems/circular-array-loop/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def circularArrayLoop(self, nums: List[int]) -> bool:\n    def advance(i: int) -> int:\n      return (i + nums[i]) % len(nums)\n\n    if len(nums) < 2:\n      return False\n\n    for i, num in enumerate(nums):\n      if num == 0:\n        continue\n\n      slow = i\n      fast = advance(slow)\n      while num * nums[fast] > 0 and num * nums[advance(fast)] > 0:\n        if slow == fast:\n          if slow == advance(slow):\n            break\n          return True\n        slow = advance(slow)\n        fast = advance(advance(fast))\n\n      slow = i\n      sign = num\n      while sign * nums[slow] > 0:\n        next = advance(slow)\n        nums[slow] = 0\n        slow = next\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean circularArrayLoop(int[] nums) {\n    if (nums.length < 2)\n      return false;\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (nums[i] == 0)\n        continue;\n      int slow = i;\n      int fast = advance(nums, slow);\n      while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(nums, fast)] > 0) {\n        if (slow == fast) {\n          if (slow == advance(nums, slow))\n            break;\n          return true;\n        }\n        slow = advance(nums, slow);\n        fast = advance(nums, advance(nums, fast));\n      }\n\n      slow = i;\n      final int sign = nums[i];\n      while (sign * nums[slow] > 0) {\n        final int next = advance(nums, slow);\n        nums[slow] = 0;\n        slow = next;\n      }\n    }\n\n    return false;\n  }\n\n  private int advance(int[] nums, int i) {\n    final int n = nums.length;\n    final int val = (i + nums[i]) % n;\n    return i + nums[i] >= 0 ? val : n + val;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool circularArrayLoop(vector<int>& nums) {\n    const int n = nums.size();\n    if (n < 2)\n      return false;\n\n    auto advance = [&](int i) {\n      const int val = (i + nums[i]) % n;\n      return i + nums[i] >= 0 ? val : n + val;\n    };\n\n    for (int i = 0; i < n; ++i) {\n      if (nums[i] == 0)\n        continue;\n      int slow = i;\n      int fast = advance(slow);\n      while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(fast)] > 0) {\n        if (slow == fast) {\n          if (slow == advance(slow))\n            break;\n          return true;\n        }\n        slow = advance(slow);\n        fast = advance(advance(fast));\n      }\n\n      slow = i;\n      const int sign = nums[i];\n      while (sign * nums[slow] > 0) {\n        const int next = advance(slow);\n        nums[slow] = 0;\n        slow = next;\n      }\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/457.html",
    "category": "Algorithms",
    "acceptance_rate": 35.46919757094298,
    "topics": [
      "Array",
      "Hash Table",
      "Two Pointers"
    ],
    "hints": [],
    "likes": 742,
    "dislikes": 837,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"92.9K\", \"totalSubmission\": \"261.8K\", \"totalAcceptedRaw\": 92868, \"totalSubmissionRaw\": 261827, \"acRate\": \"35.5%\"}",
    "title_pt": "Loop em Array Circular",
    "description_pt": "<p>Você está jogando um jogo que envolve um array <strong>circular</strong> de inteiros não nulos <code>nums</code>. Cada <code>nums[i]</code> denota o número de índices para frente/para trás que você deve mover se estiver localizado no índice <code>i</code>:</p>\n\n<ul>\n\t<li>Se <code>nums[i]</code> for positivo, mova <code>nums[i]</code> passos para <strong>frente</strong>, e</li>\n\t<li>Se <code>nums[i]</code> for negativo, mova <code>nums[i]</code> passos para <strong>trás</strong>.</li>\n</ul>\n\n<p>Como o array é <strong>circular</strong>, você pode assumir que mover-se para frente a partir do último elemento coloca você no primeiro elemento, e mover-se para trás a partir do primeiro elemento coloca você no último elemento.</p>\n\n<p>Um <strong>ciclo</strong> no array consiste em uma sequência de índices <code>seq</code> de comprimento <code>k</code> em que:</p>\n\n<ul>\n\t<li>Seguir as regras de movimento acima resulta na sequência repetida de índices <code>seq[0] -&gt; seq[1] -&gt; ... -&gt; seq[k - 1] -&gt; seq[0] -&gt; ...</code></li>\n\t<li>Cada <code>nums[seq[j]]</code> é ou <strong>todo positivo</strong> ou <strong>todo negativo</strong>.</li>\n\t<li><code>k &gt; 1</code></li>\n</ul>\n\n<p>Retorne <code>true</code><em> se houver um <strong>ciclo</strong> em </em><code>nums</code><em>, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img1.jpg\" style=\"width: 402px; height: 289px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [2,-1,1,2,2]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O grafo mostra como os índices estão conectados. Os nós brancos saltam para frente, enquanto os vermelhos saltam para trás.\nPodemos ver o ciclo 0 --&gt; 2 --&gt; 3 --&gt; 0 --&gt; ..., e todos os seus nós são brancos (saltando na mesma direção).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img2.jpg\" style=\"width: 402px; height: 390px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [-1,-2,-3,-4,-5,6]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> O grafo mostra como os índices estão conectados. Os nós brancos saltam para frente, enquanto os vermelhos saltam para trás.\nO único ciclo tem tamanho 1, então retornamos false.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/09/01/img3.jpg\" style=\"width: 497px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [1,-1,5,1,4]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O grafo mostra como os índices estão conectados. Os nós brancos saltam para frente, enquanto os vermelhos saltam para trás.\nPodemos ver o ciclo 0 --&gt; 1 --&gt; 0 --&gt; ..., e embora ele tenha tamanho &gt; 1, ele possui um nó saltando para frente e um nó saltando para trás, então <strong>não é um ciclo</strong>.\nPodemos ver o ciclo 3 --&gt; 4 --&gt; 3 --&gt; ..., e todos os seus nós são brancos (saltando na mesma direção).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5000</code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>nums[i] != 0</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria resolver isso em complexidade de tempo <code>O(n)</code> e complexidade de espaço extra <code>O(1)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "458",
    "paidOnly": false,
    "title": "Poor Pigs",
    "titleSlug": "poor-pigs",
    "url": "https://leetcode.com/problems/poor-pigs",
    "description_url": "https://leetcode.com/problems/poor-pigs/description/",
    "description": "<p>There are <code>buckets</code> buckets of liquid, where <strong>exactly one</strong> of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have <code>minutesToTest</code> minutes to determine which bucket is poisonous.</p>\n\n<p>You can feed the pigs according to these steps:</p>\n\n<ol>\n\t<li>Choose some live pigs to feed.</li>\n\t<li>For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.</li>\n\t<li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li>\n\t<li>After <code>minutesToDie</code> minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.</li>\n\t<li>Repeat this process until you run out of time.</li>\n</ol>\n\n<p>Given <code>buckets</code>, <code>minutesToDie</code>, and <code>minutesToTest</code>, return <em>the <strong>minimum</strong> number of pigs needed to figure out which bucket is poisonous within the allotted time</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buckets &lt;= 1000</code></li>\n\t<li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/poor-pigs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n    return ceil(log(buckets) / log(minutesToTest // minutesToDie + 1))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n    return (int) Math.ceil(Math.log(buckets) / Math.log(minutesToTest / minutesToDie + 1));\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int poorPigs(int buckets, int minutesToDie, int minutesToTest) {\n    return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/458.html",
    "category": "Algorithms",
    "acceptance_rate": 59.233403270800075,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Combinatorics"
    ],
    "hints": [
      "What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test.",
      "How many states can we generate with x pigs and T tests?",
      "Find minimum <code>x</code> such that <code>(T+1)^x >= N</code>"
    ],
    "likes": 1824,
    "dislikes": 3365,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"125.1K\", \"totalSubmission\": \"211.1K\", \"totalAcceptedRaw\": 125066, \"totalSubmissionRaw\": 211141, \"acRate\": \"59.2%\"}",
    "title_pt": "Porcos Pobres",
    "description_pt": "<p>Há <code>buckets</code> baldes de líquido, onde <strong>exatamente um</strong> dos baldes é venenoso. Para descobrir qual deles é venenoso, você alimenta alguns (pobres) porcos com o líquido para ver se eles morrerão ou não. Infelizmente, você só tem <code>minutesToTest</code> minutos para determinar qual balde é venenoso.</p>\n\n<p>Você pode alimentar os porcos de acordo com estes passos:</p>\n\n<ol>\n\t<li>Escolha alguns porcos vivos para alimentar.</li>\n\t<li>Para cada porco, escolha quais baldes oferecer a ele. O porco consumirá todos os baldes escolhidos simultaneamente e não levará tempo. Cada porco pode se alimentar de qualquer número de baldes, e cada balde pode ser oferecido a qualquer número de porcos.</li>\n\t<li>Aguarde <code>minutesToDie</code> minutos. Você <strong>não</strong> pode alimentar quaisquer outros porcos durante esse tempo.</li>\n\t<li>Depois que <code>minutesToDie</code> minutos tiverem passado, quaisquer porcos que tenham recebido o balde venenoso morrerão, e todos os outros sobreviverão.</li>\n\t<li>Repita esse processo até que o tempo acabe.</li>\n</ol>\n\n<p>Dados <code>buckets</code>, <code>minutesToDie</code> e <code>minutesToTest</code>, retorne <em>o número <strong>mínimo</strong> de porcos necessário para descobrir qual balde é venenoso dentro do tempo disponível</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Podemos determinar o balde venenoso da seguinte forma:\nNo tempo 0, alimente o primeiro porco com os baldes 1 e 2, e alimente o segundo porco com os baldes 2 e 3.\nNo tempo 15, há 4 possíveis resultados:\n- Se apenas o primeiro porco morrer, então o balde 1 deve ser venenoso.\n- Se apenas o segundo porco morrer, então o balde 3 deve ser venenoso.\n- Se ambos os porcos morrerem, então o balde 2 deve ser venenoso.\n- Se nenhum dos porcos morrer, então o balde 4 deve ser venenoso.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Podemos determinar o balde venenoso da seguinte forma:\nNo tempo 0, alimente o primeiro porco com o balde 1, e alimente o segundo porco com o balde 2.\nNo tempo 15, há 2 possíveis resultados:\n- Se qualquer porco morrer, então o balde venenoso é aquele que foi dado a ele.\n- Se nenhum dos porcos morrer, então alimente o primeiro porco com o balde 3, e alimente o segundo porco com o balde 4.\nNo tempo 30, um dos dois porcos deve morrer, e o balde venenoso é aquele que foi dado a ele.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= buckets &lt;= 1000</code></li>\n\t<li><code>1 &lt;=&nbsp;minutesToDie &lt;=&nbsp;minutesToTest &lt;= 100</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: E se você só tiver uma tentativa? Por exemplo, 4 baldes, 15 minutos para morrer e 15 minutos para testar.",
      "Dica 2: Quantos estados podemos gerar com x porcos e T testes?",
      "Dica 3: Encontre o menor <code>x</code> tal que <code>(T+1)^x >= N</code>"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "459",
    "paidOnly": false,
    "title": "Repeated Substring Pattern",
    "titleSlug": "repeated-substring-pattern",
    "url": "https://leetcode.com/problems/repeated-substring-pattern",
    "description_url": "https://leetcode.com/problems/repeated-substring-pattern/description/",
    "description": "<p>Given a string <code>s</code>, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abab&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> It is the substring &quot;ab&quot; twice.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aba&quot;\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abcabcabcabc&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> It is the substring &quot;abc&quot; four times or the substring &quot;abcabc&quot; twice.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/repeated-substring-pattern/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def repeatedSubstringPattern(self, s: str) -> bool:\n    return s in (s + s)[1:-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean repeatedSubstringPattern(String s) {\n    final String ss = s + s;\n    return ss.substring(1, ss.length() - 1).contains(s);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool repeatedSubstringPattern(string s) {\n    const string ss = s + s;\n    return ss.substr(1, ss.length() - 2).find(s) != string::npos;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/459.html",
    "category": "Algorithms",
    "acceptance_rate": 46.79307409169442,
    "topics": [
      "String",
      "String Matching"
    ],
    "hints": [],
    "likes": 6611,
    "dislikes": 545,
    "similar_questions": "[{\"title\": \"Find the Index of the First Occurrence in a String\", \"titleSlug\": \"find-the-index-of-the-first-occurrence-in-a-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Repeated String Match\", \"titleSlug\": \"repeated-string-match\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"523.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 523257, \"totalSubmissionRaw\": 1118236, \"acRate\": \"46.8%\"}",
    "title_pt": "Padrão de Substring Repetida",
    "description_pt": "<p>Dada uma string <code>s</code>, verifique se ela pode ser construída pegando uma substring dela e anexando múltiplas cópias da substring em sequência.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abab&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Ela é a substring &quot;ab&quot; duas vezes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aba&quot;\n<strong>Saída:</strong> false\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abcabcabcabc&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Ela é a substring &quot;abc&quot; quatro vezes ou a substring &quot;abcabc&quot; duas vezes.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste em letras minúsculas do alfabeto ইংlês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "460",
    "paidOnly": false,
    "title": "LFU Cache",
    "titleSlug": "lfu-cache",
    "url": "https://leetcode.com/problems/lfu-cache",
    "description_url": "https://leetcode.com/problems/lfu-cache/description/",
    "description": "<p>Design and implement a data structure for a <a href=\"https://en.wikipedia.org/wiki/Least_frequently_used\" target=\"_blank\">Least Frequently Used (LFU)</a> cache.</p>\n\n<p>Implement the <code>LFUCache</code> class:</p>\n\n<ul>\n\t<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>\n\t<li><code>int get(int key)</code> Gets the value of the <code>key</code> if the <code>key</code> exists in the cache. Otherwise, returns <code>-1</code>.</li>\n\t<li><code>void put(int key, int value)</code> Update the value of the <code>key</code> if present, or inserts the <code>key</code> if not already present. When the cache reaches its <code>capacity</code>, it should invalidate and remove the <strong>least frequently used</strong> key before inserting a new item. For this problem, when there is a <strong>tie</strong> (i.e., two or more keys with the same frequency), the <strong>least recently used</strong> <code>key</code> would be invalidated.</li>\n</ul>\n\n<p>To determine the least frequently used key, a <strong>use counter</strong> is maintained for each key in the cache. The key with the smallest <strong>use counter</strong> is the least frequently used key.</p>\n\n<p>When a key is first inserted into the cache, its <strong>use counter</strong> is set to <code>1</code> (due to the <code>put</code> operation). The <strong>use counter</strong> for a key in the cache is incremented either a <code>get</code> or <code>put</code> operation is called on it.</p>\n\n<p>The functions&nbsp;<code data-stringify-type=\"code\">get</code>&nbsp;and&nbsp;<code data-stringify-type=\"code\">put</code>&nbsp;must each run in <code>O(1)</code> average time complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;LFUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\n<strong>Output</strong>\n[null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n\n<strong>Explanation</strong>\n// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1);   // cache=[1,_], cnt(1)=1\nlfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1);      // return 1\n                 // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n&nbsp;                // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n                 // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4);      // return 4\n                 // cache=[4,3], cnt(4)=2, cnt(3)=3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= capacity&nbsp;&lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= key &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= value &lt;= 10<sup>9</sup></code></li>\n\t<li>At most <code>2 * 10<sup>5</sup></code>&nbsp;calls will be made to <code>get</code> and <code>put</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<span style=\"display: none;\">&nbsp;</span>",
    "solution_url": "https://leetcode.com/problems/lfu-cache/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Approach 1: Maintaining 2 HashMaps\n\n#### Intuition\n\nWe need to maintain all the keys, values and frequencies. Without invalidation (removing from the data structure when it reaches capacity), they can be maintained by a HashMap<Integer, Pair<Integer, Integer>>, keyed by the original `key` and valued by the `frequency`-`value` pair.\n\nWith the invalidation, we need to maintain the current minimum frequency and delete particular keys. Hence, we can group the keys with the same frequency together and maintain another HashMap<Integer, Set<Integer>>, keyed by the frequency and valued by the set of `keys` that have the same frequency. This way, if we know the minimum frequency, we can access the potential keys to be deleted.\n\nAlso note that in the case of a tie, we're required to find the least recently used key and invalidate it, hence we need to keep the frequencies ordered in the Set. Instead of using a TreeSet which adds an extra $O(log(N))$ time complexity, we can maintain the keys using a LinkedList so that it supports finding both an arbitrary key and the least recently used key in constant time. Fortunately, LinkedHashSet can do the job. Once a `key` is inserted/updated, we put it to the end of the LinkedHashSet so that we can invalidate the first `key` in the LinkedHashSet corresponding to the minimum frequency.\n\nThe original operations can be transformed into operations on the 2 HashMaps, keeping them in sync and maintaining the minimum frequency.\n\nSince C++ lacks LinkedHashSet, we have to use a workaround like maintaining a list of key and value pairs instead of the LinkedHashSet and keeping the iterator with the frequency in another unordered_map to keep this connection. The idea is similar but a little bit complicated. Another workaround would be to implement your own LRU cache with a doubly linked list.\n\n\n#### Algorithm\n\nTo make things simpler, assume we have 4 member variables:\n1. `HashMap<Integer, Pair<Integer, Integer>> cache`, keyed by the original `key` and valued by the `frequency`-`value` pair. \n2. `HashMap<Integer, LinkedListHashSet<Integer>> frequencies`, keyed by frequency and valued by the set of `keys` that have the same frequency.\n3. `int minf`, which is the minimum frequency at any given time.\n4. `int capacity`, which is the `capacity` given in the input.\n\nIt's also convenient to have a private utility function `insert` to insert a `key`-`value` pair with a given frequency.\n\n##### void insert(int key, int frequency, int value)\n1. Insert `frequency`-`value` pair into `cache` with the given `key`.\n2. Get the LinkedHashSet corresponding to the given `frequency` (default to empty Set) and insert the given `key`.\n\n\n##### int get(int key)\n1. If the given `key` is not in the `cache`, return `-1`, otherwise go to step `2`.\n2. Get the `frequency` and `value` from the `cache`.\n3. Get the LinkedHashSet associated with `frequency` from `frequencies` and remove the given `key` from it, since the usage of the current key is increased by this function call.\n4. If `minf` == `frequency` and the above LinkedHashSet is empty, that means there are no more elements used `minf` times, so increase `minf` by 1. To save some space, we can also delete the entry `frequency` from the `frequencies` hash map.\n5. Call insert(`key`, `frequency` + 1, `value`), since the current key's usage has increased from this function call.\n6. Return `value`\n\n##### void put(int key, int value)\n1. If `capacity` <= 0, exit.\n2. If the given `key` exists in `cache`, update the `value` in the original `frequency`-`value` (don't call insert here), and then increment the frequency by using get(`key`). Exit the function.\n3. If `cache.size()` == `capacity`, get the first (least recently used) value in the LinkedHashSet corresponding to `minf` in `frequencies`, and remove it from `cache` and the LinkedHashSet.\n4. If we didn't exit the function in step 2, it means that this element is a new one, so the minimum frequency cannot possibly be greater than one. Set `minf` to 1.\n5. Call insert(`key`, 1, `value`)\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/njKVWiZK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"njKVWiZK\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the total number of operations.\n\n* Time complexity: $O(1)$, as required by the question.\n\n    Since we only have basic HashMap/(Linked)HashSet operations. For details,\n\n    Our utility function `insert` puts the `key`- `value` pair into the `cache`, queries and possibly puts an empty LinedHashSet in the `frequencies`, then queries `frequencies` again and adds a `key` into the associated `value` which is a LinkedHashSet. All the operations are based on the hash calculating for simple type (int or Integer) and the time complexity is constant.\n\n\n    For each `get` operation, in the worst case, we query the `frequencies` and remove a `key` from the associated `value` which is a LinkedHashSet and call `insert` function once. All the operations have the constant time complexity based on the hash calculating for simple type.\n\n    For each `put` operation, in the simple case we just insert the new `key`-`value` pair into the `cache` and call `get` function once. In the worst case, we query the `frequencies` to get the associated `value`, namely all the `keys` with the same frequencies which is a LinkedHashSet. And then we get the first key from the LinkedHashSet, remove it from both `cache` and `frequencies`. All the operations have the constant time complexity based on the hash calculating for simple type.\n\n* Space complexity: $O(N)$.\n\n    We save all the `key`-`value` pairs as well as all the keys with frequencies in the 2 HashMaps (plus a LinkedHashSet), so there are at most $min(N, capacity) `keys` and `values` at any given time.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass LFUCache {\n  public LFUCache(int capacity) {\n    this.capacity = capacity;\n  }\n\n  public int get(int key) {\n    if (!keyToVal.containsKey(key))\n      return -1;\n\n    final int freq = keyToFreq.get(key);\n    freqToLRUKeys.get(freq).remove(key);\n    if (freq == minFreq && freqToLRUKeys.get(freq).isEmpty()) {\n      freqToLRUKeys.remove(freq);\n      ++minFreq;\n    }\n\n    // Increase key's freq by 1\n    // Add this key to next freq's list\n    putFreq(key, freq + 1);\n    return keyToVal.get(key);\n  }\n\n  public void put(int key, int value) {\n    if (capacity == 0)\n      return;\n    if (keyToVal.containsKey(key)) {\n      keyToVal.put(key, value);\n      get(key); // Update key's count\n      return;\n    }\n\n    if (keyToVal.size() == capacity) {\n      // Evict LRU key from the minFreq list\n      final int keyToEvict = freqToLRUKeys.get(minFreq).iterator().next();\n      freqToLRUKeys.get(minFreq).remove(keyToEvict);\n      keyToVal.remove(keyToEvict);\n    }\n\n    minFreq = 1;\n    putFreq(key, minFreq);    // Add new key and freq\n    keyToVal.put(key, value); // Add new key and value\n  }\n\n  private int capacity;\n  private int minFreq = 0;\n  private Map<Integer, Integer> keyToVal = new HashMap<>();\n  private Map<Integer, Integer> keyToFreq = new HashMap<>();\n  private Map<Integer, LinkedHashSet<Integer>> freqToLRUKeys = new HashMap<>();\n\n  private void putFreq(int key, int freq) {\n    keyToFreq.put(key, freq);\n    freqToLRUKeys.putIfAbsent(freq, new LinkedHashSet<>());\n    freqToLRUKeys.get(freq).add(key);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Node {\n  int key;\n  int value;\n  int freq;\n  list<int>::const_iterator it;\n};\n\nclass LFUCache {\n public:\n  LFUCache(int capacity) : capacity(capacity), minFreq(0) {}\n\n  int get(int key) {\n    if (!keyToNode.count(key))\n      return -1;\n\n    Node& node = keyToNode[key];\n    touch(node);\n    return node.value;\n  }\n\n  void put(int key, int value) {\n    if (capacity == 0)\n      return;\n    if (keyToNode.count(key)) {\n      Node& node = keyToNode[key];\n      node.value = value;\n      touch(node);\n      return;\n    }\n\n    if (keyToNode.size() == capacity) {\n      // Evict LRU key from the minFreq list\n      const int keyToEvict = freqToList[minFreq].back();\n      freqToList[minFreq].pop_back();\n      keyToNode.erase(keyToEvict);\n    }\n\n    minFreq = 1;\n    freqToList[1].push_front(key);\n    keyToNode[key] = {key, value, 1, cbegin(freqToList[1])};\n  }\n\n private:\n  int capacity;\n  int minFreq;\n  unordered_map<int, Node> keyToNode;\n  unordered_map<int, list<int>> freqToList;\n\n  void touch(Node& node) {\n    // Update the node's frequency\n    const int prevFreq = node.freq;\n    const int newFreq = ++node.freq;\n\n    // Remove the iterator from prevFreq's list\n    freqToList[prevFreq].erase(node.it);\n    if (freqToList[prevFreq].empty()) {\n      freqToList.erase(prevFreq);\n      // Update minFreq if needed\n      if (prevFreq == minFreq)\n        ++minFreq;\n    }\n\n    // Insert the key to the front of newFreq's list\n    freqToList[newFreq].push_front(node.key);\n    node.it = cbegin(freqToList[newFreq]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/460.html",
    "category": "Algorithms",
    "acceptance_rate": 46.312208847514555,
    "topics": [
      "Hash Table",
      "Linked List",
      "Design",
      "Doubly-Linked List"
    ],
    "hints": [],
    "likes": 5965,
    "dislikes": 338,
    "similar_questions": "[{\"title\": \"LRU Cache\", \"titleSlug\": \"lru-cache\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design In-Memory File System\", \"titleSlug\": \"design-in-memory-file-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"302.5K\", \"totalSubmission\": \"653.2K\", \"totalAcceptedRaw\": 302521, \"totalSubmissionRaw\": 653222, \"acRate\": \"46.3%\"}",
    "title_pt": "Cache LFU",
    "description_pt": "<p>Projete e implemente uma estrutura de dados para um cache <a href=\"https://en.wikipedia.org/wiki/Least_frequently_used\" target=\"_blank\">Least Frequently Used (LFU)</a>.</p>\n\n<p>Implemente a classe <code>LFUCache</code>:</p>\n\n<ul>\n\t<li><code>LFUCache(int capacity)</code> Inicializa o objeto com a <code>capacity</code> da estrutura de dados.</li>\n\t<li><code>int get(int key)</code> Obtém o valor da <code>key</code> se a <code>key</code> existir no cache. Caso contrário, retorna <code>-1</code>.</li>\n\t<li><code>void put(int key, int value)</code> Atualiza o valor da <code>key</code> se ela estiver presente, ou insere a <code>key</code> se ela ainda não estiver presente. Quando o cache atinge sua <code>capacity</code>, ele deve invalidar e remover a <strong>chave menos frequentemente usada</strong> antes de inserir um novo item. Para este problema, quando houver um <strong>empate</strong> (isto é, duas ou mais chaves com a mesma frequência), a <strong>chave menos recentemente usada</strong> será invalidada.</li>\n</ul>\n\n<p>Para determinar a chave menos frequentemente usada, um <strong>contador de uso</strong> é mantido para cada chave no cache. A chave com o menor <strong>contador de uso</strong> é a chave menos frequentemente usada.</p>\n\n<p>Quando uma chave é inserida pela primeira vez no cache, seu <strong>contador de uso</strong> é definido como <code>1</code> (devido à operação <code>put</code>). O <strong>contador de uso</strong> de uma chave no cache é incrementado sempre que uma operação <code>get</code> ou <code>put</code> é chamada sobre ela.</p>\n\n<p>As funções&nbsp;<code data-stringify-type=\"code\">get</code>&nbsp;e&nbsp;<code data-stringify-type=\"code\">put</code>&nbsp;devem executar cada uma em complexidade de tempo médio <code>O(1)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;LFUCache&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;get&quot;]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\n<strong>Saída</strong>\n[null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n\n<strong>Explicação</strong>\n// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is  most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1);   // cache=[1,_], cnt(1)=1\nlfu.put(2, 2);   // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1);      // return 1\n                 // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3);   // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n&nbsp;                // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4);   // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n                 // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1);      // return -1 (not found)\nlfu.get(3);      // return 3\n                 // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4);      // return 4\n                 // cache=[4,3], cnt(4)=2, cnt(3)=3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= capacity&nbsp;&lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= key &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= value &lt;= 10<sup>9</sup></code></li>\n\t<li>No máximo <code>2 * 10<sup>5</sup></code>&nbsp;chamadas serão feitas a <code>get</code> e <code>put</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<span style=\"display: none;\">&nbsp;</span>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "461",
    "paidOnly": false,
    "title": "Hamming Distance",
    "titleSlug": "hamming-distance",
    "url": "https://leetcode.com/problems/hamming-distance",
    "description_url": "https://leetcode.com/problems/hamming-distance/description/",
    "description": "<p>The <a href=\"https://en.wikipedia.org/wiki/Hamming_distance\" target=\"_blank\">Hamming distance</a> between two integers is the number of positions at which the corresponding bits are different.</p>\n\n<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 1, y = 4\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\n1   (0 0 0 1)\n4   (0 1 0 0)\n       &uarr;   &uarr;\nThe above arrows point to positions where the corresponding bits are different.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> x = 3, y = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;=&nbsp;x, y &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as <a href=\"https://leetcode.com/problems/minimum-bit-flips-to-convert-number/description/\" target=\"_blank\"> 2220: Minimum Bit Flips to Convert Number.</a></p>\n",
    "solution_url": "https://leetcode.com/problems/hamming-distance/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int hammingDistance(int x, int y) {\n    int ans = 0;\n\n    while (x > 0 || y > 0) {\n      ans += (x & 1) ^ (y & 1);\n      x >>= 1;\n      y >>= 1;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int hammingDistance(int x, int y) {\n    int ans = 0;\n\n    while (x || y) {\n      ans += (x & 1) ^ (y & 1);\n      x >>= 1;\n      y >>= 1;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/461.html",
    "category": "Algorithms",
    "acceptance_rate": 76.03682186913949,
    "topics": [
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 3934,
    "dislikes": 224,
    "similar_questions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Total Hamming Distance\", \"titleSlug\": \"total-hamming-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"630.1K\", \"totalSubmission\": \"828.6K\", \"totalAcceptedRaw\": 630069, \"totalSubmissionRaw\": 828637, \"acRate\": \"76.0%\"}",
    "title_pt": "Distância de Hamming",
    "description_pt": "<p>A <a href=\"https://en.wikipedia.org/wiki/Hamming_distance\" target=\"_blank\">distância de Hamming</a> entre dois inteiros é o número de posições nas quais os bits correspondentes são diferentes.</p>\n\n<p>Dados dois inteiros <code>x</code> e <code>y</code>, retorne <em>a <strong>distância de Hamming</strong> entre eles</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 1, y = 4\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong>\n1   (0 0 0 1)\n4   (0 1 0 0)\n       &uarr;   &uarr;\nAs setas acima apontam para posições nas quais os bits correspondentes são diferentes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> x = 3, y = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;=&nbsp;x, y &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que <a href=\"https://leetcode.com/problems/minimum-bit-flips-to-convert-number/description/\" target=\"_blank\"> 2220: Minimum Bit Flips to Convert Number.</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "462",
    "paidOnly": false,
    "title": "Minimum Moves to Equal Array Elements II",
    "titleSlug": "minimum-moves-to-equal-array-elements-ii",
    "url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii",
    "description_url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/",
    "description": "<p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p>\n\n<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>\n\n<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\nOnly two moves are needed (remember each move increments or decrements one element):\n[<u>1</u>,2,3]  =&gt;  [2,2,<u>3</u>]  =&gt;  [2,2,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,10,2,9]\n<strong>Output:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nimport statistics\n\n\nclass Solution:\n  def minMoves2(self, nums: List[int]) -> int:\n    median = int(statistics.median(nums))\n    return sum(abs(num - median) for num in nums)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minMoves2(int[] nums) {\n    final int n = nums.length;\n    final int median = quickSelect(nums, 0, n - 1, (n + 1) / 2);\n    int ans = 0;\n\n    for (final int num : nums)\n      ans += Math.abs(num - median);\n\n    return ans;\n  }\n\n  private int quickSelect(int[] nums, int l, int r, int k) {\n    final int randIndex = new Random().nextInt(r - l + 1) + l;\n    swap(nums, randIndex, r);\n    final int pivot = nums[r];\n\n    int nextSwapped = l;\n    for (int i = l; i < r; ++i)\n      if (nums[i] <= pivot)\n        swap(nums, nextSwapped++, i);\n    swap(nums, nextSwapped, r);\n\n    final int count = nextSwapped - l + 1;\n    if (count == k)\n      return nums[nextSwapped];\n    if (count > k)\n      return quickSelect(nums, l, nextSwapped - 1, k);\n    return quickSelect(nums, nextSwapped + 1, r, k - count);\n  }\n\n  private void swap(int[] nums, int i, int j) {\n    final int temp = nums[i];\n    nums[i] = nums[j];\n    nums[j] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minMoves2(vector<int>& nums) {\n    const int n = nums.size();\n    nth_element(begin(nums), begin(nums) + n / 2, end(nums));\n    const int median = nums[n / 2];\n    return accumulate(begin(nums), end(nums), 0,\n                      [&](int a, int b) { return a + abs(b - median); });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/462.html",
    "category": "Algorithms",
    "acceptance_rate": 60.88858064458269,
    "topics": [
      "Array",
      "Math",
      "Sorting"
    ],
    "hints": [],
    "likes": 3451,
    "dislikes": 128,
    "similar_questions": "[{\"title\": \"Best Meeting Point\", \"titleSlug\": \"best-meeting-point\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Moves to Equal Array Elements\", \"titleSlug\": \"minimum-moves-to-equal-array-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make a Uni-Value Grid\", \"titleSlug\": \"minimum-operations-to-make-a-uni-value-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Removing Minimum Number of Magic Beans\", \"titleSlug\": \"removing-minimum-number-of-magic-beans\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost to Make Array Equal\", \"titleSlug\": \"minimum-cost-to-make-array-equal\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make All Array Elements Equal\", \"titleSlug\": \"minimum-operations-to-make-all-array-elements-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost to Make Array Equalindromic\", \"titleSlug\": \"minimum-cost-to-make-array-equalindromic\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Subarray Elements Equal\", \"titleSlug\": \"minimum-operations-to-make-subarray-elements-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Elements Within K Subarrays Equal\", \"titleSlug\": \"minimum-operations-to-make-elements-within-k-subarrays-equal\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"203.7K\", \"totalSubmission\": \"334.5K\", \"totalAcceptedRaw\": 203676, \"totalSubmissionRaw\": 334508, \"acRate\": \"60.9%\"}",
    "title_pt": "Número Mínimo de Movimentos para Tornar os Elementos do Array Iguais II",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> de tamanho <code>n</code>, retorne <em>o número mínimo de movimentos necessários para tornar todos os elementos do array iguais</em>.</p>\n\n<p>Em um movimento, você pode incrementar ou decrementar um elemento do array em <code>1</code>.</p>\n\n<p>Os casos de teste são elaborados de modo que a resposta caiba em um inteiro de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong>\nApenas dois movimentos são necessários (lembre-se de que cada movimento incrementa ou decrementa um elemento):\n[<u>1</u>,2,3]  =&gt;  [2,2,<u>3</u>]  =&gt;  [2,2,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,10,2,9]\n<strong>Saída:</strong> 16\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "463",
    "paidOnly": false,
    "title": "Island Perimeter",
    "titleSlug": "island-perimeter",
    "url": "https://leetcode.com/problems/island-perimeter",
    "description_url": "https://leetcode.com/problems/island-perimeter/description/",
    "description": "<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents&nbsp;land and <code>grid[i][j] = 0</code> represents water.</p>\n\n<p>Grid cells are connected <strong>horizontally/vertically</strong> (not diagonally). The <code>grid</code> is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).</p>\n\n<p>The island doesn&#39;t have &quot;lakes&quot;, meaning the water inside isn&#39;t connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don&#39;t exceed 100. Determine the perimeter of the island.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/island.png\" style=\"width: 221px; height: 213px;\" />\n<pre>\n<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\n<strong>Output:</strong> 16\n<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [[1]]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [[1,0]]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>row == grid.length</code></li>\n\t<li><code>col == grid[i].length</code></li>\n\t<li><code>1 &lt;= row, col &lt;= 100</code></li>\n\t<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>\n\t<li>There is exactly one island in <code>grid</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/island-perimeter/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def islandPerimeter(self, grid: List[List[int]]) -> int:\n    m = len(grid)\n    n = len(grid[0])\n\n    islands = 0\n    neighbors = 0\n\n    for i in range(m):\n      for j in range(n):\n        if grid[i][j] == 1:\n          islands += 1\n          if i + 1 < m and grid[i + 1][j] == 1:\n            neighbors += 1\n          if j + 1 < n and grid[i][j + 1] == 1:\n            neighbors += 1\n\n    return islands * 4 - neighbors * 2",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int islandPerimeter(int[][] grid) {\n    int islands = 0;\n    int neighbors = 0;\n\n    for (int i = 0; i < grid.length; ++i)\n      for (int j = 0; j < grid[0].length; ++j)\n        if (grid[i][j] == 1) {\n          ++islands;\n          if (i - 1 >= 0 && grid[i - 1][j] == 1)\n            ++neighbors;\n          if (j - 1 >= 0 && grid[i][j - 1] == 1)\n            ++neighbors;\n        }\n\n    return islands * 4 - neighbors * 2;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int islandPerimeter(vector<vector<int>>& grid) {\n    int islands = 0;\n    int neighbors = 0;\n\n    for (int i = 0; i < grid.size(); ++i)\n      for (int j = 0; j < grid[0].size(); ++j)\n        if (grid[i][j]) {\n          ++islands;\n          if (i - 1 >= 0 && grid[i - 1][j])\n            ++neighbors;\n          if (j - 1 >= 0 && grid[i][j - 1])\n            ++neighbors;\n        }\n\n    return islands * 4 - neighbors * 2;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/463.html",
    "category": "Algorithms",
    "acceptance_rate": 73.45897305541433,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 7040,
    "dislikes": 404,
    "similar_questions": "[{\"title\": \"Max Area of Island\", \"titleSlug\": \"max-area-of-island\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flood Fill\", \"titleSlug\": \"flood-fill\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Coloring A Border\", \"titleSlug\": \"coloring-a-border\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"722.5K\", \"totalSubmission\": \"983.5K\", \"totalAcceptedRaw\": 722464, \"totalSubmissionRaw\": 983494, \"acRate\": \"73.5%\"}",
    "title_pt": "Perímetro da Ilha",
    "description_pt": "<p>Você recebe um <code>grid</code> de <code>row x col</code> representando um mapa em que <code>grid[i][j] = 1</code> representa&nbsp;terra e <code>grid[i][j] = 0</code> representa água.</p>\n\n<p>As células do <code>grid</code> são conectadas <strong>horizontalmente/verticalmente</strong> (não diagonalmente). O <code>grid</code> é completamente cercado por água, e existe exatamente uma ilha (isto é, uma ou mais células de terra conectadas).</p>\n\n<p>A ilha não tem &quot;lagos&quot;, o que significa que a água dentro dela não está conectada à água ao redor da ilha. Uma célula é um quadrado com comprimento de lado 1. O grid é retangular, e a largura e a altura não excedem 100. Determine o perímetro da ilha.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/island.png\" style=\"width: 221px; height: 213px;\" />\n<pre>\n<strong>Entrada:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\n<strong>Saída:</strong> 16\n<strong>Explicação:</strong> O perímetro é as 16 faixas amarelas na imagem acima.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [[1]]\n<strong>Saída:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [[1,0]]\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>row == grid.length</code></li>\n\t<li><code>col == grid[i].length</code></li>\n\t<li><code>1 &lt;= row, col &lt;= 100</code></li>\n\t<li><code>grid[i][j]</code> é <code>0</code> ou <code>1</code>.</li>\n\t<li>Existe exatamente uma ilha em <code>grid</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "464",
    "paidOnly": false,
    "title": "Can I Win",
    "titleSlug": "can-i-win",
    "url": "https://leetcode.com/problems/can-i-win",
    "description_url": "https://leetcode.com/problems/can-i-win/description/",
    "description": "<p>In the &quot;100 game&quot; two players take turns adding, to a running total, any integer from <code>1</code> to <code>10</code>. The player who first causes the running total to <strong>reach or exceed</strong> 100 wins.</p>\n\n<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>\n\n<p>For example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total &gt;= 100.</p>\n\n<p>Given two integers <code>maxChoosableInteger</code> and <code>desiredTotal</code>, return <code>true</code> if the first player to move can force a win, otherwise, return <code>false</code>. Assume both players play <strong>optimally</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11\n<strong>Output:</strong> false\n<strong>Explanation:</strong>\nNo matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is &gt;= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= maxChoosableInteger &lt;= 20</code></li>\n\t<li><code>0 &lt;= desiredTotal &lt;= 300</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/can-i-win/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canIWin(int maxChoosableInteger, int desiredTotal) {\n    if (desiredTotal <= 0)\n      return true;\n\n    final int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2;\n    if (sum < desiredTotal)\n      return false;\n\n    return dp(desiredTotal, 0, maxChoosableInteger);\n  }\n\n  // True: can win, false: can't win\n  private Map<Integer, Boolean> memo = new HashMap<>();\n\n  // State: record integers that have been chosen\n  private boolean dp(int total, int state, int n) {\n    if (total <= 0)\n      return false;\n    if (memo.containsKey(state))\n      return memo.get(state);\n\n    for (int i = 1; i <= n; ++i) {\n      if ((state & 1 << i) == 1) // Integer i is used\n        continue;\n      if (!dp(total - i, state | 1 << i, n))\n        return true;\n    }\n\n    memo.put(state, false);\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canIWin(int maxChoosableInteger, int desiredTotal) {\n    if (desiredTotal <= 0)\n      return true;\n\n    const int sum = maxChoosableInteger * (maxChoosableInteger + 1) / 2;\n    if (sum < desiredTotal)\n      return false;\n\n    return dp(desiredTotal, 0, maxChoosableInteger);\n  }\n\n private:\n  unordered_map<int, bool> memo;  // True: can win, false: can't win\n\n  // State: record integers that have been chosen\n  bool dp(int total, int state, int n) {\n    if (total <= 0)\n      return false;\n    if (memo.count(state))\n      return memo[state];\n\n    for (int i = 1; i <= n; ++i) {\n      if (state & 1 << i)  // Integer i is used\n        continue;\n      if (!dp(total - i, state | 1 << i, n))\n        return true;\n    }\n\n    return memo[state] = false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/464.html",
    "category": "Algorithms",
    "acceptance_rate": 30.311293140866546,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Bit Manipulation",
      "Memoization",
      "Game Theory",
      "Bitmask"
    ],
    "hints": [],
    "likes": 2749,
    "dislikes": 416,
    "similar_questions": "[{\"title\": \"Flip Game II\", \"titleSlug\": \"flip-game-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Guess Number Higher or Lower II\", \"titleSlug\": \"guess-number-higher-or-lower-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Predict the Winner\", \"titleSlug\": \"predict-the-winner\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Winning Player in Coin Game\", \"titleSlug\": \"find-the-winning-player-in-coin-game\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Number of Winning Players\", \"titleSlug\": \"find-the-number-of-winning-players\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"108.9K\", \"totalSubmission\": \"359.4K\", \"totalAcceptedRaw\": 108940, \"totalSubmissionRaw\": 359403, \"acRate\": \"30.3%\"}",
    "title_pt": "Posso Ganhar",
    "description_pt": "<p>No \"jogo dos 100\", dois jogadores se alternam adicionando, a um total acumulado, qualquer inteiro de <code>1</code> a <code>10</code>. O jogador que primeiro fizer com que o total acumulado <strong>alcance ou ultrapasse</strong> 100 vence.</p>\n\n<p>E se mudarmos o jogo para que os jogadores <strong>não possam</strong> reutilizar inteiros?</p>\n\n<p>Por exemplo, dois jogadores podem se revezar sorteando de um conjunto comum de números de 1 a 15, sem reposição, até que alcancem um total &gt;= 100.</p>\n\n<p>Dadas duas inteiros <code>maxChoosableInteger</code> e <code>desiredTotal</code>, retorne <code>true</code> se o primeiro jogador a mover puder forçar uma vitória; caso contrário, retorne <code>false</code>. Assuma que ambos os jogadores jogam <strong>otimamente</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> maxChoosableInteger = 10, desiredTotal = 11\n<strong>Saída:</strong> false\n<strong>Explicação:</strong>\nNão importa qual inteiro o primeiro jogador escolha, o primeiro jogador perderá.\nO primeiro jogador pode escolher um inteiro de 1 até 10.\nSe o primeiro jogador escolher 1, o segundo jogador só pode escolher inteiros de 2 até 10.\nO segundo jogador vencerá ao escolher 10 e obter um total = 11, que é &gt;= desiredTotal.\nO mesmo ocorre com outros inteiros escolhidos pelo primeiro jogador; o segundo jogador sempre vencerá.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> maxChoosableInteger = 10, desiredTotal = 0\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> maxChoosableInteger = 10, desiredTotal = 1\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= maxChoosableInteger &lt;= 20</code></li>\n\t<li><code>0 &lt;= desiredTotal &lt;= 300</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "466",
    "paidOnly": false,
    "title": "Count The Repetitions",
    "titleSlug": "count-the-repetitions",
    "url": "https://leetcode.com/problems/count-the-repetitions",
    "description_url": "https://leetcode.com/problems/count-the-repetitions/description/",
    "description": "<p>We define <code>str = [s, n]</code> as the string <code>str</code> which consists of the string <code>s</code> concatenated <code>n</code> times.</p>\n\n<ul>\n\t<li>For example, <code>str == [&quot;abc&quot;, 3] ==&quot;abcabcabc&quot;</code>.</li>\n</ul>\n\n<p>We define that string <code>s1</code> can be obtained from string <code>s2</code> if we can remove some characters from <code>s2</code> such that it becomes <code>s1</code>.</p>\n\n<ul>\n\t<li>For example, <code>s1 = &quot;abc&quot;</code> can be obtained from <code>s2 = &quot;ab<strong><u>dbe</u></strong>c&quot;</code> based on our definition by removing the bolded underlined characters.</li>\n</ul>\n\n<p>You are given two strings <code>s1</code> and <code>s2</code> and two integers <code>n1</code> and <code>n2</code>. You have the two strings <code>str1 = [s1, n1]</code> and <code>str2 = [s2, n2]</code>.</p>\n\n<p>Return <em>the maximum integer </em><code>m</code><em> such that </em><code>str = [str2, m]</code><em> can be obtained from </em><code>str1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\n<strong>Output:</strong> 2\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\n<strong>Output:</strong> 1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 100</code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n\t<li><code>1 &lt;= n1, n2 &lt;= 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-the-repetitions/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Record {\n  public int count;\n  public int nextIndex;\n  public Record(int count, int nextIndex) {\n    this.count = count;\n    this.nextIndex = nextIndex;\n  }\n};\n\nclass Solution {\n  public int getMaxRepetitions(String s1, int n1, String s2, int n2) {\n    List<Record> records = new ArrayList<>(); // [count(s1 matches s2[i:]), next index of s2[i:]]\n\n    for (int i = 0; i < s2.length(); ++i) {\n      int count = 0;\n      int nextIndex = i;\n      for (int j = 0; j < s1.length(); ++j)\n        if (s2.charAt(nextIndex) == s1.charAt(j))\n          if (++nextIndex == s2.length()) { // Have a match\n            ++count;\n            nextIndex = 0;\n          }\n      records.add(new Record(count, nextIndex));\n    }\n\n    int matches = 0; // S1 matches s2\n    int index = 0;\n\n    while (n1-- > 0) {\n      matches += records.get(index).count;\n      index = records.get(index).nextIndex;\n    }\n\n    return matches / n2; // S1 matches S2\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct Record {\n  int count;\n  int nextIndex;\n  Record(int count, int nextIndex) : count(count), nextIndex(nextIndex) {}\n};\n\nclass Solution {\n public:\n  int getMaxRepetitions(string s1, int n1, string s2, int n2) {\n    vector<Record> records;  // [count(s1 matches s2[i:]), next index of s2[i:]]\n\n    for (int i = 0; i < s2.length(); ++i) {\n      int count = 0;\n      int nextIndex = i;\n      for (int j = 0; j < s1.length(); ++j)\n        if (s2[nextIndex] == s1[j])\n          if (++nextIndex == s2.length()) {  // Have a match\n            ++count;\n            nextIndex = 0;\n          }\n      records.emplace_back(count, nextIndex);\n    }\n\n    int matches = 0;  // S1 matches s2\n    int index = 0;\n\n    while (n1--) {\n      matches += records[index].count;\n      index = records[index].nextIndex;\n    }\n\n    return matches / n2;  // S1 matches S2\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/466.html",
    "category": "Algorithms",
    "acceptance_rate": 31.644524086181068,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 421,
    "dislikes": 364,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"22.6K\", \"totalSubmission\": \"71.4K\", \"totalAcceptedRaw\": 22602, \"totalSubmissionRaw\": 71429, \"acRate\": \"31.6%\"}",
    "title_pt": "Contar as Repetições",
    "description_pt": "<p>Definimos <code>str = [s, n]</code> como a string <code>str</code> que consiste na string <code>s</code> concatenada <code>n</code> vezes.</p>\n\n<ul>\n\t<li>Por exemplo, <code>str == [&quot;abc&quot;, 3] ==&quot;abcabcabc&quot;</code>.</li>\n</ul>\n\n<p>Definimos que a string <code>s1</code> pode ser obtida a partir da string <code>s2</code> se pudermos remover alguns caracteres de <code>s2</code> de modo que ela se torne <code>s1</code>.</p>\n\n<ul>\n\t<li>Por exemplo, <code>s1 = &quot;abc&quot;</code> pode ser obtida a partir de <code>s2 = &quot;ab<strong><u>dbe</u></strong>c&quot;</code> com base em nossa definição removendo os caracteres em negrito e sublinhados.</li>\n</ul>\n\n<p>São dadas duas strings <code>s1</code> e <code>s2</code> e dois inteiros <code>n1</code> e <code>n2</code>. Você tem as duas strings <code>str1 = [s1, n1]</code> e <code>str2 = [s2, n2]</code>.</p>\n\n<p>Retorne <em>o maior inteiro </em><code>m</code><em> tal que </em><code>str = [str2, m]</code><em> possa ser obtida a partir de </em><code>str1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\n<strong>Saída:</strong> 2\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\n<strong>Saída:</strong> 1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 100</code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n\t<li><code>1 &lt;= n1, n2 &lt;= 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "467",
    "paidOnly": false,
    "title": "Unique Substrings in Wraparound String",
    "titleSlug": "unique-substrings-in-wraparound-string",
    "url": "https://leetcode.com/problems/unique-substrings-in-wraparound-string",
    "description_url": "https://leetcode.com/problems/unique-substrings-in-wraparound-string/description/",
    "description": "<p>We define the string <code>base</code> to be the infinite wraparound string of <code>&quot;abcdefghijklmnopqrstuvwxyz&quot;</code>, so <code>base</code> will look like this:</p>\n\n<ul>\n\t<li><code>&quot;...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....&quot;</code>.</li>\n</ul>\n\n<p>Given a string <code>s</code>, return <em>the number of <strong>unique non-empty substrings</strong> of </em><code>s</code><em> are present in </em><code>base</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;a&quot;\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Only the substring &quot;a&quot; of s is in base.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cac&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two substrings (&quot;a&quot;, &quot;c&quot;) of s in base.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;zab&quot;\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> There are six substrings (&quot;z&quot;, &quot;a&quot;, &quot;b&quot;, &quot;za&quot;, &quot;ab&quot;, and &quot;zab&quot;) of s in base.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/unique-substrings-in-wraparound-string/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findSubstringInWraproundString(String p) {\n    int maxLength = 1;\n    int[] count = new int[26]; // Substrings end at i\n\n    for (int i = 0; i < p.length(); ++i) {\n      if (i > 0 && (p.charAt(i) - p.charAt(i - 1) == 1 || p.charAt(i - 1) - p.charAt(i) == 25))\n        ++maxLength;\n      else\n        maxLength = 1;\n      final int index = p.charAt(i) - 'a';\n      count[index] = Math.max(count[index], maxLength);\n    }\n\n    return Arrays.stream(count).sum();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findSubstringInWraproundString(string p) {\n    int maxLength = 1;\n    vector<int> count(26);  // Substrings end at i\n\n    for (int i = 0; i < p.length(); ++i) {\n      if (i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25))\n        ++maxLength;\n      else\n        maxLength = 1;\n      const int index = p[i] - 'a';\n      count[index] = max(count[index], maxLength);\n    }\n\n    return accumulate(begin(count), end(count), 0);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/467.html",
    "category": "Algorithms",
    "acceptance_rate": 41.07664054045191,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [
      "One possible solution might be to consider allocating an array size of 26 for each character in the alphabet. (Credits to @r2ysxu)"
    ],
    "likes": 1488,
    "dislikes": 183,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"50.1K\", \"totalSubmission\": \"122K\", \"totalAcceptedRaw\": 50101, \"totalSubmissionRaw\": 121971, \"acRate\": \"41.1%\"}",
    "title_pt": "Substrings Únicas em uma String Circular",
    "description_pt": "<p>Definimos a string <code>base</code> como a string infinita circular de <code>&quot;abcdefghijklmnopqrstuvwxyz&quot;</code>, então <code>base</code> será parecida com isto:</p>\n\n<ul>\n\t<li><code>&quot;...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....&quot;</code>.</li>\n</ul>\n\n<p>Dada uma string <code>s</code>, retorne <em>o número de <strong>substrings únicas não vazias</strong> de </em><code>s</code><em> que estão presentes em </em><code>base</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;a&quot;\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Apenas a substring &quot;a&quot; de s está em base.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cac&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Há duas substrings (&quot;a&quot;, &quot;c&quot;) de s em base.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;zab&quot;\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Há seis substrings (&quot;z&quot;, &quot;a&quot;, &quot;b&quot;, &quot;za&quot;, &quot;ab&quot;, e &quot;zab&quot;) de s em base.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Uma possível solução pode ser considerar alocar um array de tamanho 26 para cada caractere no alfabeto. (Créditos para @r2ysxu)"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "468",
    "paidOnly": false,
    "title": "Validate IP Address",
    "titleSlug": "validate-ip-address",
    "url": "https://leetcode.com/problems/validate-ip-address",
    "description_url": "https://leetcode.com/problems/validate-ip-address/description/",
    "description": "<p>Given a string <code>queryIP</code>, return <code>&quot;IPv4&quot;</code> if IP is a valid IPv4 address, <code>&quot;IPv6&quot;</code> if IP is a valid IPv6 address or <code>&quot;Neither&quot;</code> if IP is not a correct IP of any type.</p>\n\n<p><strong>A valid IPv4</strong> address is an IP in the form <code>&quot;x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>&quot;</code> where <code>0 &lt;= x<sub>i</sub> &lt;= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>&quot;192.168.1.1&quot;</code> and <code>&quot;192.168.1.0&quot;</code> are valid IPv4 addresses while <code>&quot;192.168.01.1&quot;</code>, <code>&quot;192.168.1.00&quot;</code>, and <code>&quot;192.168@1.1&quot;</code> are invalid IPv4 addresses.</p>\n\n<p><strong>A valid IPv6</strong> address is an IP in the form <code>&quot;x<sub>1</sub>:x<sub>2</sub>:x<sub>3</sub>:x<sub>4</sub>:x<sub>5</sub>:x<sub>6</sub>:x<sub>7</sub>:x<sub>8</sub>&quot;</code> where:</p>\n\n<ul>\n\t<li><code>1 &lt;= x<sub>i</sub>.length &lt;= 4</code></li>\n\t<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>&#39;a&#39;</code> to <code>&#39;f&#39;</code>) and upper-case English letters (<code>&#39;A&#39;</code> to <code>&#39;F&#39;</code>).</li>\n\t<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>\n</ul>\n\n<p>For example, &quot;<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;</code> and &quot;<code>2001:db8:85a3:0:0:8A2E:0370:7334&quot;</code> are valid IPv6 addresses, while &quot;<code>2001:0db8:85a3::8A2E:037j:7334&quot;</code> and &quot;<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;</code> are invalid IPv6 addresses.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> queryIP = &quot;172.16.254.1&quot;\n<strong>Output:</strong> &quot;IPv4&quot;\n<strong>Explanation:</strong> This is a valid IPv4 address, return &quot;IPv4&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> queryIP = &quot;2001:0db8:85a3:0:0:8A2E:0370:7334&quot;\n<strong>Output:</strong> &quot;IPv6&quot;\n<strong>Explanation:</strong> This is a valid IPv6 address, return &quot;IPv6&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> queryIP = &quot;256.256.256.256&quot;\n<strong>Output:</strong> &quot;Neither&quot;\n<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>queryIP</code> consists only of English letters, digits and the characters <code>&#39;.&#39;</code> and <code>&#39;:&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/validate-ip-address/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nThe first idea is to use try/catch construct with built-in \nfacilities: [ipaddress](https://docs.python.org/3/library/ipaddress.html) \nlib in Python and [InetAddress](https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html) \nclass in Java.\n\n**Note that the code below validates the _real-life_ IPv4, \nand _real-life_ IPv6. \nIt will not work for this problem because the problem validates \nnot _real-life_ but _\"simplified\"_ versions of IPv4 and IPv6.**\n\nSome big companies, for example, Microsoft and Amazon, \nredefine IPv4 and IPv6 on the interviews for the sake of simplicity.\nBelow one could find an extended discussion about the differences.\n\n<iframe src=\"https://leetcode.com/playground/Jq9A7FGf/shared\" frameBorder=\"0\" width=\"100%\" height=\"276\" name=\"Jq9A7FGf\"></iframe>\n\nNote that these facilities both refer to \n[POSIX-compatible](https://linux.die.net/man/3/inet_addr) \n`inet-addr()` routine for parsing addresses. \nThat's why they consider chunks with leading zeros\nnot as an error, but as an _octal_ representation.\n\n> Components of the dotted address can be specified in decimal, \n_octal (with a leading 0)_, or hexadecimal, with a leading 0X). \n\nAs a result, `01.01.01.012` will be a valid IP address in \noctal representation, as it should be. \nTo check this behaviour, one can run the command `ping 01.01.01.012` \nin the console. The address `01.01.01.012` will be considered \nas the one in octal representation, \nconverted into its decimal representation `1.1.1.10`,\ntherefore the ping command would be executed without errors.\n\nBy contrary, problem description directly states that \n_leading zeros in the IPv4 is invalid_.\nThat's not a real-life case, but probably done for the sake \nof simplicity.\nImho, that makes the problem to be a bit schoolish and less fun.\nThough let's deal with it anyway, since the problem is very popular recently \nin Microsoft and Amazon. \n\nThere are three main ways to solve it:\n \n- Regex (_i.e._ regular expression). Less performing one, though it's a good way to demonstrate \nyour knowledge of regex.\n\n- Divide and Conquer, the simplest one.\n\n- Mix of \"Divide and Conquer\" and \"Try/Catch with built-in facilities\", \nthis time with ones to convert string to integer. \nTry/catch in this situation is a sort of \"dirty\"\nsolution because [usually the code inside try blocks is not optimized as \nit'd otherwise be by the compiler](https://blogs.msmvps.com/peterritchie/2007/06/22/performance-implications-of-try-catch-finally/),\nand it's better not to use it during the interview.\n<br />\n<br />\n\n\n---\n### Approach 1: Regex\n\nLet's construct step by step regex for \"IPv4\" \nas it's described in the problem description. Note, that it's not\na real-life IPv4 because of leading zeros problem as we've discussed above. \n\nAnyway, we start to construct regex pattern by using raw string in Python \n`r''` and standard string `\"\"` in Java. Here is how its skeleton looks like for Python\n\n![diff](../Figures/468/regex_ipv4.png)\n\nand here is for Java\n\n![diff](../Figures/468/java_ipv4.png)\n\nNow the problem is reduced to the construction of pattern to match each chunk.\nIt's an integer in range (0, 255), and the leading zeros are not allowed.\nThat results in five possible situations:\n\n1. Chunk contains only one digit, from 0 to 9.\n\n2. Chunk contains two digits. The first one could be from 1 to 9, and the second \none from 0 to 9.\n\n3. Chunk contains three digits, and the first one is `1`. The second and the third ones \ncould be from 0 to 9.\n\n4. Chunk contains three digits, the first one is `2` and the second one is from 0 to 4.\nThen the third one could be from 0 to 9.\n\n5. Chunk contains three digits, the first one is `2`,  and the second one is `5`.\nThen the third one could be from 0 to 5.\n\nLet's use pipe to create a regular expression that will match either case 1, or \ncase 2, ..., or case 5. \n\n![diff](../Figures/468/chunk_regex.png) \n\nThe job is done. The same logic could be used to construct \"IPv6\" regex pattern.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/SuRTfqgi/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"SuRTfqgi\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$\\mathcal{O}(1)$$ because the patterns to match have \nconstant length.\n    \n* Space complexity: $$\\mathcal{O}(1)$$. \n<br />\n<br />\n\n\n---\n### Approach 2: Divide and Conquer\n\n**Intuition**\n\nBoth IPv4 and IPv6 addresses are composed of several substrings separated by certain delimiter,\nand each of the substrings is of the same format.\n\n![diff](../Figures/468/divide_conquer.png)\n\nTherefore, intuitively, we could break down the address into chunks, \nand then verify them one by one.\n\nThe address is valid _if and only if_ each of the chunks is valid.\nWe can call this methodology _divide and conquer_.\n\n**Algorithm**\n\n- For the IPv4 address, we split IP into four chunks by the delimiter `.`,\nwhile for IPv6 address, we split IP into eight chunks by the delimiter `:`.\n\n- For each substring of \"IPv4\" address, \nwe check if it is an integer between `0 - 255`, and there is no leading zeros.\n\n- For each substring of \"IPv6\" address, \nwe check if it's a hexadecimal number of length `1 - 4`.\n \n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/9PJVJNRm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"9PJVJNRm\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$\\mathcal{O}(N)$$ because to count number of dots requires to\nparse the entire input string.\n    \n* Space complexity: $$\\mathcal{O}(1)$$. \n<br />\n<br />",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String validIPAddress(String IP) {\n    if (IP.chars().filter(c -> c == '.').count() == 3) {\n      for (final String digit : IP.split(\"\\\\.\", -1))\n        if (!isIPv4(digit))\n          return \"Neither\";\n      return \"IPv4\";\n    }\n\n    if (IP.chars().filter(c -> c == ':').count() == 7) {\n      for (final String digit : IP.split(\"\\\\:\", -1))\n        if (!isIPv6(digit))\n          return \"Neither\";\n      return \"IPv6\";\n    }\n\n    return \"Neither\";\n  }\n\n  private static final String validIPv6Chars = \"0123456789abcdefABCDEF\";\n\n  private boolean isIPv4(final String digit) {\n    if (digit.isEmpty() || digit.length() > 3)\n      return false;\n    if (digit.length() > 1 && digit.charAt(0) == '0')\n      return false;\n\n    for (final char c : digit.toCharArray())\n      if (c < '0' || c > '9')\n        return false;\n\n    final int num = Integer.parseInt(digit);\n    return 0 <= num && num <= 255;\n  }\n\n  private boolean isIPv6(final String digit) {\n    if (digit.isEmpty() || digit.length() > 4)\n      return false;\n\n    for (final char c : digit.toCharArray())\n      if (!validIPv6Chars.contains(\"\" + c))\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string validIPAddress(string IP) {\n    string digit;\n    istringstream iss(IP);\n\n    if (count(begin(IP), end(IP), '.') == 3) {\n      for (int i = 0; i < 4; ++i)  // Make sure we have 4 parts\n        if (!getline(iss, digit, '.') || !isIPv4(digit))\n          return \"Neither\";\n      return \"IPv4\";\n    }\n\n    if (count(begin(IP), end(IP), ':') == 7) {\n      for (int i = 0; i < 8; ++i)  // Make sure we have 8 parts\n        if (!getline(iss, digit, ':') || !isIPv6(digit))\n          return \"Neither\";\n      return \"IPv6\";\n    }\n\n    return \"Neither\";\n  }\n\n private:\n  static inline string validIPv6Chars = \"0123456789abcdefABCDEF\";\n\n  bool isIPv4(const string& digit) {\n    if (digit.empty() || digit.length() > 3)\n      return false;\n    if (digit.length() > 1 && digit[0] == '0')\n      return false;\n\n    for (const char c : digit)\n      if (c < '0' || c > '9')\n        return false;\n\n    const int num = stoi(digit);\n    return 0 <= num && num <= 255;\n  }\n\n  bool isIPv6(const string& digit) {\n    if (digit.empty() || digit.length() > 4)\n      return false;\n\n    for (const char c : digit)\n      if (validIPv6Chars.find(c) == string::npos)\n        return false;\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/468.html",
    "category": "Algorithms",
    "acceptance_rate": 27.768897317800057,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 1075,
    "dislikes": 2731,
    "similar_questions": "[{\"title\": \"IP to CIDR\", \"titleSlug\": \"ip-to-cidr\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Strong Password Checker II\", \"titleSlug\": \"strong-password-checker-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"184.5K\", \"totalSubmission\": \"664.4K\", \"totalAcceptedRaw\": 184491, \"totalSubmissionRaw\": 664380, \"acRate\": \"27.8%\"}",
    "title_pt": "Validar Endereço IP",
    "description_pt": "<p>Dada uma string <code>queryIP</code>, retorne <code>&quot;IPv4&quot;</code> se o IP for um endereço IPv4 válido, <code>&quot;IPv6&quot;</code> se o IP for um endereço IPv6 válido ou <code>&quot;Neither&quot;</code> se o IP não for um IP correto de nenhum tipo.</p>\n\n<p><strong>Um IPv4 válido</strong> é um IP na forma <code>&quot;x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>&quot;</code> em que <code>0 &lt;= x<sub>i</sub> &lt;= 255</code> e <code>x<sub>i</sub></code> <strong>não pode conter</strong> zeros à esquerda. Por exemplo, <code>&quot;192.168.1.1&quot;</code> e <code>&quot;192.168.1.0&quot;</code> são endereços IPv4 válidos, enquanto <code>&quot;192.168.01.1&quot;</code>, <code>&quot;192.168.1.00&quot;</code> e <code>&quot;192.168@1.1&quot;</code> são endereços IPv4 inválidos.</p>\n\n<p><strong>Um IPv6 válido</strong> é um IP na forma <code>&quot;x<sub>1</sub>:x<sub>2</sub>:x<sub>3</sub>:x<sub>4</sub>:x<sub>5</sub>:x<sub>6</sub>:x<sub>7</sub>:x<sub>8</sub>&quot;</code> em que:</p>\n\n<ul>\n\t<li><code>1 &lt;= x<sub>i</sub>.length &lt;= 4</code></li>\n\t<li><code>x<sub>i</sub></code> é uma <strong>string hexadecimal</strong> que pode conter dígitos, letras inglesas minúsculas (<code>&#39;a&#39;</code> a <code>&#39;f&#39;</code>) e letras inglesas maiúsculas (<code>&#39;A&#39;</code> a <code>&#39;F&#39;</code>).</li>\n\t<li>Zeros à esquerda são permitidos em <code>x<sub>i</sub></code>.</li>\n</ul>\n\n<p>Por exemplo, <code>&quot;2001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;</code> e <code>&quot;2001:db8:85a3:0:0:8A2E:0370:7334&quot;</code> são endereços IPv6 válidos, enquanto <code>&quot;2001:0db8:85a3::8A2E:037j:7334&quot;</code> e <code>&quot;02001:0db8:85a3:0000:0000:8a2e:0370:7334&quot;</code> são endereços IPv6 inválidos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> queryIP = &quot;172.16.254.1&quot;\n<strong>Saída:</strong> &quot;IPv4&quot;\n<strong>Explicação:</strong> Este é um endereço IPv4 válido; retorne &quot;IPv4&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> queryIP = &quot;2001:0db8:85a3:0:0:8A2E:0370:7334&quot;\n<strong>Saída:</strong> &quot;IPv6&quot;\n<strong>Explicação:</strong> Este é um endereço IPv6 válido; retorne &quot;IPv6&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> queryIP = &quot;256.256.256.256&quot;\n<strong>Saída:</strong> &quot;Neither&quot;\n<strong>Explicação:</strong> Este não é nem um endereço IPv4 nem um endereço IPv6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>queryIP</code> consiste apenas de letras inglesas, dígitos e dos caracteres <code>&#39;.&#39;</code> e <code>&#39;:&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "470",
    "paidOnly": false,
    "title": "Implement Rand10() Using Rand7()",
    "titleSlug": "implement-rand10-using-rand7",
    "url": "https://leetcode.com/problems/implement-rand10-using-rand7",
    "description_url": "https://leetcode.com/problems/implement-rand10-using-rand7/description/",
    "description": "<p>Given the <strong>API</strong> <code>rand7()</code> that generates a uniform random integer in the range <code>[1, 7]</code>, write a function <code>rand10()</code> that generates a uniform random integer in the range <code>[1, 10]</code>. You can only call the API <code>rand7()</code>, and you shouldn&#39;t call any other API. Please <strong>do not</strong> use a language&#39;s built-in random API.</p>\n\n<p>Each test case will have one <strong>internal</strong> argument <code>n</code>, the number of times that your implemented function <code>rand10()</code> will be called while testing. Note that this is <strong>not an argument</strong> passed to <code>rand10()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 1\n<strong>Output:</strong> [2]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 2\n<strong>Output:</strong> [2,8]\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> n = 3\n<strong>Output:</strong> [3,8,10]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>What is the <a href=\"https://en.wikipedia.org/wiki/Expected_value\" target=\"_blank\">expected value</a> for the number of calls to <code>rand7()</code> function?</li>\n\t<li>Could you minimize the number of calls to <code>rand7()</code>?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/implement-rand10-using-rand7/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\n/**\n * The rand7() API is already defined in the parent class SolBase.\n * public int rand7();\n * @return a random integer in the range 1 to 7\n */\n\nclass Solution extends SolBase {\n  public int rand10() {\n    int num = 40;\n\n    while (num >= 40)\n      num = (rand7() - 1) * 7 + rand7() - 1;\n\n    return num % 10 + 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\n// The rand7() API is already defined for you.\n// int rand7();\n// @return a random integer in the range 1 to 7\n\nclass Solution {\n public:\n  int rand10() {\n    int num = 40;\n\n    while (num >= 40)\n      num = (rand7() - 1) * 7 + rand7() - 1;\n\n    return num % 10 + 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/470.html",
    "category": "Algorithms",
    "acceptance_rate": 45.84301661078939,
    "topics": [
      "Math",
      "Rejection Sampling",
      "Randomized",
      "Probability and Statistics"
    ],
    "hints": [],
    "likes": 1137,
    "dislikes": 388,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"96.3K\", \"totalSubmission\": \"210K\", \"totalAcceptedRaw\": 96263, \"totalSubmissionRaw\": 209984, \"acRate\": \"45.8%\"}",
    "title_pt": "Implementar Rand10() Usando Rand7()",
    "description_pt": "<p>Dada a <strong>API</strong> <code>rand7()</code> que gera um inteiro aleatório uniforme no intervalo <code>[1, 7]</code>, escreva uma função <code>rand10()</code> que gera um inteiro aleatório uniforme no intervalo <code>[1, 10]</code>. Você só pode chamar a API <code>rand7()</code> e não deve chamar nenhuma outra API. Por favor, <strong>não</strong> use a API de aleatoriedade embutida da linguagem.</p>\n\n<p>Cada caso de teste terá um argumento <strong>interno</strong> <code>n</code>, o número de vezes que sua função implementada <code>rand10()</code> será chamada durante a avaliação. Observe que este <strong>não é um argumento</strong> passado para <code>rand10()</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> [2]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> [2,8]\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> [3,8,10]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Qual é o <a href=\"https://en.wikipedia.org/wiki/Expected_value\" target=\"_blank\">valor esperado</a> para o número de chamadas da função <code>rand7()</code>?</li>\n\t<li>Você conseguiria minimizar o número de chamadas de <code>rand7()</code>?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "472",
    "paidOnly": false,
    "title": "Concatenated Words",
    "titleSlug": "concatenated-words",
    "url": "https://leetcode.com/problems/concatenated-words",
    "description_url": "https://leetcode.com/problems/concatenated-words/description/",
    "description": "<p>Given an array of strings <code>words</code> (<strong>without duplicates</strong>), return <em>all the <strong>concatenated words</strong> in the given list of</em> <code>words</code>.</p>\n\n<p>A <strong>concatenated word</strong> is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct)&nbsp;in the given array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;cat&quot;,&quot;cats&quot;,&quot;catsdogcats&quot;,&quot;dog&quot;,&quot;dogcatsdog&quot;,&quot;hippopotamuses&quot;,&quot;rat&quot;,&quot;ratcatdogcat&quot;]\n<strong>Output:</strong> [&quot;catsdogcats&quot;,&quot;dogcatsdog&quot;,&quot;ratcatdogcat&quot;]\n<strong>Explanation:</strong> &quot;catsdogcats&quot; can be concatenated by &quot;cats&quot;, &quot;dog&quot; and &quot;cats&quot;; \n&quot;dogcatsdog&quot; can be concatenated by &quot;dog&quot;, &quot;cats&quot; and &quot;dog&quot;; \n&quot;ratcatdogcat&quot; can be concatenated by &quot;rat&quot;, &quot;cat&quot;, &quot;dog&quot; and &quot;cat&quot;.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;cat&quot;,&quot;dog&quot;,&quot;catdog&quot;]\n<strong>Output:</strong> [&quot;catdog&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>words[i]</code> consists of only lowercase English letters.</li>\n\t<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>\n\t<li><code>1 &lt;= sum(words[i].length) &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/concatenated-words/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\nThe main logic of the solutions is similar to the question [Word Break](https://leetcode.com/problems/word-break/).\n### Approach 1: Dynamic Programming\n\n#### Intuition\n\nConsider the word list as a dictionary, then the problem is: which words can be created by concatenating two or more words in the dictionary?\n\nThis is a famous \"reachability\" problem and it can be solved by DP(dynamic programming), BFS and/or DFS. Though they seem to be different, the core idea behind them is the same. Namely, if a given `word` can be created by concatenating the given words, we can split it into 2 parts, the prefix and the suffix, the prefix is a shorter word which can be got by concatenating the given words and the suffix is a given word. \n\nNamely, `word` = (another shorter word that can be created by concatenation) + (a given word in the dictionary). We can enumerate the suffix and look it up in the dictionary and the prefix part is just a sub-problem to solve.\n\n#### Algorithm\n\n##### State definition\nFormally, for each word, let's define the sub-problem as whether a (possibly empty) prefix can be created by concatenation. So the state of the dynamic programming algorithm can be defined as a boolean array:\nlet $dp[i]$ denote whether word's prefix of length i (index range [0, i - 1]) can be created by concatenation.\n\n##### Induction\nWe need to calculate $dp[i]$ for each i in range [0, word.length]. Let's do it by induction.\n\nThe base case is simple: $dp[0]$ = true, since it's the empty string that can always be created without using any words in the dictionary. \n\nNow, let's consider the value of $dp[i]$ for i > 0. \n\nIf $dp[i]$ is true, as mentioned before, we can split this prefix into 2 parts, a prefix of length j < i which can be created by the words in the dictionary, and the remaining suffix which is exactly a single word in the dictionary.\n\n$dp[i]$ is true if and only if there is an integer j, such that 0 <= j < i and the word's substring (index range [j, i - 1]) is in the dictionary.\n\n**Note: There is an corner case, when i == length, since we don't want to use the word in the dictionary directly, we should check 1 <= j < i instead.**\n\n#### The answer\n$dp[word.length]$ tells if the word can be created by concatenation.\n\nHere is how the algorithm works with \"catsdogcats\" if we have \"cats\" and \"dog\" in the dictionary.\n\n<center>\n<img src=\"../Figures/472/472_Concatenated_Words.png\" width=\"500\"/>\n</center>\n<br>\n\nFor instance, $dp[7]$ tells if we can create \"catsdogs\" (the first 7 letters). It's true because we can split it into a prefix \"cats\" which we know we can create because $dp[4]$ is true, and a suffix \"dogs\", which is in dictionary.\n\n#### Steps\n1. Put all the words into a HashSet as a `dictionary`. \n2. Create an empty list `answer`.\n3. For each `word` in the `words` create a boolean array `dp` of length = `word.length + 1`, and set dp[0] = true.\n4. For each index `i` from 1 to `word.length`, set `dp[i]` to true if we can find a value `j` from 0 (1 if i == `word.length`) such that dp[j] = true and `word.substring(j, i)` is in the `dictionary`.\n5. Put `word` into `answer` if dp[word.length] = true.\n6. After processing all the `words`, return `answer`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/HGHNkVYa/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"HGHNkVYa\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the total number of strings in the array `words`, namely `words.length`, and $M$ is the length of the longest string in the array `words`.\n\n* Time complexity: $O(M ^ 3 \\cdot N)$.\n\nAlthough we use HashSet, we need to consider the cost to calculate the hash value of a string internally which would be $O(M)$. So putting all words into the HashSet takes $O(N * M)$.\nFor each word, the i and j loops take $O(M ^ 2)$. The internal logic to take the substring and search in the HashSet needs to calculate the hash value for the substring too, and it should take another $O(M)$, so for each word, the time complexity is $O(M^3)$ and the total time complexity for $N$ words is $O(M ^ 3 \\cdot N)$\n\n\n\n* Space complexity: $O(N \\cdot M)$.\n\n  This is just the space to save all words in the `dictionary`, if we don't take $M$ as a constant.\n\n\n### Approach 2: DFS\n\n#### Intuition\n\nAs mentioned before, this problem can be transformed into a reachability problem and thus can be solved by a DFS (or BFS) algorithm. For each word, we construct a directed graph with all prefixes as nodes. For simplicity, we can represent each prefix by its length. \n\nSo the graph contains (word.length + 1) nodes. \nFor edges, consider 2 prefixes i and j with 0 <= i < j <= word.length, if prefix j can be created by concatenating prefix i and a word in the dictionary, we add a directed edge from node i to node j. \n> When i = 0, we require `j < word.length` as there should be an edge from node `0` to node `word.length`.\nDetermining whether a word can be created by concatenating 2 or more words in the dictionary is the same as determining whether there is a path from node `0` to node `word.length` in the graph.\n\n#### Algorithm\n\nFor each word, construct the implicit graph mentioned above, then add it to the answer if the node `word.length` can be reached from node `0` in the graph which can be checked using DFS.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/E6gRtdWh/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"E6gRtdWh\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the total number of strings in the array `words`, namely `words.length`, and $M$ is the length of the longest string in the array `words`.\n\n* Time complexity: $O(M ^ 3 \\cdot N)$.\n\nFor each word, the constructed graph has $M$ nodes and $O(M ^ 2)$ edges, and the DFS algorithm for reachability is $O(M ^ 2)$ without considering the time complexities of substring and HashSet. If we consider everything, the time complexity to check one word is $O(M ^ 3)$ and the total time complexity to check all words is $O(M ^ 3 \\cdot N)$.\n\n\n\n* Space complexity: $O(N \\cdot M)$.\n\n  This is the space to save all words in the `dictionary`, if we don't take $M$ as a constant, there is also $O(M)$ for the call stack to execute DFS, which wouldn't affect the space complexity anyways.\n\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n    wordSet = set(words)\n\n    @functools.lru_cache(None)\n    def isConcat(word: str) -> bool:\n      for i in range(1, len(word)):\n        prefix = word[:i]\n        suffix = word[i:]\n        if prefix in wordSet and (suffix in wordSet or isConcat(suffix)):\n          return True\n\n      return False\n\n    return [word for word in words if isConcat(word)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> findAllConcatenatedWordsInADict(String[] words) {\n    List<String> ans = new ArrayList<>();\n    Set<String> wordSet = new HashSet<>(Arrays.asList(words));\n    Map<String, Boolean> memo = new HashMap<>();\n\n    for (final String word : words)\n      if (wordBreak(word, wordSet, memo))\n        ans.add(word);\n\n    return ans;\n  }\n\n  private boolean wordBreak(final String word, Set<String> wordSet, Map<String, Boolean> memo) {\n    if (memo.containsKey(word))\n      return memo.get(word);\n\n    for (int i = 1; i < word.length(); ++i) {\n      final String prefix = word.substring(0, i);\n      final String suffix = word.substring(i);\n      if (wordSet.contains(prefix) &&\n          (wordSet.contains(suffix) || wordBreak(suffix, wordSet, memo))) {\n        memo.put(word, true);\n        return true;\n      }\n    }\n\n    memo.put(word, false);\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {\n    vector<string> ans;\n    unordered_set<string> wordSet{begin(words), end(words)};\n    unordered_map<string, bool> memo;\n\n    for (const string& word : words)\n      if (isConcat(word, wordSet, memo))\n        ans.push_back(word);\n\n    return ans;\n  }\n\n private:\n  bool isConcat(const string& s, const unordered_set<string>& wordSet,\n                unordered_map<string, bool>& memo) {\n    if (memo.count(s))\n      return memo[s];\n\n    for (int i = 1; i < s.length(); ++i) {\n      const string prefix = s.substr(0, i);\n      const string suffix = s.substr(i);\n      if (wordSet.count(prefix) &&\n          (wordSet.count(suffix) || isConcat(suffix, wordSet, memo)))\n        return memo[s] = true;\n    }\n\n    return memo[s] = false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/472.html",
    "category": "Algorithms",
    "acceptance_rate": 49.40621281956428,
    "topics": [
      "Array",
      "String",
      "Dynamic Programming",
      "Depth-First Search",
      "Trie"
    ],
    "hints": [],
    "likes": 3969,
    "dislikes": 285,
    "similar_questions": "[{\"title\": \"Word Break II\", \"titleSlug\": \"word-break-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"247.1K\", \"totalSubmission\": \"500.1K\", \"totalAcceptedRaw\": 247077, \"totalSubmissionRaw\": 500094, \"acRate\": \"49.4%\"}",
    "title_pt": "Palavras Concatenadas",
    "description_pt": "<p>Dado um array de strings <code>words</code> (<strong>sem duplicatas</strong>), retorne <em>todas as <strong>palavras concatenadas</strong> na lista dada de</em> <code>words</code>.</p>\n\n<p>Uma <strong>palavra concatenada</strong> é definida como uma string que é composta inteiramente por pelo menos duas palavras mais curtas (não necessariamente distintas)&nbsp;no array dado.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;cat&quot;,&quot;cats&quot;,&quot;catsdogcats&quot;,&quot;dog&quot;,&quot;dogcatsdog&quot;,&quot;hippopotamuses&quot;,&quot;rat&quot;,&quot;ratcatdogcat&quot;]\n<strong>Saída:</strong> [&quot;catsdogcats&quot;,&quot;dogcatsdog&quot;,&quot;ratcatdogcat&quot;]\n<strong>Explicação:</strong> &quot;catsdogcats&quot; pode ser concatenada por &quot;cats&quot;, &quot;dog&quot; e &quot;cats&quot;; \n&quot;dogcatsdog&quot; pode ser concatenada por &quot;dog&quot;, &quot;cats&quot; e &quot;dog&quot;; \n&quot;ratcatdogcat&quot; pode ser concatenada por &quot;rat&quot;, &quot;cat&quot;, &quot;dog&quot; e &quot;cat&quot;.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;cat&quot;,&quot;dog&quot;,&quot;catdog&quot;]\n<strong>Saída:</strong> [&quot;catdog&quot;]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>words[i]</code> consiste apenas de letras minúsculas do inglês.</li>\n\t<li>Todas as strings de <code>words</code> são <strong>únicas</strong>.</li>\n\t<li><code>1 &lt;= sum(words[i].length) &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "473",
    "paidOnly": false,
    "title": "Matchsticks to Square",
    "titleSlug": "matchsticks-to-square",
    "url": "https://leetcode.com/problems/matchsticks-to-square",
    "description_url": "https://leetcode.com/problems/matchsticks-to-square/description/",
    "description": "<p>You are given an integer array <code>matchsticks</code> where <code>matchsticks[i]</code> is the length of the <code>i<sup>th</sup></code> matchstick. You want to use <strong>all the matchsticks</strong> to make one square. You <strong>should not break</strong> any stick, but you can link them up, and each matchstick must be used <strong>exactly one time</strong>.</p>\n\n<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> matchsticks = [1,1,2,2,2]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> matchsticks = [3,3,3,3,4]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= matchsticks.length &lt;= 15</code></li>\n\t<li><code>1 &lt;= matchsticks[i] &lt;= 10<sup>8</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/matchsticks-to-square/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nSuppose we have `1,1,1,1,2,2,2,2,3,3,3,3` as our set of matchsticks. In this case a square of side $$6$$ can be formed and we have 4 matchsticks each of 1, 2 and 3 and so we can have each square side formed by `3 + 2 + 1 = 6`.\n\n<center>\n<img src=\"../Figures/473/473_Matchsticks-In-Square-Diag-1.png\" height=\"400\"></center>\n\nWe can clearly see in the diagram above that the 3 matchsticks of sizes `1`, `2` and `3` combine to give one side of our resulting square.\n\nThis problem boils down to splitting an array of integers into $$4$$ subsets where all of these subsets are:\n* mutually exclusive i.e. no specific element of the array is shared by any two of these subsets, and\n* have the same sum which is equal to the side of our square.\n\nWe know that we will have $$4$$ different subsets. The sum of elements of these subsets would be $$\\frac{1}{4}\\sum_{}^{} arr$$. If the sum if not divisible by $$4$$, that implies that $$4$$ subsets of equal value are not possible and we don't need to do any further processing on this.\n\nThe only question that remains now for us to solve is:\n> what subset a particular element belongs to?\n\nIf we are able to figure that out, then there's nothing else left to do. But, since we can't say which of the $$4$$ subsets would contain a particular element, we try out all the options.\n\n---\n\n### Approach 1: Depth First Search\n\n#### Intuition\n\nIt is possible that a matchstick ***can*** be a part of any of the 4 sides of the resulting square, but which one of these choices leads to an actual square is something we don't know.\n\nThis means that for every matchstick in our given array, we have $$4$$ different options each representing the side of the square or subset that this matchstick can be a part of.\n\nWe try out all of them and keep on doing this recursively until we exhaust all of the possibilities or until we find an arrangement of our matchsticks such that they form the square.\n\n#### Algorithm\n\n1. As discussed previously, we will follow a recursive, depth first approach to solve this problem. So, we have a function that takes the current matchstick index we are to process and also the number of sides of the square that are completely formed till now.\n\n2. If all of the matchsticks have been used up and 4 sides have been completely formed, that implies our square is completely formed. This is the base case for the recursion.\n\n3. For the current matchstick we have 4 different options. This matchstick at $$index$$ can be a part of any of the sides of the square. We try out the 4 options by recursing on them.\n    - If any of these recursive calls returns $$True$$, then we return from there, else we return $$False$$\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/LGi7CtY9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"LGi7CtY9\"></iframe>\n\nThis solution is very slow as is. However, we can speed it up considerably by a small trick and that is to `sort our matchsticks sizes in reverse order before processing them recursively`.\n\nThe reason for this is that if there is no solution, trying a longer matchstick first will get to negative conclusion earlier.\n\ne.g. $$[8,4,4,4]$$. In this case we can have a square of size 5 but the largest side 8 doesn't fit in anywhere i.e. cannot be a part of any of the sides (because we can't break matchsticks according to the question) and hence we can simply return $$False$$ without even considering the remaining matchsticks.\n\n#### Complexity Analysis\n\n* Time Complexity: $$O(4^N)$$ because we have a total of $$N$$ sticks and for each one of those matchsticks, we have $$4$$ different possibilities for the subsets they might belong to or the side of the square they might be a part of.\n\n* Space Complexity: $$O(N)$$. For recursive solutions, the space complexity is the stack space occupied by all the recursive calls. The deepest recursive call here would be of size $$N$$ and hence the space complexity is $$O(N)$$. There is no additional space other than the recursion stack in this solution.\n\n---\n\n### Approach 2: Dynamic Programming\n\n#### Intuition\n\nIn any dynamic programming problem, what's important is that our problem must be breakable into smaller subproblems and also, these subproblems show some sort of overlap which we can save upon by caching or memoization.\n\nSuppose we have `3,3,4,4,5,5` as our matchsticks that have been used already to construct some of the sides of our square (**Note:** not all the sides may be completely constructed at all times.)\n\nIf the square side is $$8$$, then there are many possibilities for how the sides can be constructed using the matchsticks above. We can have\n\n<pre>\n  (4, 4), (3, 5), (3, 5) -----------> 3 sides fully constructed.\n  (3, 4), (3, 5), (4), (5) ---------> 0 sides completely constructed.\n  (3, 3), (4, 4), (5), (5) ---------> 1 side completely constructed.\n</pre>\n\nAs we can see above, there are multiple ways to use the same set of matchsticks and land up in completely different recursion states.\n\nThis means that if we just keep track of what all matchsticks have been used and which all are remaining, it won't properly define the state of recursion we are in or what subproblem we are solving.\n\nA single set of used matchsticks can represent multiple different unrelated subproblems and that is just not right.\n\nWe also need to keep track of number of sides of the square that have been **completely** formed till now.\n\nAlso, an important thing to note in the example we just considered was that if the matchsticks being used are $$[3,3,4,4,5,5]$$ and the side of the square is `8`, then we will always consider that arrangement that forms the most number of complete sides over that arrangement that leads to incomplete sides. Hence, the optimal arrangement here is $$(4, 4), (3, 5), (3, 5)$$ with 3 complete sides of the square.\n\nLet us take a look at the following recursion tree to see if in-fact we can get overlapping subproblems.\n\n<center>\n<img src=\"../Figures/473/473_Matchsticks-In-Square-Diag-2.png\" width=\"500\"></center>\n\n**Note:** Not all subproblems have been shown in this figure. The thing we wanted to point out was overlapping subproblems.\n\nWe know that the overall sum of these matchsticks can be split equally into 4 halves. The only thing we don't know is if 4 **equal** halves can be carved out of the given set of matchsticks. For that also we need to keep track of the number of sides completely formed at any point in time. ***If we end up forming 4 equal sides successfully then naturally we would have used up all of the matchsticks each being used exactly once and we would have formed a square***.\n\n#### Algorithm\n\nLet us first look at the pseudo-code for this problem before looking at the exact implementation details for the same.\n\n<pre>\nlet square_side = sum(matchsticks) / 4\nfunc recurse(matchsticks_used, sides_formed) {\n    if sides_formed == 4, then {\n        Square Formed!!\n    }\n    for match in matchsticks available, do {\n          add match to matchsticks_used\n          let result = recurse(matchsticks_used, sides_formed)\n          if result == True, then {\n              return True\n          }\n          remove match from matchsticks_used\n    }\n    return False\n}\n</pre>\n\nThis is the overall structure of our dynamic programming solution. Of course, a lot of implementation details are missing here that we will address now.\n\n<br />\n\nIt is very clear from the pseudo-code above that the state of a recursion is defined by two variables `matchsticks_used` and `sides_formed`. Hence, these are the two variables that will be used to **memoize** or cache the results for that specific subproblem.\n\nThe question however is how do we actually store all the matchsticks that have been used? We want a memory efficient solution for this.\n\nIf we look at the question's constraints, we find that the max number of matchsticks we can have are $$15$$. That's a pretty small number and we can make use of this constraint.\n\nAll we need to store is which of the matchsticks from the original list have been used. `We can use a Bit-Map for this`\n\nWe will use $$N$$ number of bits, one for each of the matchsticks ($$N$$ is at max 15 according to the question's constraints). Initially we will start with a bit mask of `all 1s` and then as we keep on using the matchsticks, we will keep on setting their corresponding bits to `0`.\n\nThis way, we just have to hash an integer value which represents our bit-map and the max value for this mask would be $$2^{15}$$.\n\n<br />\n\n**Do we really need to see if all 4 sides have been completely formed ?**\n\nAnother implementation trick that helps optimize this solution is that we don't really need to see if 4 sides have been completely formed.\n\nThis is because, we already know that the sum of all the matchsticks is divisible by 4. So, *if 3 equal sides have been formed by using some of the matchsticks, then the remaining matchsticks would definitely form the remaining side of our square.*\n\nHence, we only need to check if 3 sides of our square can be formed or not.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/kKkAjm9e/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"kKkAjm9e\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$O(N \\times 2^N)$$. At max $$2^N$$ unique bit masks are possible and during every recursive call, we iterate our original matchsticks array to sum up the values of matchsticks used to update the `sides_formed` variable.\n\n* Space Complexity: $$O(N + 2^N)$$ because $$N$$ is the stack space taken up by recursion and $$4 \\times 2^N$$ = $$O(2^N)$$ is the max possible size of our cache for memoization.\n    - The size of the cache is defined by the two variables `sides_formed` and `mask`. The number of different values that `sides_formed` can take = 4 and number of unique values of `mask` = $$2^N$$.\n\n  <br />\n  <br />",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def makesquare(self, matchsticks: List[int]) -> bool:\n    if len(matchsticks) < 4:\n      return False\n\n    perimeter = sum(matchsticks)\n    if perimeter % 4 != 0:\n      return False\n\n    A = sorted(matchsticks)[::-1]\n\n    def dfs(selected: int, edges: List[int]) -> bool:\n      if selected == len(A):\n        return all(edge == edges[0] for edge in edges)\n\n      for i, edge in enumerate(edges):\n        if A[selected] > edge:\n          continue\n        edges[i] -= A[selected]\n        if dfs(selected + 1, edges):\n          return True\n        edges[i] += A[selected]\n\n      return False\n\n    return dfs(0, [perimeter // 4] * 4)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean makesquare(int[] matchsticks) {\n    if (matchsticks.length < 4)\n      return false;\n\n    final int perimeter = Arrays.stream(matchsticks).sum();\n    if (perimeter % 4 != 0)\n      return false;\n\n    int[] edges = new int[4];\n    Arrays.fill(edges, perimeter / 4);\n    Arrays.sort(edges); // can't do \"Arrays.sort(edges, (a, b) -> b - a);\" in Java\n    return dfs(matchsticks, matchsticks.length - 1, edges);\n  }\n\n  private boolean dfs(int[] matchsticks, int selected, int[] edges) {\n    if (selected == -1)\n      return Arrays.stream(edges).allMatch(edge -> edge == 0);\n\n    for (int i = 0; i < 4; ++i) {\n      if (matchsticks[selected] > edges[i])\n        continue;\n      edges[i] -= matchsticks[selected];\n      if (dfs(matchsticks, selected - 1, edges))\n        return true;\n      edges[i] += matchsticks[selected];\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool makesquare(vector<int>& matchsticks) {\n    if (matchsticks.size() < 4)\n      return false;\n\n    const int perimeter = accumulate(begin(matchsticks), end(matchsticks), 0);\n    if (perimeter % 4 != 0)\n      return false;\n\n    sort(begin(matchsticks), end(matchsticks), greater<int>());\n    return dfs(matchsticks, 0, vector<int>(4, perimeter / 4));\n  }\n\n private:\n  bool dfs(const vector<int>& matchsticks, int selected, vector<int>&& edges) {\n    if (selected == matchsticks.size())\n      return all_of(begin(edges), end(edges),\n                    [](int edge) { return edge == 0; });\n\n    for (int i = 0; i < 4; ++i) {\n      if (matchsticks[selected] > edges[i])\n        continue;\n      edges[i] -= matchsticks[selected];\n      if (dfs(matchsticks, selected + 1, move(edges)))\n        return true;\n      edges[i] += matchsticks[selected];\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/473.html",
    "category": "Algorithms",
    "acceptance_rate": 40.83134464355447,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Backtracking",
      "Bit Manipulation",
      "Bitmask"
    ],
    "hints": [
      "Treat the matchsticks as an array. Can we split the array into 4 equal parts?",
      "Every matchstick can belong to either of the 4 sides. We don't know which one. Maybe try out all options!",
      "For every matchstick, we have to try out each of the 4 options i.e. which side it can belong to. We can make use of recursion for this.",
      "We don't really need to keep track of which matchsticks belong to a particular side during recursion. We just need to keep track of the <b>length</b> of each of the 4 sides.",
      "When all matchsticks have been used we simply need to see the length of all 4 sides. If they're equal, we have a square on our hands!"
    ],
    "likes": 3918,
    "dislikes": 310,
    "similar_questions": "[{\"title\": \"Maximum Rows Covered by Columns\", \"titleSlug\": \"maximum-rows-covered-by-columns\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"188.2K\", \"totalSubmission\": \"460.9K\", \"totalAcceptedRaw\": 188208, \"totalSubmissionRaw\": 460940, \"acRate\": \"40.8%\"}",
    "title_pt": "Palitos de Fósforo para Quadrado",
    "description_pt": "<p>Você recebe um array de inteiros <code>matchsticks</code>, em que <code>matchsticks[i]</code> é o comprimento do <code>i<sup>th</sup></code> palito de fósforo. Você quer usar <strong>todos os palitos de fósforo</strong> para fazer um quadrado. Você <strong>não deve quebrar</strong> nenhum palito, mas pode conectá-los, e cada palito de fósforo deve ser usado <strong>exatamente uma vez</strong>.</p>\n\n<p>Retorne <code>true</code> se você puder fazer esse quadrado e <code>false</code> caso contrário.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/09/matchsticks1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> matchsticks = [1,1,2,2,2]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Você pode formar um quadrado com comprimento 2, um lado do quadrado foi formado por dois palitos com comprimento 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> matchsticks = [3,3,3,3,4]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Você não consegue encontrar uma maneira de formar um quadrado com todos os palitos de fósforo.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= matchsticks.length &lt;= 15</code></li>\n\t<li><code>1 &lt;= matchsticks[i] &lt;= 10<sup>8</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Trate os palitos de fósforo como um array. Podemos dividir o array em 4 partes iguais?",
      "Dica 2: Cada palito de fósforo pode pertencer a qualquer um dos 4 lados. Não sabemos qual. Talvez tente todas as opções!",
      "Dica 3: Para cada palito de fósforo, temos que tentar cada uma das 4 opções, isto é, a qual lado ele pode pertencer. Podemos usar recursão para isso.",
      "Dica 4: Na verdade, não precisamos acompanhar quais palitos de fósforo pertencem a um lado específico durante a recursão. Só precisamos acompanhar o <b>comprimento</b> de cada um dos 4 lados.",
      "Dica 5: Quando todos os palitos de fósforo tiverem sido usados, basta verificar o comprimento de todos os 4 lados. Se forem iguais, então temos um quadrado!"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "474",
    "paidOnly": false,
    "title": "Ones and Zeroes",
    "titleSlug": "ones-and-zeroes",
    "url": "https://leetcode.com/problems/ones-and-zeroes",
    "description_url": "https://leetcode.com/problems/ones-and-zeroes/description/",
    "description": "<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>\n\n<p>Return <em>the size of the largest subset of <code>strs</code> such that there are <strong>at most</strong> </em><code>m</code><em> </em><code>0</code><em>&#39;s and </em><code>n</code><em> </em><code>1</code><em>&#39;s in the subset</em>.</p>\n\n<p>A set <code>x</code> is a <strong>subset</strong> of a set <code>y</code> if all elements of <code>x</code> are also elements of <code>y</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> strs = [&quot;10&quot;,&quot;0001&quot;,&quot;111001&quot;,&quot;1&quot;,&quot;0&quot;], m = 5, n = 3\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The largest subset with at most 5 0&#39;s and 3 1&#39;s is {&quot;10&quot;, &quot;0001&quot;, &quot;1&quot;, &quot;0&quot;}, so the answer is 4.\nOther valid but smaller subsets include {&quot;0001&quot;, &quot;1&quot;} and {&quot;10&quot;, &quot;1&quot;, &quot;0&quot;}.\n{&quot;111001&quot;} is an invalid subset because it contains 4 1&#39;s, greater than the maximum of 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> strs = [&quot;10&quot;,&quot;0&quot;,&quot;1&quot;], m = 1, n = 1\n<strong>Output:</strong> 2\n<b>Explanation:</b> The largest subset is {&quot;0&quot;, &quot;1&quot;}, so the answer is 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 600</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consists only of digits <code>&#39;0&#39;</code> and <code>&#39;1&#39;</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/ones-and-zeroes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n    # dp[i][j] := max size of the subset given i 0's and j 1's are available\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n    for s in strs:\n      count0 = s.count('0')\n      count1 = len(s) - count0\n      for i in range(m, count0 - 1, -1):\n        for j in range(n, count1 - 1, -1):\n          dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1)\n\n    return dp[m][n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMaxForm(String[] strs, int m, int n) {\n    // dp[i][j] := max size of the subset given i 0's and j 1's are available\n    int[][] dp = new int[m + 1][n + 1];\n\n    for (final String s : strs) {\n      final int count0 = (int) s.chars().filter(c -> c == '0').count();\n      final int count1 = (int) s.length() - count0;\n      for (int i = m; i >= count0; --i)\n        for (int j = n; j >= count1; --j)\n          dp[i][j] = Math.max(dp[i][j], dp[i - count0][j - count1] + 1);\n    }\n\n    return dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMaxForm(vector<string>& strs, int m, int n) {\n    // dp[i][j] := max size of the subset given i 0's and j 1's are available\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n    for (const string& s : strs) {\n      const int count0 = count(begin(s), end(s), '0');\n      const int count1 = s.length() - count0;\n      for (int i = m; i >= count0; --i)\n        for (int j = n; j >= count1; --j)\n          dp[i][j] = max(dp[i][j], dp[i - count0][j - count1] + 1);\n    }\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/474.html",
    "category": "Algorithms",
    "acceptance_rate": 48.720462709685926,
    "topics": [
      "Array",
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 5574,
    "dislikes": 474,
    "similar_questions": "[{\"title\": \"Count Subarrays With More Ones Than Zeros\", \"titleSlug\": \"count-subarrays-with-more-ones-than-zeros\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Non-negative Integers without Consecutive Ones\", \"titleSlug\": \"non-negative-integers-without-consecutive-ones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"All Divisions With the Highest Score of a Binary Array\", \"titleSlug\": \"all-divisions-with-the-highest-score-of-a-binary-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"236.5K\", \"totalSubmission\": \"485.5K\", \"totalAcceptedRaw\": 236532, \"totalSubmissionRaw\": 485488, \"acRate\": \"48.7%\"}",
    "title_pt": "Uns e Zeros",
    "description_pt": "<p>Você recebe um array de strings binárias <code>strs</code> e dois inteiros <code>m</code> e <code>n</code>.</p>\n\n<p>Retorne <em>o tamanho do maior subconjunto de <code>strs</code> tal que haja <strong>no máximo</strong> </em><code>m</code><em> </em><code>0</code><em>&#39;s e </em><code>n</code><em> </em><code>1</code><em>&#39;s no subconjunto</em>.</p>\n\n<p>Um conjunto <code>x</code> é um <strong>subconjunto</strong> de um conjunto <code>y</code> se todos os elementos de <code>x</code> também são elementos de <code>y</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> strs = [&quot;10&quot;,&quot;0001&quot;,&quot;111001&quot;,&quot;1&quot;,&quot;0&quot;], m = 5, n = 3\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> O maior subconjunto com no máximo 5 0&#39;s e 3 1&#39;s é {&quot;10&quot;, &quot;0001&quot;, &quot;1&quot;, &quot;0&quot;}, então a resposta é 4.\nOutros subconjuntos válidos, mas menores, incluem {&quot;0001&quot;, &quot;1&quot;} e {&quot;10&quot;, &quot;1&quot;, &quot;0&quot;}.\n{&quot;111001&quot;} é um subconjunto inválido porque contém 4 1&#39;s, maior que o máximo de 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> strs = [&quot;10&quot;,&quot;0&quot;,&quot;1&quot;], m = 1, n = 1\n<strong>Saída:</strong> 2\n<b>Explicação:</b> O maior subconjunto é {&quot;0&quot;, &quot;1&quot;}, então a resposta é 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= strs.length &lt;= 600</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 100</code></li>\n\t<li><code>strs[i]</code> consiste apenas de dígitos <code>&#39;0&#39;</code> e <code>&#39;1&#39;</code>.</li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "475",
    "paidOnly": false,
    "title": "Heaters",
    "titleSlug": "heaters",
    "url": "https://leetcode.com/problems/heaters",
    "description_url": "https://leetcode.com/problems/heaters/description/",
    "description": "<p>Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.</p>\n\n<p>Every house can be warmed, as long as the house is within the heater&#39;s warm radius range.&nbsp;</p>\n\n<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters&nbsp;so that those heaters could cover all houses.</em></p>\n\n<p><strong>Notice</strong> that&nbsp;all the <code>heaters</code> follow your radius standard, and the warm radius will the same.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> houses = [1,2,3], heaters = [2]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> houses = [1,5], heaters = [2]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= houses.length, heaters.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= houses[i], heaters[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/heaters/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findRadius(int[] houses, int[] heaters) {\n    Arrays.sort(houses);\n    Arrays.sort(heaters);\n\n    int ans = 0;\n    int i = 0; // Point to the heater that currently used\n\n    for (final int house : houses) {\n      while (i + 1 < heaters.length && house - heaters[i] > heaters[i + 1] - house)\n        ++i; // Next heater is better\n      ans = Math.max(ans, Math.abs(heaters[i] - house));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findRadius(vector<int>& houses, vector<int>& heaters) {\n    sort(begin(houses), end(houses));\n    sort(begin(heaters), end(heaters));\n\n    int ans = 0;\n    int i = 0;  // Point to the heater that currently used\n\n    for (const int house : houses) {\n      while (i + 1 < heaters.size() &&\n             house - heaters[i] > heaters[i + 1] - house)\n        ++i;  // Next heater is better\n      ans = max(ans, abs(heaters[i] - house));\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/475.html",
    "category": "Algorithms",
    "acceptance_rate": 39.79912502310678,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search",
      "Sorting"
    ],
    "hints": [],
    "likes": 2227,
    "dislikes": 1184,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"142.1K\", \"totalSubmission\": \"357K\", \"totalAcceptedRaw\": 142098, \"totalSubmissionRaw\": 357038, \"acRate\": \"39.8%\"}",
    "title_pt": "Aquecedores",
    "description_pt": "<p>O inverno está chegando! Durante a competição, sua primeira tarefa é projetar um aquecedor padrão com um raio de aquecimento fixo para aquecer todas as casas.</p>\n\n<p>Toda casa pode ser aquecida, desde que esteja dentro do intervalo do raio de aquecimento do aquecedor.&nbsp;</p>\n\n<p>Dadas as posições de <code>houses</code> e <code>heaters</code> em uma linha horizontal, retorne <em>o menor padrão de raio dos aquecedores&nbsp;de modo que esses aquecedores possam cobrir todas as casas.</em></p>\n\n<p><strong>Observe</strong> que&nbsp;todos os <code>heaters</code> seguem seu padrão de raio, e o raio de aquecimento será o mesmo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> houses = [1,2,3], heaters = [2]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> O único aquecedor foi colocado na posição 2, e se usarmos o padrão de raio 1, então todas as casas podem ser aquecidas.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> houses = [1,2,3,4], heaters = [1,4]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Os dois aquecedores foram colocados nas posições 1 e 4. Precisamos usar um padrão de raio 1, então todas as casas podem ser aquecidas.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> houses = [1,5], heaters = [2]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= houses.length, heaters.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= houses[i], heaters[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "476",
    "paidOnly": false,
    "title": "Number Complement",
    "titleSlug": "number-complement",
    "url": "https://leetcode.com/problems/number-complement",
    "description_url": "https://leetcode.com/problems/number-complement/description/",
    "description": "<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>&#39;s to <code>1</code>&#39;s and all the <code>1</code>&#39;s to <code>0</code>&#39;s in its binary representation.</p>\n\n<ul>\n\t<li>For example, The integer <code>5</code> is <code>&quot;101&quot;</code> in binary and its <strong>complement</strong> is <code>&quot;010&quot;</code> which is the integer <code>2</code>.</li>\n</ul>\n\n<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 5\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 1\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt; 2<sup>31</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1009: <a href=\"https://leetcode.com/problems/complement-of-base-10-integer/\" target=\"_blank\">https://leetcode.com/problems/complement-of-base-10-integer/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/number-complement/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findComplement(int num) {\n    for (long i = 1; i <= num; i <<= 1)\n      num ^= i;\n    return num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findComplement(long num) {\n    for (long i = 1; i <= num; i <<= 1)\n      num ^= i;\n    return num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/476.html",
    "category": "Algorithms",
    "acceptance_rate": 70.32017409264857,
    "topics": [
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 3124,
    "dislikes": 139,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"501.8K\", \"totalSubmission\": \"713.6K\", \"totalAcceptedRaw\": 501834, \"totalSubmissionRaw\": 713642, \"acRate\": \"70.3%\"}",
    "title_pt": "Complemento de Número",
    "description_pt": "<p>O <strong>complemento</strong> de um inteiro é o inteiro que você obtém ao trocar todos os <code>0</code>&#39;s por <code>1</code>&#39;s e todos os <code>1</code>&#39;s por <code>0</code>&#39;s em sua representação binária.</p>\n\n<ul>\n\t<li>Por exemplo, o inteiro <code>5</code> é <code>&quot;101&quot;</code> em binário e seu <strong>complemento</strong> é <code>&quot;010&quot;</code>, que é o inteiro <code>2</code>.</li>\n</ul>\n\n<p>Dado um inteiro <code>num</code>, retorne <em>seu complemento</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 5\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A representação binária de 5 é 101 (sem bits zero à esquerda), e seu complemento é 010. Portanto, você deve produzir 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 1\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> A representação binária de 1 é 1 (sem bits zero à esquerda), e seu complemento é 0. Portanto, você deve produzir 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt; 2<sup>31</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que 1009: <a href=\"https://leetcode.com/problems/complement-of-base-10-integer/\" target=\"_blank\">https://leetcode.com/problems/complement-of-base-10-integer/</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "477",
    "paidOnly": false,
    "title": "Total Hamming Distance",
    "titleSlug": "total-hamming-distance",
    "url": "https://leetcode.com/problems/total-hamming-distance",
    "description_url": "https://leetcode.com/problems/total-hamming-distance/description/",
    "description": "<p>The <a href=\"https://en.wikipedia.org/wiki/Hamming_distance\" target=\"_blank\">Hamming distance</a> between two integers is the number of positions at which the corresponding bits are different.</p>\n\n<p>Given an integer array <code>nums</code>, return <em>the sum of <strong>Hamming distances</strong> between all the pairs of the integers in</em> <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,14,2]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,14,4]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/total-hamming-distance/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int totalHammingDistance(int[] nums) {\n    int ans = 0;\n    int mask = 1;\n\n    for (int i = 0; i < 30; ++i) {\n      final int onesCount = getCount(nums, mask);\n      final int zerosCount = nums.length - onesCount;\n      ans += onesCount * zerosCount;\n      mask <<= 1;\n    }\n\n    return ans;\n  }\n\n  private int getCount(int[] nums, int mask) {\n    int count = 0;\n    for (final int num : nums)\n      if ((num & mask) > 0)\n        ++count;\n    return count;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int totalHammingDistance(vector<int>& nums) {\n    int ans = 0;\n    int mask = 1;\n\n    for (int i = 0; i < 30; ++i) {\n      const int onesCount = count_if(begin(nums), end(nums),\n                                     [&mask](int num) { return num & mask; });\n      const int zerosCount = nums.size() - onesCount;\n      ans += onesCount * zerosCount;\n      mask <<= 1;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/477.html",
    "category": "Algorithms",
    "acceptance_rate": 53.65939727574281,
    "topics": [
      "Array",
      "Math",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 2263,
    "dislikes": 93,
    "similar_questions": "[{\"title\": \"Hamming Distance\", \"titleSlug\": \"hamming-distance\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Digit Differences of All Pairs\", \"titleSlug\": \"sum-of-digit-differences-of-all-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"121.6K\", \"totalSubmission\": \"226.7K\", \"totalAcceptedRaw\": 121648, \"totalSubmissionRaw\": 226704, \"acRate\": \"53.7%\"}",
    "title_pt": "Distância Total de Hamming",
    "description_pt": "<p>A <a href=\"https://en.wikipedia.org/wiki/Hamming_distance\" target=\"_blank\">distância de Hamming</a> entre dois inteiros é o número de posições nas quais os bits correspondentes são diferentes.</p>\n\n<p>Dado um array de inteiros <code>nums</code>, retorne <em>a soma das <strong>distâncias de Hamming</strong> entre todos os pares de inteiros em</em> <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,14,2]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Na representação binária, 4 é 0100, 14 é 1110 e 2 é 0010 (mostrando\napenas os quatro bits relevantes neste caso).\nA resposta será:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,14,4]\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li>A resposta para a entrada fornecida caberá em um inteiro de <strong>32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "478",
    "paidOnly": false,
    "title": "Generate Random Point in a Circle",
    "titleSlug": "generate-random-point-in-a-circle",
    "url": "https://leetcode.com/problems/generate-random-point-in-a-circle",
    "description_url": "https://leetcode.com/problems/generate-random-point-in-a-circle/description/",
    "description": "<p>Given the radius and the position of the center of a circle, implement the function <code>randPoint</code> which generates a uniform random point inside the circle.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(double radius, double x_center, double y_center)</code> initializes the object with the radius of the circle <code>radius</code> and the position of the center <code>(x_center, y_center)</code>.</li>\n\t<li><code>randPoint()</code> returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array <code>[x, y]</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;randPoint&quot;, &quot;randPoint&quot;, &quot;randPoint&quot;]\n[[1.0, 0.0, 0.0], [], [], []]\n<strong>Output</strong>\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\n<strong>Explanation</strong>\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;&nbsp;radius &lt;= 10<sup>8</sup></code></li>\n\t<li><code>-10<sup>7</sup> &lt;= x_center, y_center &lt;= 10<sup>7</sup></code></li>\n\t<li>At most <code>3 * 10<sup>4</sup></code> calls will be made to <code>randPoint</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/generate-random-point-in-a-circle/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self, radius: float, x_center: float, y_center: float):\n    self.radius = radius\n    self.x_center = x_center\n    self.y_center = y_center\n\n  def randPoint(self) -> List[float]:\n    length = sqrt(random.uniform(0, 1)) * self.radius\n    degree = random.uniform(0, 1) * 2 * math.pi\n    x = self.x_center + length * math.cos(degree)\n    y = self.y_center + length * math.sin(degree)\n    return [x, y]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(double radius, double x_center, double y_center) {\n    this.radius = radius;\n    this.x_center = x_center;\n    this.y_center = y_center;\n  }\n\n  public double[] randPoint() {\n    final double length = Math.sqrt(Math.random()) * radius;\n    final double degree = Math.random() * 2 * Math.PI;\n    final double x = x_center + length * Math.cos(degree);\n    final double y = y_center + length * Math.sin(degree);\n    return new double[] {x, y};\n  }\n\n  private double radius;\n  private double x_center;\n  private double y_center;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(double radius, double x_center, double y_center)\n      : radius(radius), x_center(x_center), y_center(y_center) {}\n\n  vector<double> randPoint() {\n    const double length = sqrt(distribution(generator)) * radius;\n    const double degree = distribution(generator) * 2 * M_PI;\n    const double x = x_center + length * cos(degree);\n    const double y = y_center + length * sin(degree);\n    return {x, y};\n  }\n\n private:\n  const double radius;\n  const double x_center;\n  const double y_center;\n  default_random_engine generator;\n  uniform_real_distribution<double> distribution =\n      uniform_real_distribution<double>(0.0, 1.0);\n};",
    "solution_code_url": "https://leetcodehelp.github.io/478.html",
    "category": "Algorithms",
    "acceptance_rate": 40.85157273630616,
    "topics": [
      "Math",
      "Geometry",
      "Rejection Sampling",
      "Randomized"
    ],
    "hints": [],
    "likes": 470,
    "dislikes": 776,
    "similar_questions": "[{\"title\": \"Random Point in Non-overlapping Rectangles\", \"titleSlug\": \"random-point-in-non-overlapping-rectangles\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"46.5K\", \"totalSubmission\": \"113.7K\", \"totalAcceptedRaw\": 46456, \"totalSubmissionRaw\": 113719, \"acRate\": \"40.9%\"}",
    "title_pt": "Gerar Ponto Aleatório em um Círculo",
    "description_pt": "<p>Dado o raio e a posição do centro de um círculo, implemente a função <code>randPoint</code> que gera um ponto aleatório uniforme dentro do círculo.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(double radius, double x_center, double y_center)</code> inicializa o objeto com o raio do círculo <code>radius</code> e a posição do centro <code>(x_center, y_center)</code>.</li>\n\t<li><code>randPoint()</code> retorna um ponto aleatório dentro do círculo. Um ponto na circunferência do círculo é considerado como estando no círculo. A resposta é retornada como um array <code>[x, y]</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;randPoint&quot;, &quot;randPoint&quot;, &quot;randPoint&quot;]\n[[1.0, 0.0, 0.0], [], [], []]\n<strong>Saída</strong>\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\n<strong>Explicação</strong>\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;&nbsp;radius &lt;= 10<sup>8</sup></code></li>\n\t<li><code>-10<sup>7</sup> &lt;= x_center, y_center &lt;= 10<sup>7</sup></code></li>\n\t<li>No máximo <code>3 * 10<sup>4</sup></code> chamadas serão feitas a <code>randPoint</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "479",
    "paidOnly": false,
    "title": "Largest Palindrome Product",
    "titleSlug": "largest-palindrome-product",
    "url": "https://leetcode.com/problems/largest-palindrome-product",
    "description_url": "https://leetcode.com/problems/largest-palindrome-product/description/",
    "description": "<p>Given an integer n, return <em>the <strong>largest palindromic integer</strong> that can be represented as the product of two <code>n</code>-digits integers</em>. Since the answer can be very large, return it <strong>modulo</strong> <code>1337</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/largest-palindrome-product/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def largestPalindrome(self, n: int) -> int:\n    if n == 1:\n      return 9\n\n    kMod = 1337\n    upper = pow(10, n) - 1\n    lower = pow(10, n - 1) - 1\n\n    for i in range(upper, lower, -1):\n      cand = int(str(i) + str(i)[::-1])\n      j = upper\n      while j * j >= cand:\n        if cand % j == 0:\n          return cand % kMod\n        j -= 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int largestPalindrome(int n) {\n    if (n == 1)\n      return 9;\n\n    final int kMod = 1337;\n    final int upper = (int) Math.pow(10, n) - 1;\n    final int lower = (int) Math.pow(10, n - 1) - 1;\n\n    for (int i = upper; i > lower; --i) {\n      final long cand = getPalindromeCandidate(i);\n      for (long j = upper; j * j >= cand; --j)\n        if (cand % j == 0)\n          return (int) (cand % kMod);\n    }\n\n    throw new IllegalArgumentException();\n  }\n\n  private long getPalindromeCandidate(int i) {\n    final String reversed = new StringBuilder().append(i).reverse().toString();\n    return Long.valueOf(i + reversed);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int largestPalindrome(int n) {\n    if (n == 1)\n      return 9;\n\n    constexpr int kMod = 1337;\n    const int upper = pow(10, n) - 1;\n    const int lower = pow(10, n - 1) - 1;\n\n    for (int i = upper; i > lower; --i) {\n      const long cand = getPalindromeCandidate(i);\n      for (long j = upper; j * j >= cand; --j)\n        if (cand % j == 0)\n          return cand % kMod;\n    }\n\n    throw;\n  }\n\n private:\n  long getPalindromeCandidate(int i) {\n    string reversed = to_string(i);\n    reverse(begin(reversed), end(reversed));\n    return stol(to_string(i) + reversed);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/479.html",
    "category": "Algorithms",
    "acceptance_rate": 34.90779357821215,
    "topics": [
      "Math",
      "Enumeration"
    ],
    "hints": [],
    "likes": 181,
    "dislikes": 1563,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"27.8K\", \"totalSubmission\": \"79.6K\", \"totalAcceptedRaw\": 27788, \"totalSubmissionRaw\": 79604, \"acRate\": \"34.9%\"}",
    "title_pt": "Maior Produto Palíndromo",
    "description_pt": "<p>Dado um inteiro n, retorne <em>o <strong>maior inteiro palindrômico</strong> que pode ser representado como o produto de dois inteiros de <code>n</code> dígitos</em>. Como a resposta pode ser muito grande, retorne-a <strong>módulo</strong> <code>1337</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 987\nExplicação: 99 x 91 = 9009, 9009 % 1337 = 987\n</pre>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 8</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "480",
    "paidOnly": false,
    "title": "Sliding Window Median",
    "titleSlug": "sliding-window-median",
    "url": "https://leetcode.com/problems/sliding-window-median",
    "description_url": "https://leetcode.com/problems/sliding-window-median/description/",
    "description": "<p>The <strong>median</strong> is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.</p>\n\n<ul>\n\t<li>For examples, if <code>arr = [2,<u>3</u>,4]</code>, the median is <code>3</code>.</li>\n\t<li>For examples, if <code>arr = [1,<u>2,3</u>,4]</code>, the median is <code>(2 + 3) / 2 = 2.5</code>.</li>\n</ul>\n\n<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. There is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>\n\n<p>Return <em>the median array for each window in the original array</em>. Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3\n<strong>Output:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\n<strong>Explanation:</strong> \nWindow position                Median\n---------------                -----\n[<strong>1  3  -1</strong>] -3  5  3  6  7        1\n 1 [<strong>3  -1  -3</strong>] 5  3  6  7       -1\n 1  3 [<strong>-1  -3  5</strong>] 3  6  7       -1\n 1  3  -1 [<strong>-3  5  3</strong>] 6  7        3\n 1  3  -1  -3 [<strong>5  3  6</strong>] 7        5\n 1  3  -1  -3  5 [<strong>3  6  7</strong>]       6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3\n<strong>Output:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sliding-window-median/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n    vector<double> ans;\n    multiset<double> window(begin(nums), begin(nums) + k);\n    auto it = next(begin(window), (k - 1) / 2);\n\n    for (int i = k;; ++i) {\n      const double median = k & 1 ? *it : (*it + *next(it)) / 2.0;\n      ans.push_back(median);\n      if (i == nums.size())\n        break;\n      window.insert(nums[i]);\n      if (nums[i] < *it)\n        --it;\n      if (nums[i - k] <= *it)\n        ++it;\n      window.erase(window.lower_bound(nums[i - k]));\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/480.html",
    "category": "Algorithms",
    "acceptance_rate": 38.636060124938794,
    "topics": [
      "Array",
      "Hash Table",
      "Sliding Window",
      "Heap (Priority Queue)"
    ],
    "hints": [
      "The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array?",
      "Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done.",
      "The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?"
    ],
    "likes": 3378,
    "dislikes": 218,
    "similar_questions": "[{\"title\": \"Find Median from Data Stream\", \"titleSlug\": \"find-median-from-data-stream\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make Median of Array Equal to K\", \"titleSlug\": \"minimum-operations-to-make-median-of-array-equal-to-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"182.3K\", \"totalSubmission\": \"471.8K\", \"totalAcceptedRaw\": 182265, \"totalSubmissionRaw\": 471750, \"acRate\": \"38.6%\"}",
    "title_pt": "Mediana da Janela Deslizante",
    "description_pt": "<p>A <strong>mediana</strong> é o valor central em uma lista ordenada de inteiros. Se o tamanho da lista for par, não há valor central. Então a mediana é a média dos dois valores centrais.</p>\n\n<ul>\n\t<li>Por exemplo, se <code>arr = [2,<u>3</u>,4]</code>, a mediana é <code>3</code>.</li>\n\t<li>Por exemplo, se <code>arr = [1,<u>2,3</u>,4]</code>, a mediana é <code>(2 + 3) / 2 = 2.5</code>.</li>\n</ul>\n\n<p>Você recebe um array de inteiros <code>nums</code> e um inteiro <code>k</code>. Há uma janela deslizante de tamanho <code>k</code> que está se movendo da extrema esquerda do array até a extrema direita. Você só pode ver os <code>k</code> números na janela. A cada vez, a janela deslizante se move uma posição para a direita.</p>\n\n<p>Retorne <em>o array de medianas para cada janela no array original</em>. Respostas dentro de <code>10<sup>-5</sup></code> do valor real serão aceitas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,-1,-3,5,3,6,7], k = 3\n<strong>Saída:</strong> [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\n<strong>Explicação:</strong> \nWindow position                Median\n---------------                -----\n[<strong>1  3  -1</strong>] -3  5  3  6  7        1\n 1 [<strong>3  -1  -3</strong>] 5  3  6  7       -1\n 1  3 [<strong>-1  -3  5</strong>] 3  6  7       -1\n 1  3  -1 [<strong>-3  5  3</strong>] 6  7        3\n 1  3  -1  -3 [<strong>5  3  6</strong>] 7        5\n 1  3  -1  -3  5 [<strong>3  6  7</strong>]       6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,2,3,1,4,2], k = 3\n<strong>Saída:</strong> [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: A solução mais simples vem da ideia básica de encontrar a mediana dado um conjunto de números. Sabemos que, por definição, uma mediana é o elemento central (ou a média dos dois elementos centrais). Dada uma lista não ordenada de números, como encontramos o elemento mediano? Se você souber a resposta para essa pergunta, podemos estender essa ideia para cada janela deslizante que encontramos no array?",
      "Dica 2: Há uma maneira melhor de fazer o que estamos fazendo na dica acima? Você não acha que há repetição de cálculo sendo feita ali? Existe algum tipo de otimização que podemos fazer para alcançar o mesmo resultado? Essa abordagem é apenas uma modificação da abordagem básica, exceto pelo fato de que ela simplesmente reduz a duplicação de cálculos já realizados.",
      "Dica 3: A terceira linha de raciocínio também é baseada nessa mesma ideia, mas alcança o resultado de uma forma diferente. Obviamente, precisamos que a janela esteja ordenada para conseguirmos encontrar a mediana. Existe alguma estrutura de dados que possamos usar (em uma ou mais quantidades) para obter o elemento mediano extremamente rápido, digamos em tempo O(1), ao mesmo tempo em que temos a capacidade de realizar as outras operações de forma bastante eficiente também?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "481",
    "paidOnly": false,
    "title": "Magical String",
    "titleSlug": "magical-string",
    "url": "https://leetcode.com/problems/magical-string",
    "description_url": "https://leetcode.com/problems/magical-string/description/",
    "description": "<p>A magical string <code>s</code> consists of only <code>&#39;1&#39;</code> and <code>&#39;2&#39;</code> and obeys the following rules:</p>\n\n<ul>\n\t<li>The string s is magical because concatenating the number of contiguous occurrences of characters <code>&#39;1&#39;</code> and <code>&#39;2&#39;</code> generates the string <code>s</code> itself.</li>\n</ul>\n\n<p>The first few elements of <code>s</code> is <code>s = &quot;1221121221221121122&hellip;&hellip;&quot;</code>. If we group the consecutive <code>1</code>&#39;s and <code>2</code>&#39;s in <code>s</code>, it will be <code>&quot;1 22 11 2 1 22 1 22 11 2 11 22 ......&quot;</code> and the occurrences of <code>1</code>&#39;s or <code>2</code>&#39;s in each group are <code>&quot;1 2 2 1 1 2 1 2 2 1 2 2 ......&quot;</code>. You can see that the occurrence sequence is <code>s</code> itself.</p>\n\n<p>Given an integer <code>n</code>, return the number of <code>1</code>&#39;s in the first <code>n</code> number in the magical string <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 6\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The first 6 elements of magical string s is &quot;122112&quot; and it contains three 1&#39;s, so return 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/magical-string/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int magicalString(int n) {\n    string s = \" 122\";\n\n    for (int i = 3; i <= n; ++i)\n      if (i & 1)\n        s.append(s[i] - '0', '1');\n      else\n        s.append(s[i] - '0', '2');\n\n    return count(begin(s), begin(s) + n + 1, '1');\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/481.html",
    "category": "Algorithms",
    "acceptance_rate": 52.31921531495441,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 345,
    "dislikes": 1367,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"43.1K\", \"totalSubmission\": \"82.4K\", \"totalAcceptedRaw\": 43099, \"totalSubmissionRaw\": 82377, \"acRate\": \"52.3%\"}",
    "title_pt": "String Mágica",
    "description_pt": "<p>Uma string mágica <code>s</code> consiste apenas de <code>&#39;1&#39;</code> e <code>&#39;2&#39;</code> e obedece às seguintes regras:</p>\n\n<ul>\n\t<li>A string s é mágica porque concatenar o número de ocorrências contíguas dos caracteres <code>&#39;1&#39;</code> e <code>&#39;2&#39;</code> gera a própria string <code>s</code>.</li>\n</ul>\n\n<p>Os primeiros elementos de <code>s</code> são <code>s = &quot;1221121221221121122&hellip;&hellip;&quot;</code>. Se agrupamos os <code>1</code>&#39;s e <code>2</code>&#39;s consecutivos em <code>s</code>, ele será <code>&quot;1 22 11 2 1 22 1 22 11 2 11 22 ......&quot;</code> e as ocorrências de <code>1</code>&#39;s ou <code>2</code>&#39;s em cada grupo são <code>&quot;1 2 2 1 1 2 1 2 2 1 2 2 ......&quot;</code>. Você pode ver que a sequência de ocorrências é a própria <code>s</code>.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne o número de <code>1</code>&#39;s nos primeiros <code>n</code> números na string mágica <code>s</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 6\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os primeiros 6 elementos da string mágica s são &quot;122112&quot; e ela contém três <code>1</code>&#39;s, então retorne 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "482",
    "paidOnly": false,
    "title": "License Key Formatting",
    "titleSlug": "license-key-formatting",
    "url": "https://leetcode.com/problems/license-key-formatting",
    "description_url": "https://leetcode.com/problems/license-key-formatting/description/",
    "description": "<p>You are given a license key represented as a string <code>s</code> that consists of only alphanumeric characters and dashes. The string is separated into <code>n + 1</code> groups by <code>n</code> dashes. You are also given an integer <code>k</code>.</p>\n\n<p>We want to reformat the string <code>s</code> such that each group contains exactly <code>k</code> characters, except for the first group, which could be shorter than <code>k</code> but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.</p>\n\n<p>Return <em>the reformatted license key</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;5F3Z-2e-9-w&quot;, k = 4\n<strong>Output:</strong> &quot;5F3Z-2E9W&quot;\n<strong>Explanation:</strong> The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;2-5g-3-J&quot;, k = 2\n<strong>Output:</strong> &quot;2-5G-3J&quot;\n<strong>Explanation:</strong> The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of English letters, digits, and dashes <code>&#39;-&#39;</code>.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/license-key-formatting/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n\n### Overview\n\nThe problem states that we need to split the entire string into groups such that each group other than the first group has `k` number of upper-case characters.\n\nBe sure to communicate thoroughly with your interviewer to make sure you're covering all cases. In this problem, the constraints are thorough because there is no interviewer to communicate with. However, in an interview, there is a potential to ask a few follow-up questions from the interviewer, like:\n1) Can we have more numbers of groups in the output string as compared to the input string?\n2) Can `k` be greater than the size of the input string?\n\n---\n### Approach 1: Right to Left Traversal\n\n#### Intuition\n\nWe need to form some groups in the string where each group has exactly the `k` characters in it except the first group (which can have `k` or fewer characters) and each group will be separated by a `-`.\n\nThus, the problem's main essence is finding how many alphanumeric characters will come in the first group!\nWe can think of forming groups of size `k` from the end of the given string, and when the last group is left (which will be first in reality) it will automatically have `k` or fewer characters in it.\n\n![Representation1](../Figures/482/approach1.png)\n\n\n\nUsing the above thought process, let's understand how to address this problem.\n\nWe can start traversing the string from the end so that we can form all the groups other than the first group in the size of `k` alphanumeric characters. While traversing from the end, we need to make sure that groups are formed in such a way that each group satisfies our problem's conditions. When we reach the start of the input string our output string will automatically be forming the group of size `k` alphanumeric characters leaving the first group with either equal to the size of `k` or lesser than the size of `k`. There's one scenario here where if all our groups including the first group are of size `k`, then `dash` gets inserted at the end of the string. Thus we need to make sure for such cases we should remove the last element from our answer string. However, our output string needs to be reversed since we were traversing the input string from the end.\n\n#### Algorithm\n\n1. Initialize:\n    - `count` to `0`, which is used to count the number of characters in the current group.\n    - `n` to input string length.\n    - `ans` to an empty string, which is used to store the final result.  \n\n2. Now, iterate on the input string in reverse order:\n    - We will skip `'-'` characters from the input string. \n    - If the current character is not `'-'`, we include the current character in `ans` string and increment the current group size by incrementing `count` by `1`.\n    - If `count` reaches `k`, it means we formed a group of size `k`, thus we can append a `'-'` in `ans` now, and reset `count` to start counting a new group.\n\n3. After we finish traversing on the input string, we should check if the last character inserted wasn't a dash. If we find a dash we need to remove it from `ans` string. \n\n4. Now that we formed all groups in reverse order, thus we need to reverse the `ans` string and then return it.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/f6VatTcm/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"f6VatTcm\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the size of the input array.\n\n* Time Complexity: $O(N)$\n  - We traverse on each input string's character once in reverse order which takes $O(N)$ time.\n  - At the end, we reverse the `ans` thus iterating on it once, which also takes $O(N)$ time.\n  - Thus, overall we take $O(N)$ time.\n\n* Space Complexity: $O(1)$\n  - We are not using any extra space other than the output string.\n<br />\n\n---\n\n### Approach 2: Left to Right Traversal\n\n\n#### Intuition\n\nTo solve the problem, let's look at the inputs carefully,\n> We will be given an alphanumeric string which will have numbers, characters and dash.\n\n\n\nThe problem states that we need to form equal groups of size `k` upper case characters other than the first group. For doing so, we need to first find the total number of alphanumeric characters in the input string.             \nAnd then the size of the first group will be decided on the basis of 2 factors:         \n1. Total count of alphanumeric characters in the string              \n2. Value of `k`\n\n\nIf we observe carefully, we just need to find how many characters will be left behind at last when we form groups from the end of the string, thus the size of the first group will be given by `total count of alphanumeric characters in string % value of k`.\n\nIn this approach, we will first populate the first group and then fill the characters in the remaining groups, whereas in the first approach we fill the first group in the end.\n\n![Representation2](../Figures/482/approach2.png)\n\n\nWe can also have two cases where the size of `k` is equal to, or greater than the total count of alphanumeric characters of the input string. During such cases, our output string will only consist of 1 group.\n\n#### Algorithm\n\nBy analysing the above observations, we can derive the following algorithm,\n1. Initialize:\n    - `totalChars` to `0`, which is used to count the number of characters in the input string excluding dash.\n    - `count` to `0`, which is used to count the number of characters in the current group.\n    - `sizeOfFirstGroup` to be populated which will store the result of `(totalChars % k)`.\n    - `ans` to an empty string, which is used to store the final result  \n\n\n2. Now, iterate on the input string:\n    - We will skip `'-'` characters from the input string to get the total count of characters in the input string.\n    - Fill the first group by only copying `sizeOfFirstGroup` characters in the `ans` string and then break the loop.\n    - Return the `ans` string if we reach the end of the loop.\n    - Append the `ans` string with `-` in order to form the first group.\n    - Continue iterating from the previous `i` till the end of the input string.\n    - If the current character is not `'-'`, we include the current character in `ans` string and increment the current group size by incrementing `count` by `1`.\n    - If `count` reaches `k`, it means we formed a group of size `k`, thus we can append a `'-'` in `ans` now, and reset `count` to start counting a new group.\n\n3. After we finish traversing on the input string, we return `ans` string.\n\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/MoHJwKqj/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"MoHJwKqj\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the size of the input array.\n\n* Time Complexity: $O(N)$\n  - We traverse on each input string's character once to get the count of `totalChars` which takes $O(N)$ time.\n  - We traverse input string for the second time in order to correctly populate `ans` string in groups which again takes $O(N)$ time.\n  - Thus, overall we take $O(N)$ time.\n\n* Space Complexity: $O(1)$\n  - We are not using any extra space other than the output string.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String licenseKeyFormatting(String S, int K) {\n    StringBuilder sb = new StringBuilder();\n    int length = 0;\n\n    for (int i = S.length() - 1; i >= 0; --i) {\n      if (S.charAt(i) == '-')\n        continue;\n      if (length > 0 && length % K == 0)\n        sb.append('-');\n      sb.append(Character.toUpperCase(S.charAt(i)));\n      ++length;\n    }\n\n    return sb.reverse().toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string licenseKeyFormatting(string S, int K) {\n    string ans;\n    int length = 0;\n\n    for (int i = S.length() - 1; i >= 0; --i) {\n      if (S[i] == '-')\n        continue;\n      if (length > 0 && length % K == 0)\n        ans += \"-\";\n      ans += toupper(S[i]);\n      ++length;\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/482.html",
    "category": "Algorithms",
    "acceptance_rate": 44.62303822129245,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 1147,
    "dislikes": 1434,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"316.5K\", \"totalSubmission\": \"709.4K\", \"totalAcceptedRaw\": 316541, \"totalSubmissionRaw\": 709368, \"acRate\": \"44.6%\"}",
    "title_pt": "Formatação de Chave de Licença",
    "description_pt": "<p>Você recebe uma chave de licença representada como uma string <code>s</code> que consiste apenas de caracteres alfanuméricos e hífens. A string é separada em <code>n + 1</code> grupos por <code>n</code> hífens. Você também recebe um inteiro <code>k</code>.</p>\n\n<p>Queremos reformatar a string <code>s</code> de modo que cada grupo contenha exatamente <code>k</code> caracteres, exceto o primeiro grupo, que pode ser menor que <code>k</code>, mas ainda deve conter pelo menos um caractere. Além disso, deve haver um hífen inserido entre dois grupos, e você deve converter todas as letras minúsculas para maiúsculas.</p>\n\n<p>Retorne <em>a chave de licença reformatada</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;5F3Z-2e-9-w&quot;, k = 4\n<strong>Saída:</strong> &quot;5F3Z-2E9W&quot;\n<strong>Explicação:</strong> A string s foi dividida em duas partes, cada parte com 4 caracteres.\nObserve que os dois hífens extras não são necessários e podem ser removidos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;2-5g-3-J&quot;, k = 2\n<strong>Saída:</strong> &quot;2-5G-3J&quot;\n<strong>Explicação:</strong> A string s foi dividida em três partes, cada parte com 2 caracteres, exceto a primeira parte, que pode ser menor, conforme mencionado acima.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em letras inglesas, dígitos e hífens <code>&#39;-&#39;</code>.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "483",
    "paidOnly": false,
    "title": "Smallest Good Base",
    "titleSlug": "smallest-good-base",
    "url": "https://leetcode.com/problems/smallest-good-base",
    "description_url": "https://leetcode.com/problems/smallest-good-base/description/",
    "description": "<p>Given an integer <code>n</code> represented as a string, return <em>the smallest <strong>good base</strong> of</em> <code>n</code>.</p>\n\n<p>We call <code>k &gt;= 2</code> a <strong>good base</strong> of <code>n</code>, if all digits of <code>n</code> base <code>k</code> are <code>1</code>&#39;s.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = &quot;13&quot;\n<strong>Output:</strong> &quot;3&quot;\n<strong>Explanation:</strong> 13 base 3 is 111.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = &quot;4681&quot;\n<strong>Output:</strong> &quot;8&quot;\n<strong>Explanation:</strong> 4681 base 8 is 11111.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = &quot;1000000000000000000&quot;\n<strong>Output:</strong> &quot;999999999999999999&quot;\n<strong>Explanation:</strong> 1000000000000000000 base 999999999999999999 is 11.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n</code> is an integer in the range <code>[3, 10<sup>18</sup>]</code>.</li>\n\t<li><code>n</code> does not contain any leading zeros.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/smallest-good-base/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def smallestGoodBase(self, n: str) -> str:\n    n = int(n)\n\n    for m in range(int(math.log(n, 2)), 1, -1):\n      k = int(n**m**-1)\n      if (k**(m + 1) - 1) // (k - 1) == n:\n        return str(k)\n\n    return str(n - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String smallestGoodBase(String n) {\n    final long num = Long.parseLong(n);\n    final int log2 = (int) (Math.log(num) / Math.log(2));\n\n    for (int m = log2; m >= 2; --m) {\n      int k = (int) Math.floor(Math.pow(num, 1.0 / m));\n      long sum = 1;\n      long prod = 1;\n      for (int i = 0; i < m; ++i) {\n        prod *= k;\n        sum += prod;\n      }\n      if (sum == num)\n        return String.valueOf(k);\n    }\n\n    return String.valueOf(num - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string smallestGoodBase(string n) {\n    const long num = stol(n);\n\n    for (int m = log2(num); m >= 2; --m) {\n      const int k = pow(num, 1.0 / m);\n      long sum = 1;\n      long prod = 1;\n      for (int i = 0; i < m; ++i) {\n        prod *= k;\n        sum += prod;\n      }\n      if (sum == num)\n        return to_string(k);\n    }\n\n    return to_string(num - 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/483.html",
    "category": "Algorithms",
    "acceptance_rate": 43.20437645363121,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [],
    "likes": 415,
    "dislikes": 528,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"26.4K\", \"totalSubmission\": \"61.1K\", \"totalAcceptedRaw\": 26378, \"totalSubmissionRaw\": 61054, \"acRate\": \"43.2%\"}",
    "title_pt": "Menor Base Boa",
    "description_pt": "<p>Dado um inteiro <code>n</code> representado como uma string, retorne <em>a menor <strong>base boa</strong> de</em> <code>n</code>.</p>\n\n<p>Chamamos <code>k &gt;= 2</code> de uma <strong>base boa</strong> de <code>n</code> se todos os dígitos de <code>n</code> na base <code>k</code> forem <code>1</code>&#39;s.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = &quot;13&quot;\n<strong>Saída:</strong> &quot;3&quot;\n<strong>Explicação:</strong> 13 na base 3 é 111.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = &quot;4681&quot;\n<strong>Saída:</strong> &quot;8&quot;\n<strong>Explicação:</strong> 4681 na base 8 é 11111.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = &quot;1000000000000000000&quot;\n<strong>Saída:</strong> &quot;999999999999999999&quot;\n<strong>Explicação:</strong> 1000000000000000000 na base 999999999999999999 é 11.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n</code> é um inteiro no intervalo <code>[3, 10<sup>18</sup>]</code>.</li>\n\t<li><code>n</code> não contém zeros à esquerda.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "486",
    "paidOnly": false,
    "title": "Predict the Winner",
    "titleSlug": "predict-the-winner",
    "url": "https://leetcode.com/problems/predict-the-winner",
    "description_url": "https://leetcode.com/problems/predict-the-winner/description/",
    "description": "<p>You are given an integer array <code>nums</code>. Two players are playing a game with this array: player 1 and player 2.</p>\n\n<p>Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of <code>0</code>. At each turn, the player takes one of the numbers from either end of the array (i.e., <code>nums[0]</code> or <code>nums[nums.length - 1]</code>) which reduces the size of the array by <code>1</code>. The player adds the chosen number to their score. The game ends when there are no more elements in the array.</p>\n\n<p>Return <code>true</code> if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return <code>true</code>. You may assume that both players are playing optimally.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,2]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,5,233,7]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/predict-the-winner/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  bool PredictTheWinner(vector<int>& nums) {\n    const int n = nums.size();\n    vector<int> dp = nums;\n\n    for (int d = 1; d < n; ++d)\n      for (int j = n - 1; j - d >= 0; --j) {\n        const int i = j - d;\n        dp[j] = max(nums[i] - dp[j],       // Pick left num\n                    nums[j] - dp[j - 1]);  // Pick right num\n      }\n\n    return dp[n - 1] >= 0;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean PredictTheWinner(int[] nums) {\n    final int n = nums.length;\n    // dp[i][j] := max number you can get more than your opponent in nums[i..j]\n    int[][] dp = new int[n][n];\n\n    for (int i = 0; i < n; ++i)\n      dp[i][i] = nums[i];\n\n    for (int d = 1; d < n; ++d)\n      for (int i = 0; i + d < n; ++i) {\n        final int j = i + d;\n        dp[i][j] = Math.max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);\n      }\n\n    return dp[0][n - 1] >= 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool PredictTheWinner(vector<int>& nums) {\n    const int n = nums.size();\n    // dp[i][j] := max number you can get more than your opponent in nums[i..j]\n    vector<vector<int>> dp(n, vector<int>(n));\n\n    for (int i = 0; i < n; ++i)\n      dp[i][i] = nums[i];\n\n    for (int d = 1; d < n; ++d)\n      for (int i = 0; i + d < n; ++i) {\n        const int j = i + d;\n        dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);\n      }\n\n    return dp[0][n - 1] >= 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/486.html",
    "category": "Algorithms",
    "acceptance_rate": 55.662486096075845,
    "topics": [
      "Array",
      "Math",
      "Dynamic Programming",
      "Recursion",
      "Game Theory"
    ],
    "hints": [],
    "likes": 5998,
    "dislikes": 291,
    "similar_questions": "[{\"title\": \"Can I Win\", \"titleSlug\": \"can-i-win\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Winning Player in Coin Game\", \"titleSlug\": \"find-the-winning-player-in-coin-game\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Number of Winning Players\", \"titleSlug\": \"find-the-number-of-winning-players\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count The Number of Winning Sequences\", \"titleSlug\": \"count-the-number-of-winning-sequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"261.7K\", \"totalSubmission\": \"470.2K\", \"totalAcceptedRaw\": 261720, \"totalSubmissionRaw\": 470191, \"acRate\": \"55.7%\"}",
    "title_pt": "Prever o Vencedor",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code>. Dois jogadores estão jogando um jogo com esse array: o jogador 1 e o jogador 2.</p>\n\n<p>O jogador 1 e o jogador 2 jogam em turnos, com o jogador 1 começando primeiro. Ambos os jogadores começam o jogo com uma pontuação de <code>0</code>. A cada turno, o jogador pega um dos números de qualquer uma das extremidades do array (ou seja, <code>nums[0]</code> ou <code>nums[nums.length - 1]</code>), o que reduz o tamanho do array em <code>1</code>. O jogador adiciona o número escolhido à sua pontuação. O jogo termina quando não houver mais elementos no array.</p>\n\n<p>Retorne <code>true</code> se o Jogador 1 puder vencer o jogo. Se as pontuações de ambos os jogadores forem iguais, então o jogador 1 ainda será o vencedor, e você também deve retornar <code>true</code>. Você pode assumir que ambos os jogadores estão jogando de forma ótima.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,2]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Inicialmente, o jogador 1 pode escolher entre 1 e 2. \nSe ele escolher 2 (ou 1), então o jogador 2 pode escolher entre 1 (ou 2) e 5. Se o jogador 2 escolher 5, então o jogador 1 ficará com 1 (ou 2). \nPortanto, a pontuação final do jogador 1 é 1 + 2 = 3, e a do jogador 2 é 5. \nAssim, o jogador 1 jamais será o vencedor e você precisa retornar false.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,5,233,7]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O jogador 1 escolhe primeiro 1. Então o jogador 2 precisa escolher entre 5 e 7. Não importa qual número o jogador 2 escolha, o jogador 1 pode escolher 233.\nPor fim, o jogador 1 tem mais pontos (234) do que o jogador 2 (12), então você precisa retornar True representando que o jogador 1 pode vencer.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "488",
    "paidOnly": false,
    "title": "Zuma Game",
    "titleSlug": "zuma-game",
    "url": "https://leetcode.com/problems/zuma-game",
    "description_url": "https://leetcode.com/problems/zuma-game/description/",
    "description": "<p>You are playing a variation of the game Zuma.</p>\n\n<p>In this variation of Zuma, there is a <strong>single row</strong> of colored balls on a board, where each ball can be colored red <code>&#39;R&#39;</code>, yellow <code>&#39;Y&#39;</code>, blue <code>&#39;B&#39;</code>, green <code>&#39;G&#39;</code>, or white <code>&#39;W&#39;</code>. You also have several colored balls in your hand.</p>\n\n<p>Your goal is to <strong>clear all</strong> of the balls from the board. On each turn:</p>\n\n<ul>\n\t<li>Pick <strong>any</strong> ball from your hand and insert it in between two balls in the row or on either end of the row.</li>\n\t<li>If there is a group of <strong>three or more consecutive balls</strong> of the <strong>same color</strong>, remove the group of balls from the board.\n\t<ul>\n\t\t<li>If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.</li>\n\t</ul>\n\t</li>\n\t<li>If there are no more balls on the board, then you win the game.</li>\n\t<li>Repeat this process until you either win or do not have any more balls in your hand.</li>\n</ul>\n\n<p>Given a string <code>board</code>, representing the row of balls on the board, and a string <code>hand</code>, representing the balls in your hand, return <em>the <strong>minimum</strong> number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return </em><code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> board = &quot;WRRBBW&quot;, hand = &quot;RB&quot;\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> It is impossible to clear all the balls. The best you can do is:\n- Insert &#39;R&#39; so the board becomes WRR<u>R</u>BBW. W<u>RRR</u>BBW -&gt; WBBW.\n- Insert &#39;B&#39; so the board becomes WBB<u>B</u>W. W<u>BBB</u>W -&gt; WW.\nThere are still balls remaining on the board, and you are out of balls to insert.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> board = &quot;WWRRBBWW&quot;, hand = &quot;WRBRW&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> To make the board empty:\n- Insert &#39;R&#39; so the board becomes WWRR<u>R</u>BBWW. WW<u>RRR</u>BBWW -&gt; WWBBWW.\n- Insert &#39;B&#39; so the board becomes WWBB<u>B</u>WW. WW<u>BBB</u>WW -&gt; <u>WWWW</u> -&gt; empty.\n2 balls from your hand were needed to clear the board.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> board = &quot;G&quot;, hand = &quot;GGGGG&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> To make the board empty:\n- Insert &#39;G&#39; so the board becomes G<u>G</u>.\n- Insert &#39;G&#39; so the board becomes GG<u>G</u>. <u>GGG</u> -&gt; empty.\n2 balls from your hand were needed to clear the board.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= board.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= hand.length &lt;= 5</code></li>\n\t<li><code>board</code> and <code>hand</code> consist of the characters <code>&#39;R&#39;</code>, <code>&#39;Y&#39;</code>, <code>&#39;B&#39;</code>, <code>&#39;G&#39;</code>, and <code>&#39;W&#39;</code>.</li>\n\t<li>The initial row of balls on the board will <strong>not</strong> have any groups of three or more consecutive balls of the same color.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/zuma-game/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMinStep(self, board: str, hand: str) -> int:\n    def deDup(board):\n      start = 0  # Start index of a color sequenece\n      for i, c in enumerate(board):\n        if c != board[start]:\n          if i - start >= 3:\n            return deDup(board[:start] + board[i:])\n          start = i  # Meet a new sequence\n      return board\n\n    @functools.lru_cache(None)\n    def dfs(board: str, hand: str):\n      board = deDup(board)\n      if board == '#':\n        return 0\n\n      boardSet = set(board)\n      # Hand that in board\n      hand = ''.join(h for h in hand if h in boardSet)\n      if not hand:  # Infeasible\n        return math.inf\n\n      ans = math.inf\n\n      for i in range(len(board)):\n        for j, h in enumerate(hand):\n          # Place hs[j] in board[i]\n          newHand = hand[:j] + hand[j + 1:]\n          newBoard = board[:i] + h + board[i:]\n          ans = min(ans, 1 + dfs(newBoard, newHand))\n\n      return ans\n\n    ans = dfs(board + '#', hand)\n    return -1 if ans == math.inf else ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMinStep(String board, String hand) {\n    Map<String, Integer> memo = new HashMap<>();\n    final int ans = dfs(board + '#', hand, memo);\n    return ans == Integer.MAX_VALUE ? -1 : ans;\n  }\n\n  private int dfs(String board, final String hand, Map<String, Integer> memo) {\n    final String hashKey = board + '#' + hand;\n    if (memo.containsKey(hashKey))\n      return memo.get(hashKey);\n    board = deDup(board);\n    if (board.equals(\"#\"))\n      return 0;\n\n    Set<Character> boardSet = new HashSet<>();\n    for (final char c : board.toCharArray())\n      boardSet.add(c);\n\n    StringBuilder sb = new StringBuilder();\n    for (final char h : hand.toCharArray())\n      if (boardSet.contains(h))\n        sb.append(h);\n    final String hs = sb.toString();\n    if (sb.length() == 0) // Infeasible\n      return Integer.MAX_VALUE;\n\n    int ans = Integer.MAX_VALUE;\n\n    for (int i = 0; i < board.length(); ++i)\n      for (int j = 0; j < hs.length(); ++j) {\n        // Place hs[j] in board[i]\n        final String newHand = hs.substring(0, j) + hs.substring(j + 1);\n        String newBoard = board.substring(0, i) + hs.charAt(j) + board.substring(i);\n        final int res = dfs(newBoard, newHand, memo);\n        if (res < Integer.MAX_VALUE)\n          ans = Math.min(ans, 1 + res);\n      }\n\n    memo.put(hashKey, ans);\n    return ans;\n  }\n\n  private String deDup(String board) {\n    int start = 0; // Start index of a color sequenece\n    for (int i = 0; i < board.length(); ++i)\n      if (board.charAt(i) != board.charAt(start)) {\n        if (i - start >= 3)\n          return deDup(board.substring(0, start) + board.substring(i));\n        start = i; // Meet a new sequence\n      }\n    return board;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMinStep(string board, string hand) {\n    const int ans = dfs(board + \"#\", hand, {});\n    return ans == INT_MAX ? -1 : ans;\n  }\n\n private:\n  int dfs(string&& board, const string& hand,\n          unordered_map<string, int>&& memo) {\n    const string& hashKey = board + '#' + hand;\n    if (memo.count(hashKey))\n      return memo[hashKey];\n    board = deDup(board);\n    if (board == \"#\")\n      return 0;\n\n    unordered_set<char> boardSet = unordered_set(begin(board), end(board));\n\n    string hs;  // Hand that in board\n    for (const char h : hand)\n      if (boardSet.count(h))\n        hs += h;\n    if (hs.empty())  // Infeasible\n      return INT_MAX;\n\n    int ans = INT_MAX;\n\n    for (int i = 0; i < board.size(); ++i)\n      for (int j = 0; j < hs.size(); ++j) {\n        // Place hs[j] in board[i]\n        const string& newHand = hs.substr(0, j) + hs.substr(j + 1);\n        string newBoard = board.substr(0, i) + hs[j] + board.substr(i);\n        const int res = dfs(move(newBoard), newHand, move(memo));\n        if (res < INT_MAX)\n          ans = min(ans, 1 + res);\n      }\n\n    return memo[hashKey] = ans;\n  }\n\n  string deDup(string board) {\n    int start = 0;  // Start index of a color sequenece\n    for (int i = 0; i < board.size(); ++i)\n      if (board[i] != board[start]) {\n        if (i - start >= 3)\n          return deDup(board.substr(0, start) + board.substr(i));\n        start = i;  // Meet a new sequence\n      }\n    return board;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/488.html",
    "category": "Algorithms",
    "acceptance_rate": 31.603654048052903,
    "topics": [
      "String",
      "Dynamic Programming",
      "Stack",
      "Breadth-First Search",
      "Memoization"
    ],
    "hints": [],
    "likes": 470,
    "dislikes": 500,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"26.2K\", \"totalSubmission\": \"82.9K\", \"totalAcceptedRaw\": 26189, \"totalSubmissionRaw\": 82866, \"acRate\": \"31.6%\"}",
    "title_pt": "Jogo Zuma",
    "description_pt": "<p>Você está jogando uma variação do jogo Zuma.</p>\n\n<p>Nesta variação de Zuma, há uma <strong>única linha</strong> de bolas coloridas em um tabuleiro, onde cada bola pode ser colorida de vermelho <code>&#39;R&#39;</code>, amarelo <code>&#39;Y&#39;</code>, azul <code>&#39;B&#39;</code>, verde <code>&#39;G&#39;</code> ou branco <code>&#39;W&#39;</code>. Você também tem várias bolas coloridas em sua mão.</p>\n\n<p>Seu objetivo é <strong>remover todas</strong> as bolas do tabuleiro. Em cada turno:</p>\n\n<ul>\n\t<li>Escolha <strong>qualquer</strong> bola da sua mão e insira-a entre duas bolas na linha ou em qualquer uma das extremidades da linha.</li>\n\t<li>Se houver um grupo de <strong>três ou mais bolas consecutivas</strong> da <strong>mesma cor</strong>, remova o grupo de bolas do tabuleiro.\n\t<ul>\n\t\t<li>Se essa remoção causar a formação de mais grupos de três ou mais bolas da mesma cor, então continue removendo cada grupo até que não reste nenhum.</li>\n\t</ul>\n\t</li>\n\t<li>Se não houver mais bolas no tabuleiro, então você vence o jogo.</li>\n\t<li>Repita esse processo até que você vença ou não tenha mais bolas em sua mão.</li>\n</ul>\n\n<p>Dada uma string <code>board</code>, representando a linha de bolas no tabuleiro, e uma string <code>hand</code>, representando as bolas em sua mão, retorne <em>o <strong>mínimo</strong> número de bolas que você precisa inserir para remover todas as bolas do tabuleiro. Se você não conseguir remover todas as bolas do tabuleiro usando as bolas em sua mão, retorne </em><code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> board = &quot;WRRBBW&quot;, hand = &quot;RB&quot;\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong> É impossível remover todas as bolas. O melhor que você pode fazer é:\n- Insira &#39;R&#39; de modo que o tabuleiro se torne WRR<u>R</u>BBW. W<u>RRR</u>BBW -&gt; WBBW.\n- Insira &#39;B&#39; de modo que o tabuleiro se torne WBB<u>B</u>W. W<u>BBB</u>W -&gt; WW.\nAinda há bolas restantes no tabuleiro, e você ficou sem bolas para inserir.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> board = &quot;WWRRBBWW&quot;, hand = &quot;WRBRW&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Para deixar o tabuleiro vazio:\n- Insira &#39;R&#39; de modo que o tabuleiro se torne WWRR<u>R</u>BBWW. WW<u>RRR</u>BBWW -&gt; WWBBWW.\n- Insira &#39;B&#39; de modo que o tabuleiro se torne WWBB<u>B</u>WW. WW<u>BBB</u>WW -&gt; <u>WWWW</u> -&gt; vazio.\n2 bolas da sua mão foram necessárias para remover as bolas do tabuleiro.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> board = &quot;G&quot;, hand = &quot;GGGGG&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Para deixar o tabuleiro vazio:\n- Insira &#39;G&#39; de modo que o tabuleiro se torne G<u>G</u>.\n- Insira &#39;G&#39; de modo que o tabuleiro se torne GG<u>G</u>. <u>GGG</u> -&gt; vazio.\n2 bolas da sua mão foram necessárias para remover as bolas do tabuleiro.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= board.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= hand.length &lt;= 5</code></li>\n\t<li><code>board</code> e <code>hand</code> consistem dos caracteres <code>&#39;R&#39;</code>, <code>&#39;Y&#39;</code>, <code>&#39;B&#39;</code>, <code>&#39;G&#39;</code> e <code>&#39;W&#39;</code>.</li>\n\t<li>A linha inicial de bolas no tabuleiro <strong>não</strong> terá nenhum grupo de três ou mais bolas consecutivas da mesma cor.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "491",
    "paidOnly": false,
    "title": "Non-decreasing Subsequences",
    "titleSlug": "non-decreasing-subsequences",
    "url": "https://leetcode.com/problems/non-decreasing-subsequences",
    "description_url": "https://leetcode.com/problems/non-decreasing-subsequences/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>all the different possible non-decreasing subsequences of the given array with at least two elements</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,6,7,7]\n<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,4,3,2,1]\n<strong>Output:</strong> [[4,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 15</code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/non-decreasing-subsequences/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n    ans = []\n\n    def dfs(s: int, path: List[int]) -> None:\n      if len(path) > 1:\n        ans.append(path)\n\n      used = set()\n\n      for i in range(s, len(nums)):\n        if nums[i] in used:\n          continue\n        if not path or nums[i] >= path[-1]:\n          used.add(nums[i])\n          dfs(i + 1, path + [nums[i]])\n\n    dfs(0, [])\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<Integer>> findSubsequences(int[] nums) {\n    List<List<Integer>> ans = new LinkedList<>();\n    dfs(nums, 0, new LinkedList<>(), ans);\n    return ans;\n  }\n\n  private void dfs(int[] nums, int s, LinkedList<Integer> path, List<List<Integer>> ans) {\n    if (path.size() > 1)\n      ans.add(new LinkedList<>(path));\n\n    Set<Integer> used = new HashSet<>();\n\n    for (int i = s; i < nums.length; ++i) {\n      if (used.contains(nums[i]))\n        continue;\n      if (path.isEmpty() || nums[i] >= path.getLast()) {\n        used.add(nums[i]);\n        path.addLast(nums[i]);\n        dfs(nums, i + 1, path, ans);\n        path.removeLast();\n      }\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> findSubsequences(vector<int>& nums) {\n    vector<vector<int>> ans;\n    dfs(nums, 0, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(const vector<int>& nums, int s, vector<int>&& path,\n           vector<vector<int>>& ans) {\n    if (path.size() > 1)\n      ans.push_back(path);\n\n    unordered_set<int> used;\n\n    for (int i = s; i < nums.size(); ++i) {\n      if (used.count(nums[i]))\n        continue;\n      if (path.empty() || nums[i] >= path.back()) {\n        used.insert(nums[i]);\n        path.push_back(nums[i]);\n        dfs(nums, i + 1, move(path), ans);\n        path.pop_back();\n      }\n    }\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/491.html",
    "category": "Algorithms",
    "acceptance_rate": 61.57130155077277,
    "topics": [
      "Array",
      "Hash Table",
      "Backtracking",
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 3737,
    "dislikes": 232,
    "similar_questions": "[{\"title\": \"Maximum Length of Pair Chain\", \"titleSlug\": \"maximum-length-of-pair-chain\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"188.4K\", \"totalSubmission\": \"305.9K\", \"totalAcceptedRaw\": 188354, \"totalSubmissionRaw\": 305912, \"acRate\": \"61.6%\"}",
    "title_pt": "Subsequências Não Decrescentes",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>todas as diferentes subsequências não decrescentes possíveis do array dado, com pelo menos dois elementos</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,6,7,7]\n<strong>Saída:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,4,3,2,1]\n<strong>Saída:</strong> [[4,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 15</code></li>\n\t<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "492",
    "paidOnly": false,
    "title": "Construct the Rectangle",
    "titleSlug": "construct-the-rectangle",
    "url": "https://leetcode.com/problems/construct-the-rectangle",
    "description_url": "https://leetcode.com/problems/construct-the-rectangle/description/",
    "description": "<p>A web developer needs to know how to design a web page&#39;s size. So, given a specific rectangular web page&rsquo;s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:</p>\n\n<ol>\n\t<li>The area of the rectangular web page you designed must equal to the given target area.</li>\n\t<li>The width <code>W</code> should not be larger than the length <code>L</code>, which means <code>L &gt;= W</code>.</li>\n\t<li>The difference between length <code>L</code> and width <code>W</code> should be as small as possible.</li>\n</ol>\n\n<p>Return <em>an array <code>[L, W]</code> where <code>L</code> and <code>W</code> are the length and width of the&nbsp;web page you designed in sequence.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> area = 4\n<strong>Output:</strong> [2,2]\n<strong>Explanation:</strong> The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3,  [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> area = 37\n<strong>Output:</strong> [37,1]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> area = 122122\n<strong>Output:</strong> [427,286]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= area &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/construct-the-rectangle/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] constructRectangle(int area) {\n    int width = (int) Math.sqrt(area);\n\n    while (area % width > 0)\n      --width;\n\n    return new int[] {area / width, width};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> constructRectangle(int area) {\n    int width = sqrt(area);\n\n    while (area % width)\n      --width;\n\n    return {area / width, width};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/492.html",
    "category": "Algorithms",
    "acceptance_rate": 60.45115929400106,
    "topics": [
      "Math"
    ],
    "hints": [
      "The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result."
    ],
    "likes": 741,
    "dislikes": 394,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"141.5K\", \"totalSubmission\": \"234.1K\", \"totalAcceptedRaw\": 141521, \"totalSubmissionRaw\": 234108, \"acRate\": \"60.5%\"}",
    "title_pt": "Construir o Retângulo",
    "description_pt": "<p>Um desenvolvedor web precisa saber como projetar o tamanho de uma página web. Portanto, dada a área específica de uma página web retangular, sua tarefa agora é projetar uma página web retangular, cujo comprimento L e largura W satisfaçam os seguintes requisitos:</p>\n\n<ol>\n\t<li>A área da página web retangular que você projetou deve ser igual à área-alvo dada.</li>\n\t<li>A largura <code>W</code> não deve ser maior do que o comprimento <code>L</code>, o que significa <code>L &gt;= W</code>.</li>\n\t<li>A diferença entre o comprimento <code>L</code> e a largura <code>W</code> deve ser a menor possível.</li>\n</ol>\n\n<p>Retorne <em>um array <code>[L, W]</code> em que <code>L</code> e <code>W</code> são, em sequência, o comprimento e a largura da&nbsp;página web que você projetou.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> area = 4\n<strong>Saída:</strong> [2,2]\n<strong>Explicação:</strong> A área-alvo é 4, e todas as formas possíveis de construí-la são [1,4], [2,2], [4,1]. \nMas, de acordo com o requisito 2, [1,4] é ilegal; de acordo com o requisito 3,  [4,1] não é ótimo em comparação com [2,2]. Portanto, o comprimento L é 2, e a largura W é 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> area = 37\n<strong>Saída:</strong> [37,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> area = 122122\n<strong>Saída:</strong> [427,286]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= area &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: W é sempre menor ou igual à raiz quadrada da área, então começamos a busca em sqrt(area) até encontrarmos o resultado."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "493",
    "paidOnly": false,
    "title": "Reverse Pairs",
    "titleSlug": "reverse-pairs",
    "url": "https://leetcode.com/problems/reverse-pairs",
    "description_url": "https://leetcode.com/problems/reverse-pairs/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the number of <strong>reverse pairs</strong> in the array</em>.</p>\n\n<p>A <strong>reverse pair</strong> is a pair <code>(i, j)</code> where:</p>\n\n<ul>\n\t<li><code>0 &lt;= i &lt; j &lt; nums.length</code> and</li>\n\t<li><code>nums[i] &gt; 2 * nums[j]</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,2,3,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The reverse pairs are:\n(1, 4) --&gt; nums[1] = 3, nums[4] = 1, 3 &gt; 2 * 1\n(3, 4) --&gt; nums[3] = 3, nums[4] = 1, 3 &gt; 2 * 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,4,3,5,1]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The reverse pairs are:\n(1, 4) --&gt; nums[1] = 4, nums[4] = 1, 4 &gt; 2 * 1\n(2, 4) --&gt; nums[2] = 3, nums[4] = 1, 3 &gt; 2 * 1\n(3, 4) --&gt; nums[3] = 5, nums[4] = 1, 5 &gt; 2 * 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-pairs/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int reversePairs(vector<int>& nums) {\n    int ans = 0;\n    mergeSort(nums, 0, nums.size() - 1, ans);\n    return ans;\n  }\n\n private:\n  void mergeSort(vector<int>& nums, int l, int r, int& ans) {\n    if (l >= r)\n      return;\n\n    const int m = (l + r) / 2;\n    mergeSort(nums, l, m, ans);\n    mergeSort(nums, m + 1, r, ans);\n    merge(nums, l, m, r, ans);\n  }\n\n  void merge(vector<int>& nums, int l, int m, int r, int& ans) {\n    const int lo = m + 1;\n    int hi = m + 1;  // 1st index s.t. nums[i] <= 2 * nums[hi]\n\n    // For each index i in range [l, m], add hi - lo to ans\n    for (int i = l; i <= m; ++i) {\n      while (hi <= r && nums[i] > 2L * nums[hi])\n        ++hi;\n      ans += hi - lo;\n    }\n\n    vector<int> sorted(r - l + 1);\n    int k = 0;      // sorted's index\n    int i = l;      // left's index\n    int j = m + 1;  // right's index\n\n    while (i <= m && j <= r)\n      if (nums[i] < nums[j])\n        sorted[k++] = nums[i++];\n      else\n        sorted[k++] = nums[j++];\n\n    // Put possible remaining left part to the sorted array\n    while (i <= m)\n      sorted[k++] = nums[i++];\n\n    // Put possible remaining right part to the sorted array\n    while (j <= r)\n      sorted[k++] = nums[j++];\n\n    copy(begin(sorted), end(sorted), begin(nums) + l);\n  }\n};",
    "solution_code_java": "\t\t\t\n\nstruct SegmentTreeNode {\n  int lo;\n  int hi;\n  int sum;\n  SegmentTreeNode* left;\n  SegmentTreeNode* right;\n  SegmentTreeNode(int lo, int hi, int sum, SegmentTreeNode* left = nullptr,\n                  SegmentTreeNode* right = nullptr)\n      : lo(lo), hi(hi), sum(sum), left(left), right(right) {}\n  ~SegmentTreeNode() {\n    delete left;\n    delete right;\n    left = nullptr;\n    right = nullptr;\n  }\n};\n\nclass SegmentTree {\n public:\n  SegmentTree(const vector<int>& nums)\n      : root(build(nums, 0, nums.size() - 1)) {}\n\n  void update(int i, int val) {\n    update(root.get(), i, val);\n  }\n\n  int sumRange(int i, int j) const {\n    return sumRange(root.get(), i, j);\n  }\n\n private:\n  std::unique_ptr<SegmentTreeNode> root;\n\n  SegmentTreeNode* build(const vector<int>& nums, int lo, int hi) const {\n    if (lo == hi)\n      return new SegmentTreeNode(lo, hi, nums[lo]);\n    const int mid = (lo + hi) / 2;\n    auto left = build(nums, lo, mid);\n    auto right = build(nums, mid + 1, hi);\n    return new SegmentTreeNode(lo, hi, left->sum + right->sum, left, right);\n  }\n\n  void update(SegmentTreeNode* root, int i, int val) {\n    if (root->lo == i && root->hi == i) {\n      root->sum += val;\n      return;\n    }\n    const int mid = (root->lo + root->hi) / 2;\n    if (i <= mid)\n      update(root->left, i, val);\n    else\n      update(root->right, i, val);\n    root->sum = root->left->sum + root->right->sum;\n  }\n\n  int sumRange(SegmentTreeNode* root, int i, int j) const {\n    if (root->lo == i && root->hi == j)\n      return root->sum;\n    const int mid = (root->lo + root->hi) / 2;\n    if (j <= mid)\n      return sumRange(root->left, i, j);\n    if (i > mid)\n      return sumRange(root->right, i, j);\n    return sumRange(root->left, i, mid) + sumRange(root->right, mid + 1, j);\n  }\n};\n\nclass Solution {\n public:\n  int reversePairs(vector<int>& nums) {\n    int ans = 0;\n    unordered_map<long, int> ranks;\n    getRanks(nums, ranks);\n    SegmentTree tree(vector<int>(ranks.size() + 1));\n\n    for (int i = nums.size() - 1; i >= 0; --i) {\n      const long num = nums[i];\n      ans += tree.sumRange(0, ranks[num] - 1);\n      tree.update(ranks[num * 2], 1);\n    }\n\n    return ans;\n  }\n\n private:\n  void getRanks(const vector<int>& nums, unordered_map<long, int>& ranks) {\n    set<long> sorted(begin(nums), end(nums));\n    for (const long num : nums)\n      sorted.insert(num * 2);\n    int rank = 0;\n    for (const long num : sorted)\n      ranks[num] = ++rank;\n  }\n};",
    "solution_code_cpp": "\t\t\t\n\nclass FenwickTree {\n public:\n  FenwickTree(int n) : sums(n + 1) {}\n\n  void update(int i, int delta) {\n    while (i < sums.size()) {\n      sums[i] += delta;\n      i += lowbit(i);\n    }\n  }\n\n  int get(int i) const {\n    int sum = 0;\n    while (i > 0) {\n      sum += sums[i];\n      i -= lowbit(i);\n    }\n    return sum;\n  }\n\n private:\n  vector<int> sums;\n\n  static inline int lowbit(int i) {\n    return i & -i;\n  }\n};\n\nclass Solution {\n public:\n  int reversePairs(vector<int>& nums) {\n    int ans = 0;\n    unordered_map<long, int> ranks;\n    getRanks(nums, ranks);\n    FenwickTree tree(ranks.size());\n\n    for (int i = nums.size() - 1; i >= 0; --i) {\n      const long num = nums[i];\n      ans += tree.get(ranks[num] - 1);\n      tree.update(ranks[num * 2], 1);\n    }\n\n    return ans;\n  }\n\n private:\n  void getRanks(const vector<int>& nums, unordered_map<long, int>& ranks) {\n    set<long> sorted(begin(nums), end(nums));\n    for (const long num : nums)\n      sorted.insert(num * 2);\n    int rank = 0;\n    for (const long num : sorted)\n      ranks[num] = ++rank;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/493.html",
    "category": "Algorithms",
    "acceptance_rate": 31.956017630564926,
    "topics": [
      "Array",
      "Binary Search",
      "Divide and Conquer",
      "Binary Indexed Tree",
      "Segment Tree",
      "Merge Sort",
      "Ordered Set"
    ],
    "hints": [
      "Use the merge-sort technique.",
      "Divide the array into two parts and sort them.",
      "For each integer in the first part, count the number of integers that satisfy the condition from the second part. Use the pointer to help you in the counting process."
    ],
    "likes": 6515,
    "dislikes": 282,
    "similar_questions": "[{\"title\": \"Count of Smaller Numbers After Self\", \"titleSlug\": \"count-of-smaller-numbers-after-self\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count of Range Sum\", \"titleSlug\": \"count-of-range-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"258.2K\", \"totalSubmission\": \"808.1K\", \"totalAcceptedRaw\": 258246, \"totalSubmissionRaw\": 808130, \"acRate\": \"32.0%\"}",
    "title_pt": "Pares Reversos",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o número de <strong>pares reversos</strong> no array</em>.</p>\n\n<p>Um <strong>par reverso</strong> é um par <code>(i, j)</code> em que:</p>\n\n<ul>\n\t<li><code>0 &lt;= i &lt; j &lt; nums.length</code> e</li>\n\t<li><code>nums[i] &gt; 2 * nums[j]</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,2,3,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Os pares reversos são:\n(1, 4) --&gt; nums[1] = 3, nums[4] = 1, 3 &gt; 2 * 1\n(3, 4) --&gt; nums[3] = 3, nums[4] = 1, 3 &gt; 2 * 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,4,3,5,1]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os pares reversos são:\n(1, 4) --&gt; nums[1] = 4, nums[4] = 1, 4 &gt; 2 * 1\n(2, 4) --&gt; nums[2] = 3, nums[4] = 1, 3 &gt; 2 * 1\n(3, 4) --&gt; nums[3] = 5, nums[4] = 1, 5 &gt; 2 * 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": [
      "Use a técnica de merge-sort.",
      "Divida o array em duas partes e ordene-as.",
      "Para cada inteiro na primeira parte, conte o número de inteiros que satisfazem a condição da segunda parte. Use o ponteiro para ajudar você no processo de contagem."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "494",
    "paidOnly": false,
    "title": "Target Sum",
    "titleSlug": "target-sum",
    "url": "https://leetcode.com/problems/target-sum",
    "description_url": "https://leetcode.com/problems/target-sum/description/",
    "description": "<p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>\n\n<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code> before each integer in nums and then concatenate all the integers.</p>\n\n<ul>\n\t<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>&#39;+&#39;</code> before <code>2</code> and a <code>&#39;-&#39;</code> before <code>1</code> and concatenate them to build the expression <code>&quot;+2-1&quot;</code>.</li>\n</ul>\n\n<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,1,1,1], target = 3\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1], target = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>0 &lt;= sum(nums[i]) &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= target &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/target-sum/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nWe are given a list of numbers, `nums`, and a `target` value. Our task is to figure out how many ways we can add plus or minus signs in front of the numbers in `nums` to get the `target` value, while keeping the order of the numbers the same.\n\nLet's consider an example where `nums = [2, 1]` and `target = 1`.\n\nThe possible expressions from this are:\n1. `+2 - 1 = 1` → **matches the target**.  \n2. `-2 + 1 = -1` → does not match.  \n3. `+2 + 1 = 3` → does not match.  \n4. `-2 - 1 = -3` → does not match.  \n\nSo, there’s only one way (`+2 - 1`) to get the target value `1`.\n\n> Note: We need to use all the elements of the `nums` array.\n\n---\n\n### Approach 1: Brute Force\n\n#### Intuition\n\nStart by thinking about how we would manually solve this problem. We would consider each number and decide whether to add it or subtract it. This decision-making process can be modeled using recursion.\n\nWe start by defining a recursive function that takes the current index in the list, the current sum of the expression, and the target. For each number, we make two recursive calls: one where we add the number and one where we subtract it. \n\nWhen we reach the end of the list (i.e., all numbers have been considered), we check if the current sum equals the target. If it does, we increment a counter that tracks the number of valid expressions for that route. We repeat this for every route and find the total number of ways. \n\nWhile this works for small inputs, it becomes impractical for larger lists due to its exponential time complexity ($2^n$).\n\n> For a more comprehensive understanding of recursion, check out the [Recursion Explore Card 🔗](https://leetcode.com/explore/learn/card/recursion-i/). This resource provides an in-depth look at recursion, explaining its key concepts and applications with a variety of problems to solidify understanding of the pattern.\n\n#### Algorithm\n\n- Initialize `totalWays` to 0 to track the number of ways to reach the target sum.\n\n- Call `calculateWays` with the initial parameters: `nums`, `currentIndex = 0`, `currentSum = 0`, `target`, to start the recursive process.\n\n- In the `calculateWays` function:\n  - If `currentIndex` equals the length of `nums`:\n    - Check if `currentSum` matches `target`:\n      - If yes, increment `totalWays` by 1 (a valid way to reach the target sum).\n  - Otherwise:\n    - Include the number at `currentIndex` with a positive sign:\n      - Recursively call `calculateWays` with `currentIndex + 1` and `currentSum + nums[currentIndex]`.\n    - Include the current number at `currentIndex` with a negative sign:\n      - Recursively call `calculateWays` with `currentIndex + 1` and `currentSum - nums[currentIndex]`.\n\n- Return `totalWays` after all recursive calls, representing the total number of ways to assign signs to reach the target sum.\n\n#### Implementation\n\n> Note: The Python3 solution gets a TLE.\n\n<iframe src=\"https://leetcode.com/playground/gAErDNjQ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gAErDNjQ\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the input array `nums`.\n\n- Time complexity: $O(2^n)$\n\n    The function `calculateWays` is a recursive function that branches out into two recursive calls at each step. This is because each element in the array can either be added or subtracted, leading to $2$ choices for each of the $n$ elements. \n    \n    This results in a binary tree of recursive calls, where each level of the tree corresponds to a position in the array `nums`. Since there are $n$ elements in the array, the maximum depth of the recursion tree is $n$. Therefore, the total number of recursive calls is $2^n$, leading to a time complexity of $O(2^n)$.\n\n- Space complexity: $O(n)$\n\n    The space complexity is determined by the depth of the recursion stack. In the worst case, the recursion stack can go as deep as $n$ levels (one level for each element in the array). Therefore, the space complexity is $O(n)$.\n \n---\n\n### Approach 2: Recursion with Memoization\n\n#### Intuition\n\nBuilding on the brute force approach, we can say that it has many subproblems that are being solved repeatedly. To understand this redundancy, let's consider a simple example.\n\nSuppose we have the list `nums = [1, 1, 1, 1, 1]` and the target `target = 3`.\n\nIn the brute force approach, we would explore all possible combinations of signs:\n- `+1 +1 +1 +1 +1`\n- `+1 +1 +1 +1 -1`\n- `+1 +1 +1 -1 +1`\n- `+1 +1 -1 +1 +1`\n- `+1 -1 +1 +1 +1`\n- `-1 +1 +1 +1 +1`\n- ...\n\nLet's focus on a specific subproblem: reaching a sum of `2` using the first four numbers `[1, 1, 1, 1]`.\n\n1. Combination 1: `+1 +1 +1 -1 +1`\n   - The sum of the first three numbers is `3`.\n   - The sum of the first four numbers is `2` (since `3 - 1 = 2`).\n\n2. Combination 2: `+1 +1 -1 +1 +1`\n   - The sum of the first three numbers is `1`.\n   - The sum of the first four numbers is `2` (since `1 + 1 = 2`).\n\n3. Combination 3: `+1 -1 +1 +1 +1`\n   - The sum of the first three numbers is `1`.\n   - The sum of the first four numbers is `2` (since `1 + 1 = 2`).\n\nIn each of these combinations, we encounter the subproblem of reaching a sum of `2` using the first four numbers multiple times. Specifically, the subproblem of reaching a sum of `2` using the first four numbers `[1, 1, 1, -1]` or `[1, 1, -1, 1]` is solved repeatedly.\n\nAnother example can be given with `nums = [a, b, c]`. \n\nHere is the corresponding recursion tree:\n```\n├── (+a)\n│   ├── (+b)^\n│   │   ├── (+c)\n│   │   └── (-c)\n│   └── (-b)~\n│       ├── (+c)\n│       └── (-c)\n└── (-a)\n    ├── (+b)^\n    │   ├── (+c)\n    │   └── (-c)\n    └── (-b)~\n        ├── (+c)\n        └── (-c)\n```\n\nAs illustrated, the subtrees marked by `^` and `~` are solved twice.\n\nTo avoid this redundancy, we introduce a memoization table (a 2D array) where `memo[index][currentSum]` stores the number of ways to reach the target starting from the `index` with the `currentSum`.\n\nBefore making recursive calls, we check if the result for the current `index` and `currentSum` is already computed. If it is, we return the stored result instead of recalculating it. After computing the result for a given `index` and `currentSum`, we store it in the memoization table for future reference.\n\nFor example, after calculating the number of ways to reach a sum of `2` using the first four numbers, we store this result in the memoization table. The next time we encounter this subproblem, we simply retrieve the stored result instead of recalculating it. This reduces the time complexity from exponential to polynomial.\n\n#### Algorithm\n\n- Calculate `totalSum`, the sum of all elements in the array `nums`.\n- Initialize a 2D array `memo` of size `[nums.length][2 * totalSum + 1]` to store intermediate results, and fill it with minimum value to indicate uncomputed states. Possible sums are shifted by `totalSum` to handle negative indices.\n\n- Call `calculateWays` with the initial parameters: `nums`, `currentIndex = 0`, `currentSum = 0`, `target`, and `memo`.\n\n- In the `calculateWays` function:\n  - If `currentIndex` equals `nums.length`:\n    - Check if `currentSum` equals `target`:\n      - Return 1 if they match, as this represents a valid way to reach the target sum.\n      - Otherwise, return 0.\n\n  - If the result for the current state (`currentIndex` and `currentSum`) is already computed in `memo`:\n    - Return the stored result from `memo`.\n\n  - Recursively calculate the number of ways:\n    - Add the current number (`nums[currentIndex]`) to `currentSum` and call `calculateWays` for the next index.\n    - Subtract the current number (`nums[currentIndex]`) from `currentSum` and call `calculateWays` for the next index.\n\n  - Store the sum of the results from both recursive calls in `memo[currentIndex][currentSum + totalSum]` to avoid recomputing.\n  - Return the stored result from `memo`.\n\n- Return the result of the initial call to `calculateWays`, which represents the total number of ways to reach the target sum.\n\n#### Implementation\n\n> Instead of using the range $[-\\text{totalSum}, +\\text{totalSum}]$, which is not possible in an array due to negative indices, we shift the range by adding $\\text{totalSum}$ to both the lower and upper bounds. This transformation changes the range to $[-\\text{totalSum} + \\text{totalSum}, \\text{totalSum} + \\text{totalSum}]$, which simplifies to $[0, 2 \\times \\text{totalSum}]$.\n\n<iframe src=\"https://leetcode.com/playground/7CJP4uAJ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"7CJP4uAJ\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the input array `nums`.\n\n- Time complexity: $O(n \\cdot \\text{totalSum})$\n\n    In the worst case, the function `calculateWays` is called for each index in the array and each possible sum within the range $[-\\text{totalSum}, \\text{totalSum}]$. Since the sum can range from $-\\text{totalSum}$ to $\\text{totalSum}$, there are $2 \\cdot \\text{totalSum} + 1$ possible sums.\n    \n    Therefore, the total number of unique states (index, sum) is $n \\times (2 \\cdot \\text{totalSum} + 1)$. Each state is computed once and stored in the memoization table, leading to a time complexity of $O(n \\cdot \\text{totalSum})$.\n\n- Space complexity: $O(n \\cdot \\text{totalSum})$\n\n    The space complexity is determined by the memoization table, which has dimensions $n \\times (2 \\cdot \\text{totalSum} + 1)$. Additionally, the recursion stack can go as deep as $n$, but this is typically dominated by the space used by the memoization table. Therefore, the space complexity is $O(n \\cdot \\text{totalSum})$.\n\n    The space complexity also includes the space used by the built-in functions, such as computing the sum and filling the rows. However, these operations are linear in terms of the input size and do not significantly affect the overall space complexity, which is dominated by the memoization table.\n\n---\n\n### Approach 3: 2D Dynamic Programming\n\n#### Intuition\n\nDynamic programming (DP) is a technique that solves problems by breaking them down into simpler subproblems and solving each subproblem only once. We create a 2D DP table where `dp[index][sum]` represents the number of ways to reach the sum `sum` using the first `index` numbers.\n\nSuppose we have the list `nums = [1, 1, 1, 1, 1]` and the target `target = 3`.\n\nWe initialize the first row of the DP table. For the first number, there is exactly one way to reach the sum equal to the number itself (either by adding or subtracting it). In our example, we initialize `dp[0][1 + totalSum] = 1` and `dp[0][-1 + totalSum] = 1`.\n\nFor each subsequent number, we update the DP table based on the previous row. For each possible sum, we add the number of ways to reach that sum by either adding or subtracting the current number. For example, if we are at the second number `1`, we update the DP table based on the first row:\n- If the previous sum was `0` (i.e., `dp[0][0 + totalSum] = 1`), we can reach a sum of `1` by adding the current number (`1 + 1 = 2`) or a sum of `-1` by subtracting the current number (`1 - 1 = 0`).\n\nWe continue this process for each number in the list. The value at `dp[nums.length - 1][target + totalSum]` gives the number of ways to reach the target sum using all numbers. This approach efficiently computes the number of valid expressions by leveraging the results of previously solved subproblems. \n\nThe animation below shows how various sums are generated, along with the corresponding indices. The example assumes that the sum values lie in the range of `-6` to `+6`, just for the purpose of illustration.\n\n!?!../Documents/494/494_Target_Sum_slides.json:1280,720!?!\n\n> For a more comprehensive understanding of dynamic programming, check out the [Dynamic Programming Explore Card 🔗](https://leetcode.com/explore/learn/card/dynamic-programming/). This resource provides an in-depth look at dynamic programming, explaining its key concepts and applications with a variety of problems to solidify understanding of the pattern.\n\n#### Algorithm\n\n- Compute `totalSum` as the sum of all elements in the `nums` array.\n- Initialize a 2D `dp` array with dimensions `[nums.length][2 * totalSum + 1]` to represent possible sums shifted by `totalSum` (to handle negative indices).\n\n- Set up the base case for the first row of the DP table:\n  - Add 1 to `dp[0][nums[0] + totalSum]` to account for adding the first number.\n  - Add 1 to `dp[0][-nums[0] + totalSum]` to account for subtracting the first number (handle duplicate cases).\n\n- Iterate through the remaining numbers in the `nums` array:\n  - For each possible sum `sum` in the range `-totalSum` to `totalSum`:\n    - If `dp[index - 1][sum + totalSum] > 0` (i.e., the sum is achievable from previous numbers):\n      - Add its value to `dp[index][sum + nums[index] + totalSum]` (sum achieved by adding the current number).\n      - Add its value to `dp[index][sum - nums[index] + totalSum]` (sum achieved by subtracting the current number).\n\n- Check if the absolute value of the `target` exceeds `totalSum`:\n  - If yes, return 0 (the target is unachievable).\n  - Otherwise, return `dp[nums.length - 1][target + totalSum]`, which contains the number of ways to achieve the `target`.\n\n#### Implementation\n\n> Like in the previous approach, we shift the range of possible sums by adding $\\text{totalSum}$ to both the lower and upper bounds, in order to avoid negative indices.\n\n<iframe src=\"https://leetcode.com/playground/iY7GEgWd/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"iY7GEgWd\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the input array `nums`.\n\n- Time complexity: $O(n \\cdot \\text{totalSum})$\n\n    The time complexity is determined by the nested loops in the function. The outer loop runs $n$ times (once for each element in `nums`), and the inner loop runs $2 \\cdot \\text{totalSum} + 1$ times (once for each possible sum from $-\\text{totalSum}$ to $\\text{totalSum}$).\n\n    Therefore, the overall time complexity is $O(n \\cdot \\text{totalSum})$.\n\n- Space complexity: $O(n \\cdot \\text{totalSum})$\n\n    The space complexity is determined by the size of the DP table `dp`, which is a 2D array of size $n \\times (2 \\cdot \\text{totalSum} + 1)$. Each entry in the DP table requires constant space, so the total space complexity is $O(n \\cdot \\text{totalSum})$.\n\n    Additionally, the space complexity includes the space required for the input array `nums`, which is $O(n)$. However, since $O(n \\cdot \\text{totalSum})$ dominates $O(n)$, the overall space complexity is $O(n \\cdot \\text{totalSum})$.\n \n---\n\n### Approach 4: Space Optimized\n\n#### Intuition\n\nIn the previous DP approach, the table `dp[index][sum]` stores the number of ways to reach the sum `sum` using the first `index` numbers. Each entry in the table is calculated based on the entries from the previous row. Specifically, to calculate `dp[index][sum]`, we only need values from the previous row:  \n- `dp[index-1][sum - nums[index]]` (subtracting the current number)  \n- `dp[index-1][sum + nums[index]]` (adding the current number).  \n\nSuppose we have the list `nums = [1, 1, 1, 1, 1]` and the target `target = 3`.\n\nIn the 2D DP table, the calculation for `dp[2][3]` (number of ways to reach a sum of `3` using the first three numbers) depends on:\n- `dp[1][3 - 1]` (number of ways to reach a sum of `2` using the first two numbers)\n- `dp[1][3 + 1]` (number of ways to reach a sum of `4` using the first two numbers)\n\nThis dependency shows that each row in the 2D DP table only depends on the previous row. Once we have calculated the values for `dp[index - 1]`, we no longer need the values from `dp[index - 2]` or any earlier rows. Thus, instead of maintaining a full 2D table, we update a single array as we process each number in the list.\n\nWe initialize the DP array with the first number. For the first number `1`, we initialize `dp[1 + totalSum] = 1` and `dp[-1 + totalSum] = 1`.\n\nFor each subsequent number, we create a new array and update it based on the previous array. This avoids the need to store the entire 2D table. For each possible sum, we update the new array by adding the number of ways to reach that sum by either adding or subtracting the current number. For example, if we are at the second number `1`, we update the new array based on the previous array:\n- If the previous sum was `0` (i.e., `dp[0 + totalSum] = 1`), we can reach a sum of `1` by adding the current number (`0 + 1 = 1`) or a sum of `-1` by subtracting the current number (`0 - 1 = -1`).\n\nWe continue this process for each number in the list. The value at `dp[target + totalSum]` gives the number of ways to reach the target sum using all numbers.\n\n#### Algorithm\n\n- Calculate the `totalSum` as the sum of all elements in the array `nums`.\n\n- Create a `dp` array of size `2 * totalSum + 1` to track the number of ways to achieve each possible sum, offset by `totalSum` to handle negative indices.\n\n- Initialize the first row of the DP table:\n  - Set `dp[nums[0] + totalSum] = 1` for adding the first number.\n  - Increment `dp[-nums[0] + totalSum]` by 1 for subtracting the first number (handles duplicates).\n\n- Iterate through the rest of the `nums` array:\n  - For each index in `nums`, create a `next` array to represent the next state of the DP table.\n  - For each possible `sum` in the range `[-totalSum, totalSum]`:\n    - If the current sum `dp[sum + totalSum]` has valid ways:\n      - Add the number at `nums[index]` to the current sum and update `next[sum + nums[index] + totalSum]`.\n      - Subtract the number at `nums[index]` from the current sum and update `next[sum - nums[index] + totalSum]`.\n  - Replace `dp` with `next` to move to the next state.\n\n- After processing all numbers, check if the target is within the valid range of `[-totalSum, totalSum]`:\n  - If the `target` is out of range, return 0 (no valid ways exist).\n  - Otherwise, return `dp[target + totalSum]`, which gives the number of ways to achieve the target sum.\n\n- The final result represents the number of ways to assign `+` or `-` to elements in `nums` to achieve the `target`.\n\n#### Implementation\n\n> Note: The line `dp[-nums[0] + totalSum] += 1` ensures that if the first number is `0`, both `+0` and `-0` are counted as valid sums. This is crucial because for `nums[0] = 0`, both adding and subtracting `0` result in the sum of `0`. \n\n<iframe src=\"https://leetcode.com/playground/cSYY4EQu/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"cSYY4EQu\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the input array `nums`.\n\n- Time complexity: $O(n \\cdot \\text{totalSum})$\n\n    The algorithm iterates through each element of the array `nums` once, and for each element, it iterates through all possible sums from $- \\text{totalSum}$ to $\\text{totalSum}$. The `totalSum` is the sum of all elements in the array `nums`, which is $O(n)$ in terms of the number of elements. \n    \n    Therefore, the overall time complexity is $O(n \\cdot \\text{totalSum})$.\n\n- Space complexity: $O(2 \\cdot \\text{totalSum}) \\approx O(\\text{totalSum})$\n\n    The space complexity is dominated by the dynamic programming table, which stores values for sums in the range from `-totalSum` to `totalSum`. This means the DP table has a size of $2 \\cdot \\text{totalSum} + 1$, or $O(2 \\cdot \\text{totalSum})$.\n\n    Additionally, there is an extra array `next` that is used to store the results of the next state, which also requires $O(2 \\cdot \\text{totalSum})$ space.\n\n    Thus, the overall space complexity is $O(2 \\cdot \\text{totalSum}) \\approx O(\\text{totalSum})$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findTargetSumWays(self, nums: List[int], target: int) -> int:\n    summ = sum(nums)\n    if summ < abs(target) or (summ + target) & 1:\n      return 0\n\n    def knapsack(target: int) -> int:\n      # dp[i] := # Of ways to sum to i by nums so far\n      dp = [1] + [0] * summ\n\n      for num in nums:\n        for j in range(summ, num - 1, -1):\n          dp[j] += dp[j - num]\n\n      return dp[target]\n\n    return knapsack((summ + target) // 2)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findTargetSumWays(int[] nums, int target) {\n    final int sum = Arrays.stream(nums).sum();\n    if (sum < Math.abs(target) || (sum + target) % 2 == 1)\n      return 0;\n    return knapsack(nums, (sum + target) / 2);\n  }\n\n  private int knapsack(int[] nums, int target) {\n    final int n = nums.length;\n    // dp[i][j] := # of ways to sum to j by nums[0..i)\n    int[][] dp = new int[n + 1][target + 1];\n    dp[0][0] = 1;\n\n    for (int i = 1; i <= n; ++i) {\n      final int num = nums[i - 1];\n      for (int j = 0; j <= target; ++j)\n        if (j < num)\n          dp[i][j] = dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num];\n    }\n\n    return dp[n][target];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findTargetSumWays(vector<int>& nums, int target) {\n    const int sum = accumulate(begin(nums), end(nums), 0);\n    if (sum < abs(target) || (sum + target) & 1)\n      return 0;\n    return knapsack(nums, (sum + target) / 2);\n  }\n\n private:\n  int knapsack(const vector<int>& nums, int target) {\n    const int n = nums.size();\n    // dp[i][j] := # of ways to sum to j by nums[0..i)\n    vector<vector<int>> dp(n + 1, vector<int>(target + 1));\n    dp[0][0] = 1;\n\n    for (int i = 1; i <= n; ++i) {\n      const int num = nums[i - 1];\n      for (int j = 0; j <= target; ++j)\n        if (j < num)\n          dp[i][j] = dp[i - 1][j];\n        else\n          dp[i][j] = dp[i - 1][j] + dp[i - 1][j - num];\n    }\n\n    return dp[n][target];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/494.html",
    "category": "Algorithms",
    "acceptance_rate": 50.59508028373983,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Backtracking"
    ],
    "hints": [],
    "likes": 11798,
    "dislikes": 392,
    "similar_questions": "[{\"title\": \"Expression Add Operators\", \"titleSlug\": \"expression-add-operators\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Ways to Express an Integer as Sum of Powers\", \"titleSlug\": \"ways-to-express-an-integer-as-sum-of-powers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"874K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 874029, \"totalSubmissionRaw\": 1727497, \"acRate\": \"50.6%\"}",
    "title_pt": "Soma Alvo",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> e um inteiro <code>target</code>.</p>\n\n<p>Você quer construir uma <strong>expressão</strong> a partir de nums adicionando um dos símbolos <code>&#39;+&#39;</code> e <code>&#39;-&#39;</code> antes de cada inteiro em nums e então concatenando todos os inteiros.</p>\n\n<ul>\n\t<li>Por exemplo, se <code>nums = [2, 1]</code>, você pode adicionar um <code>&#39;+&#39;</code> antes de <code>2</code> e um <code>&#39;-&#39;</code> antes de <code>1</code> e concatená-los para construir a expressão <code>&quot;+2-1&quot;</code>.</li>\n</ul>\n\n<p>Retorne o número de <strong>expressões</strong> diferentes que você pode construir, cujo valor seja <code>target</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,1,1,1], target = 3\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Há 5 maneiras de atribuir símbolos para fazer a soma de nums ser target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1], target = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 20</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>0 &lt;= sum(nums[i]) &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= target &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "495",
    "paidOnly": false,
    "title": "Teemo Attacking",
    "titleSlug": "teemo-attacking",
    "url": "https://leetcode.com/problems/teemo-attacking",
    "description_url": "https://leetcode.com/problems/teemo-attacking/description/",
    "description": "<p>Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly <code>duration</code> seconds. More formally, an attack at second <code>t</code> will mean Ashe is poisoned during the <strong>inclusive</strong> time interval <code>[t, t + duration - 1]</code>. If Teemo attacks again <strong>before</strong> the poison effect ends, the timer for it is <strong>reset</strong>, and the poison effect will end <code>duration</code> seconds after the new attack.</p>\n\n<p>You are given a <strong>non-decreasing</strong> integer array <code>timeSeries</code>, where <code>timeSeries[i]</code> denotes that Teemo attacks Ashe at second <code>timeSeries[i]</code>, and an integer <code>duration</code>.</p>\n\n<p>Return <em>the <strong>total</strong> number of seconds that Ashe is poisoned</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> timeSeries = [1,4], duration = 2\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Teemo&#39;s attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> timeSeries = [1,2], duration = 2\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Teemo&#39;s attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= timeSeries.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= timeSeries[i], duration &lt;= 10<sup>7</sup></code></li>\n\t<li><code>timeSeries</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/teemo-attacking/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Approach 1: One pass\n\n**Intuition**\n\nThe problem is an example of merge interval questions which are now [quite popular in Google](https://leetcode.com/discuss/interview-question/280433/Google-or-Phone-screen-or-Program-scheduling).\n\nTypically such problems could be solved in a linear time in the case of sorted input, like [here](https://leetcode.com/articles/insert-interval/), and in $$\\mathcal{O}(N \\log N)$$ time otherwise, [here is an example](https://leetcode.com/articles/merge-intervals/).\n\nHere one deals with a sorted input, and the problem could be solved in one pass with a constant space. The idea is straightforward: consider only the interval between two attacks. Ashe spends in a poisoned condition the whole time interval if this interval is shorter than the poisoning time duration `duration`, and `duration` otherwise. \n\n**Algorithm**\n\n- Initiate total time in poisoned condition `total = 0`.\n\n- Iterate over `timeSeries` list. At each step add to the total time the minimum between interval length and the poisoning time duration `duration`. \n\n- Return `total + duration` to take the last attack into account.  \n \n**Implementation**\n\n![pic](../Figures/495/ashe.png)\n\n<iframe src=\"https://leetcode.com/playground/eYS2y2Uh/shared\" frameBorder=\"0\" width=\"100%\" height=\"242\" name=\"eYS2y2Uh\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$\\mathcal{O}(N)$$, where N is the length of the input list since we iterate the entire list.\n\n* Space complexity: $$\\mathcal{O}(1)$$, it's a constant space solution.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n    if duration == 0:\n      return 0\n\n    ans = 0\n\n    for i in range(0, len(timeSeries) - 1):\n      ans += min(timeSeries[i + 1] - timeSeries[i], duration)\n\n    return ans + duration",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findPoisonedDuration(int[] timeSeries, int duration) {\n    if (duration == 0)\n      return 0;\n\n    int ans = 0;\n\n    for (int i = 0; i + 1 < timeSeries.length; ++i)\n      ans += Math.min(timeSeries[i + 1] - timeSeries[i], duration);\n\n    return ans + duration;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findPoisonedDuration(vector<int>& timeSeries, int duration) {\n    if (duration == 0)\n      return 0;\n\n    int ans = 0;\n\n    for (int i = 0; i + 1 < timeSeries.size(); ++i)\n      ans += min(timeSeries[i + 1] - timeSeries[i], duration);\n\n    return ans + duration;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/495.html",
    "category": "Algorithms",
    "acceptance_rate": 56.910813609559185,
    "topics": [
      "Array",
      "Simulation"
    ],
    "hints": [],
    "likes": 1250,
    "dislikes": 138,
    "similar_questions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Can Place Flowers\", \"titleSlug\": \"can-place-flowers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Dota2 Senate\", \"titleSlug\": \"dota2-senate\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"183.6K\", \"totalSubmission\": \"322.5K\", \"totalAcceptedRaw\": 183559, \"totalSubmissionRaw\": 322538, \"acRate\": \"56.9%\"}",
    "title_pt": "Teemo Atacando",
    "description_pt": "<p>Nosso herói Teemo está atacando uma inimiga Ashe com ataques venenosos! Quando Teemo ataca Ashe, Ashe fica envenenada por exatamente <code>duration</code> segundos. Mais formalmente, um ataque no segundo <code>t</code> significará que Ashe está envenenada durante o intervalo de tempo <strong>inclusivo</strong> <code>[t, t + duration - 1]</code>. Se Teemo atacar novamente <strong>antes</strong> de o efeito do veneno terminar, o temporizador é <strong>reiniciado</strong>, e o efeito do veneno terminará <code>duration</code> segundos após o novo ataque.</p>\n\n<p>É dado a você um array inteiro <strong>não decrescente</strong> <code>timeSeries</code>, em que <code>timeSeries[i]</code> denota que Teemo ataca Ashe no segundo <code>timeSeries[i]</code>, e um inteiro <code>duration</code>.</p>\n\n<p>Retorne o <em><strong>total</strong> de segundos durante os quais Ashe está envenenada</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> timeSeries = [1,4], duration = 2\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Os ataques de Teemo em Ashe acontecem da seguinte forma:\n- No segundo 1, Teemo ataca, e Ashe fica envenenada durante os segundos 1 e 2.\n- No segundo 4, Teemo ataca, e Ashe fica envenenada durante os segundos 4 e 5.\nAshe fica envenenada durante os segundos 1, 2, 4 e 5, o que totaliza 4 segundos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> timeSeries = [1,2], duration = 2\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Os ataques de Teemo em Ashe acontecem da seguinte forma:\n- No segundo 1, Teemo ataca, e Ashe fica envenenada durante os segundos 1 e 2.\n- No segundo 2, no entanto, Teemo ataca novamente e reinicia o temporizador do veneno. Ashe fica envenenada durante os segundos 2 e 3.\nAshe fica envenenada durante os segundos 1, 2 e 3, o que totaliza 3 segundos.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= timeSeries.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= timeSeries[i], duration &lt;= 10<sup>7</sup></code></li>\n\t<li><code>timeSeries</code> está ordenado em ordem <strong>não decrescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "496",
    "paidOnly": false,
    "title": "Next Greater Element I",
    "titleSlug": "next-greater-element-i",
    "url": "https://leetcode.com/problems/next-greater-element-i",
    "description_url": "https://leetcode.com/problems/next-greater-element-i/description/",
    "description": "<p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>\n\n<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>\n\n<p>For each <code>0 &lt;= i &lt; nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>\n\n<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]\n<strong>Output:</strong> [-1,3,-1]\n<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]\n<strong>Output:</strong> [3,-1]\n<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length &lt;= nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>\n\t<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?",
    "solution_url": "https://leetcode.com/problems/next-greater-element-i/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n    numToNextGreater = {}\n    stack = []\n\n    for num in nums2:\n      while stack and stack[-1] < num:\n        numToNextGreater[stack.pop()] = num\n      stack.append(num)\n\n    return [numToNextGreater.get(num, -1) for num in nums1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] nextGreaterElement(int[] nums1, int[] nums2) {\n    List<Integer> ans = new ArrayList<>();\n    Map<Integer, Integer> numToNextGreater = new HashMap<>();\n    Deque<Integer> stack = new ArrayDeque<>(); // Decreasing stack\n\n    for (final int num : nums2) {\n      while (!stack.isEmpty() && stack.peek() < num)\n        numToNextGreater.put(stack.pop(), num);\n      stack.push(num);\n    }\n\n    for (final int num : nums1)\n      if (numToNextGreater.containsKey(num))\n        ans.add(numToNextGreater.get(num));\n      else\n        ans.add(-1);\n\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {\n    vector<int> ans;\n    unordered_map<int, int> numToNextGreater;\n    stack<int> stack;  // Decreasing stack\n\n    for (const int num : nums2) {\n      while (!stack.empty() && stack.top() < num)\n        numToNextGreater[stack.top()] = num, stack.pop();\n      stack.push(num);\n    }\n\n    for (const int num : nums1)\n      if (numToNextGreater.count(num))\n        ans.push_back(numToNextGreater[num]);\n      else\n        ans.push_back(-1);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/496.html",
    "category": "Algorithms",
    "acceptance_rate": 74.29433689141257,
    "topics": [
      "Array",
      "Hash Table",
      "Stack",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 8813,
    "dislikes": 937,
    "similar_questions": "[{\"title\": \"Next Greater Element II\", \"titleSlug\": \"next-greater-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element III\", \"titleSlug\": \"next-greater-element-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Daily Temperatures\", \"titleSlug\": \"daily-temperatures\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Subarray Ranges\", \"titleSlug\": \"sum-of-subarray-ranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Total Strength of Wizards\", \"titleSlug\": \"sum-of-total-strength-of-wizards\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element IV\", \"titleSlug\": \"next-greater-element-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Remove Nodes From Linked List\", \"titleSlug\": \"remove-nodes-from-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Missing Integer Greater Than Sequential Prefix Sum\", \"titleSlug\": \"smallest-missing-integer-greater-than-sequential-prefix-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 1022363, \"totalSubmissionRaw\": 1376100, \"acRate\": \"74.3%\"}",
    "title_pt": "Próximo Elemento Maior I",
    "description_pt": "<p>O <strong>próximo elemento maior</strong> de algum elemento <code>x</code> em um array é o <strong>primeiro elemento maior</strong> que está <strong>à direita</strong> de <code>x</code> no mesmo array.</p>\n\n<p>Você recebe dois arrays inteiros <strong>distintos indexados em 0</strong>, <code>nums1</code> e <code>nums2</code>, onde <code>nums1</code> é um subconjunto de <code>nums2</code>.</p>\n\n<p>Para cada <code>0 &lt;= i &lt; nums1.length</code>, encontre o índice <code>j</code> tal que <code>nums1[i] == nums2[j]</code> e determine o <strong>próximo elemento maior</strong> de <code>nums2[j]</code> em <code>nums2</code>. Se não houver próximo elemento maior, então a resposta para esta consulta é <code>-1</code>.</p>\n\n<p>Retorne <em>um array </em><code>ans</code><em> de comprimento </em><code>nums1.length</code><em> tal que </em><code>ans[i]</code><em> seja o <strong>próximo elemento maior</strong> conforme descrito acima.</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]\n<strong>Saída:</strong> [-1,3,-1]\n<strong>Explicação:</strong> O próximo elemento maior para cada valor de nums1 é o seguinte:\n- 4 está sublinhado em nums2 = [1,3,<u>4</u>,2]. Não há próximo elemento maior, então a resposta é -1.\n- 1 está sublinhado em nums2 = [<u>1</u>,3,4,2]. O próximo elemento maior é 3.\n- 2 está sublinhado em nums2 = [1,3,4,<u>2</u>]. Não há próximo elemento maior, então a resposta é -1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [2,4], nums2 = [1,2,3,4]\n<strong>Saída:</strong> [3,-1]\n<strong>Explicação:</strong> O próximo elemento maior para cada valor de nums1 é o seguinte:\n- 2 está sublinhado em nums2 = [1,<u>2</u>,3,4]. O próximo elemento maior é 3.\n- 4 está sublinhado em nums2 = [1,2,3,<u>4</u>]. Não há próximo elemento maior, então a resposta é -1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length &lt;= nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os inteiros em <code>nums1</code> e <code>nums2</code> são <strong>únicos</strong>.</li>\n\t<li>Todos os inteiros de <code>nums1</code> também aparecem em <code>nums2</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você conseguiria encontrar uma solução de <code>O(nums1.length + nums2.length)</code>?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "497",
    "paidOnly": false,
    "title": "Random Point in Non-overlapping Rectangles",
    "titleSlug": "random-point-in-non-overlapping-rectangles",
    "url": "https://leetcode.com/problems/random-point-in-non-overlapping-rectangles",
    "description_url": "https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/description/",
    "description": "<p>You are given an array of non-overlapping axis-aligned rectangles <code>rects</code> where <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indicates that <code>(a<sub>i</sub>, b<sub>i</sub>)</code> is the bottom-left corner point of the <code>i<sup>th</sup></code> rectangle and <code>(x<sub>i</sub>, y<sub>i</sub>)</code> is the top-right corner point of the <code>i<sup>th</sup></code> rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.</p>\n\n<p>Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.</p>\n\n<p><strong>Note</strong> that an integer point is a point that has integer coordinates.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(int[][] rects)</code> Initializes the object with the given rectangles <code>rects</code>.</li>\n\t<li><code>int[] pick()</code> Returns a random integer point <code>[u, v]</code> inside the space covered by one of the given rectangles.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg\" style=\"width: 419px; height: 539px;\" />\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\n<strong>Output</strong>\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= rects.length &lt;= 100</code></li>\n\t<li><code>rects[i].length == 4</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= a<sub>i</sub> &lt; x<sub>i</sub> &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= b<sub>i</sub> &lt; y<sub>i</sub> &lt;= 10<sup>9</sup></code></li>\n\t<li><code>x<sub>i</sub> - a<sub>i</sub> &lt;= 2000</code></li>\n\t<li><code>y<sub>i</sub> - b<sub>i</sub> &lt;= 2000</code></li>\n\t<li>All the rectangles do not overlap.</li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self, rects: List[List[int]]):\n    self.rects = rects\n    self.areas = list(itertools.accumulate(\n        [(x2 - x1 + 1) * (y2 - y1 + 1) for x1, y1, x2, y2 in rects]))\n\n  def pick(self) -> List[int]:\n    index = bisect_right(self.areas, randint(0, self.areas[-1] - 1))\n    x1, y1, x2, y2 = self.rects[index]\n    return [randint(x1, x2), randint(y1, y2)]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int[][] rects) {\n    this.rects = rects;\n    areas = new int[rects.length];\n    for (int i = 0; i < rects.length; ++i)\n      areas[i] = getArea(rects[i]) + (i > 0 ? areas[i - 1] : 0);\n  }\n\n  public int[] pick() {\n    final int target = rand.nextInt(areas[areas.length - 1]);\n    final int index = firstGreater(areas, target);\n    final int[] r = rects[index];\n    return new int[] {\n        rand.nextInt(r[2] - r[0] + 1) + r[0],\n        rand.nextInt(r[3] - r[1] + 1) + r[1],\n    };\n  }\n\n  private int[][] rects;\n  private int[] areas;\n  private Random rand = new Random();\n\n  private int getArea(int[] r) {\n    return (r[2] - r[0] + 1) * (r[3] - r[1] + 1);\n  }\n\n  private int firstGreater(int[] areas, int target) {\n    int l = 0;\n    int r = areas.length;\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (areas[m] > target)\n        r = m;\n      else\n        l = m + 1;\n    }\n    return l;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(vector<vector<int>>& rects) : rects(move(rects)) {\n    for (const vector<int>& r : this->rects)\n      areas.push_back(getArea(r));\n    partial_sum(begin(areas), end(areas), begin(areas));\n  }\n\n  vector<int> pick() {\n    const int target = rand() % areas.back();\n    const int index =\n        upper_bound(begin(areas), end(areas), target) - begin(areas);\n    const vector<int>& r = rects[index];\n    return {rand() % (r[2] - r[0] + 1) + r[0],\n            rand() % (r[3] - r[1] + 1) + r[1]};\n  }\n\n private:\n  const vector<vector<int>> rects;\n  vector<int> areas;\n\n  int getArea(const vector<int>& r) {\n    return (r[2] - r[0] + 1) * (r[3] - r[1] + 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/497.html",
    "category": "Algorithms",
    "acceptance_rate": 37.976338322766196,
    "topics": [
      "Array",
      "Math",
      "Binary Search",
      "Reservoir Sampling",
      "Prefix Sum",
      "Ordered Set",
      "Randomized"
    ],
    "hints": [],
    "likes": 502,
    "dislikes": 682,
    "similar_questions": "[{\"title\": \"Random Pick with Weight\", \"titleSlug\": \"random-pick-with-weight\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Generate Random Point in a Circle\", \"titleSlug\": \"generate-random-point-in-a-circle\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"46.5K\", \"totalSubmission\": \"122.4K\", \"totalAcceptedRaw\": 46480, \"totalSubmissionRaw\": 122392, \"acRate\": \"38.0%\"}",
    "title_pt": "Ponto Aleatório em Retângulos Não Sobrepostos",
    "description_pt": "<p>Você recebe um array de retângulos sem sobreposição e alinhados aos eixos <code>rects</code>, em que <code>rects[i] = [a<sub>i</sub>, b<sub>i</sub>, x<sub>i</sub>, y<sub>i</sub>]</code> indica que <code>(a<sub>i</sub>, b<sub>i</sub>)</code> é o ponto do canto inferior esquerdo do <code>i<sup>ésimo</sup></code> retângulo e <code>(x<sub>i</sub>, y<sub>i</sub>)</code> é o ponto do canto superior direito do <code>i<sup>ésimo</sup></code> retângulo. Projete um algoritmo para escolher um ponto inteiro aleatório dentro da área coberta por um dos retângulos dados. Um ponto no perímetro de um retângulo está incluído na área coberta pelo retângulo.</p>\n\n<p>Qualquer ponto inteiro dentro da área coberta por um dos retângulos dados deve ter a mesma probabilidade de ser retornado.</p>\n\n<p><strong>Nota</strong> que um ponto inteiro é um ponto que possui coordenadas inteiras.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(int[][] rects)</code> Inicializa o objeto com os retângulos fornecidos <code>rects</code>.</li>\n\t<li><code>int[] pick()</code> Retorna um ponto inteiro aleatório <code>[u, v]</code> dentro da área coberta por um dos retângulos dados.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/07/24/lc-pickrandomrec.jpg\" style=\"width: 419px; height: 539px;\" />\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\n<strong>Saída</strong>\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= rects.length &lt;= 100</code></li>\n\t<li><code>rects[i].length == 4</code></li>\n\t<li><code>-10<sup>9</sup> &lt;= a<sub>i</sub> &lt; x<sub>i</sub> &lt;= 10<sup>9</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= b<sub>i</sub> &lt; y<sub>i</sub> &lt;= 10<sup>9</sup></code></li>\n\t<li><code>x<sub>i</sub> - a<sub>i</sub> &lt;= 2000</code></li>\n\t<li><code>y<sub>i</sub> - b<sub>i</sub> &lt;= 2000</code></li>\n\t<li>Todos os retângulos não se sobrepõem.</li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas a <code>pick</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "498",
    "paidOnly": false,
    "title": "Diagonal Traverse",
    "titleSlug": "diagonal-traverse",
    "url": "https://leetcode.com/problems/diagonal-traverse",
    "description_url": "https://leetcode.com/problems/diagonal-traverse/description/",
    "description": "<p>Given an <code>m x n</code> matrix <code>mat</code>, return <em>an array of all the elements of the array in a diagonal order</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg\" style=\"width: 334px; height: 334px;\" />\n<pre>\n<strong>Input:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Output:</strong> [1,2,4,7,5,3,6,8,9]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> mat = [[1,2],[3,4]]\n<strong>Output:</strong> [1,2,3,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/diagonal-traverse/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n### Approach 1: Diagonal Iteration and Reversal\n\n**Intuition**\n\nA common strategy for solving a lot of programming problem is to first solve a stripped down, simpler version of them and then think what needs to be changed to achieve the original goal. Our first approach to this problem is also based on this very idea. So, instead of thinking about the zig-zag pattern of printing for the diagonals, let's say the problem statement simply asked us to print out the contents of the matrix, one diagonal after the other starting from the first element. Let's see what this problem would look like. \n\n<center>\n<img src=\"../Figures/498/img1.png\" width=\"600\"/>\n</center>\n\nThe first row and the last column in this problem would serve as the starting point for the corresponding diagonal. Given an element inside a diagonal, say $$[i, j]$$, we can either go up the diagonal by going one row up and one column ahead i.e. $$[i - 1, j + 1]$$ or, we can go down the diagonal by going one row down and one column to the left i.e. $$[i + 1, j - 1]$$. *Note* that this applies to diagonals that go from `right to left` only. The math would change for the ones that go from left to right. \n\nThis is a simple problem to solve, right? The only difference between this one and the original problem is that some of the diagonals are not printed in the right order. That's all we need to fix to get the right solution!\n\n> We simply need to reverse the odd numbered diagonals before we add the elements to the final result array. So, for e.g. the third diagonal starting from the left would be [3, 7, 11] and before we add these elements to the final result array, we simply reverse them i.e. [11, 7, 3]. \n\n**Algorithm**\n\n1. Initialize a `result` array that we will eventually return. \n2. We would have an outer loop that will go over each of the diagonals one by one. As mentioned before, the elements in the first row and the last column would actually be the heads of their corresponding diagonals. \n3. We then have an inner while loop that iterates over all the elements in the diagonal. We can calculate the number of elements in the corresponding diagonal by doing some math but we can simply iterate until one of the indices goes out of bounds.\n4. For each diagonal we will need a new list or dynamic array like data structure since we don't know what size to allocate. Again, we can do some math and calculate the size of that particular diagonal and allocate memory; but it's not necessary for this explanation.  \n5. For odd numbered diagonals, we simply need to add the elements in our intermediary array, in reverse order to the final result array.\n\n    <center>\n    <img src=\"../Figures/498/img2.png\" width=\"500\"/>\n    </center>\n\n<iframe src=\"https://leetcode.com/playground/8NzZyMbU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8NzZyMbU\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N \\cdot M)$$ considering the array has $$N$$ rows and $$M$$ columns. An important thing to remember is that for all the odd numbered diagonals, we will be processing the elements twice since we have to reverse the elements before adding to the result array. Additionally, to save space, we have to `clear` the intermediate array before we process a new diagonal. That operation also takes $$O(K)$$ where $$K$$ is the size of that array. So, we will be processing all the elements of the array at least twice. But, as far as the asymptotic complexity is concerned, it remains the same.\n* Space Complexity: $$O(min(N, M))$$ since the extra space is occupied by the intermediate arrays we use for storing diagonal elements and the maximum it can occupy is the equal to the minimum of $$N$$ and $$M$$. Remember, the diagonal can only extend till one of its indices goes out of scope.\n<br>\n<br>\n\n---\n### Approach 2: Simulation\n\n**Intuition**\n\nThis approach simply and plainly does what the problem statement asks us to do. It's pure simulation. However, in order to implement this simulation, we need to understand the walking patterns inside the array. Basically, in the previous approach, figuring out the `head` of the diagonal was pretty easy. In this case, it won't be that easy. We need to figure out two things for each diagonal:\n\n1. The direction in which we want to process it's elements and\n2. The head or the starting point for the diagonal `depending upon its direction`.\n\nLet's see these two things annotated on a sample matrix. \n\n<center>\n<img src=\"../Figures/498/img3.png\" width=\"600\"/>\n</center>\n\nNow that we know what two things we need to figure out, let's get to the part where we actually do it! The direction is pretty straightforward. We can simply use a boolean variable and keep alternating it to figure out the direction for a diagonal. That part is sorted. The slightly tricky part is figuring out the head of the next diagonal. \n\nThe good part is, we already know the `end` of the previous diagonal. We can use that information to figure out the head of the next diagonal. \n\n**Next head when going UP**<br>\nLet's look at the two scenarios that we may come across when we are at the tail end of a downwards diagonal and we want to find the head of the next diagonal.\n\n<center>\n<img src=\"../Figures/498/img4.png\" width=\"600\"/>\n</center>\n\nSo, the general rule that we will be following when we want to find the head for an upwards going diagonal is that:\n\n> The head would be the node directly below the tail of the previous diagonal. Unless the tail lies in the last row of the matrix in which case the head would be the node right next to the tail.\n\n**Next head when going DOWN** <br>\nLet's look at the two scenarios that we may come across when we are at the tail end of an upwards diagonal and we want to find the head of the next diagonal.\n\n<center>\n<img src=\"../Figures/498/img5.png\" width=\"600\"/>\n</center>\n\nSo, the general rule that we will be following when we want to find the head for a downwards going diagonal is that:\n\n> The head would be the node to the right of the tail of the previous diagonal. Unless the tail lies in the last column of the matrix in which case the head would be the node directly below the tail.\n\n**Algorithm**\n\n1. Initialize a boolean variable called `direction` which will tell us whether the current diagonal is an upwards or downwards going. Based on the current direction and the tail, we will determine the head of the next diagonal. Initially the direction would be `1` which would indicate `up`. We will keep alternating this value from one iteration to the next.\n2. Assuming we know the head of a diagonal, say $$matrix[i][j]$$, we will use the direction to progress along the diagonal and process its elements. \n    - For an upwards going diagonal, the next element in the diagonal would be $$matrix[i - 1][j + 1]$$\n    - For a downwards going diagonal, the next element would be $$matrix[i + 1][j - 1]$$. \n3. We keep processing the elements of the current diagonal until we go out of the boundaries of the matrix. \n4. Now, given that we know the tail of the diagonal (the last node before we went out of bounds), let's see how we can find the next head. Note that in the following pseudocode, the `direction` is for the current diagonal and we are trying to find the head of the next diagonal. So, if the direction is `up`, it means the next diagonal would be going down and vice-versa.\n    <pre>\n   tail = [i, j]\n   if direction == up, then {\n      if [i, j + 1] is within bounds, then {\n          next_head = [i, j + 1]\n      } else { \n          next_head = [i + 1, j]\n      }\n   } else {\n      if [i + 1, j] is within bounds, then {\n          next_head = [i + 1, j]\n      } else { \n          next_head = [i, j + 1]\n      }\n   }</pre>\n    \n5. We keep processing the elements of a diagonal and once the current diagonal ends, we use the current direction and the tail element to find the next head and we switch over to processing the next diagonal. Also remember to flip the direction bit. \n\n<iframe src=\"https://leetcode.com/playground/4fXSDJuN/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4fXSDJuN\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N \\cdot M)$$ since we process each element of the matrix exactly once.\n* Space Complexity: $$O(1)$$ since we don't make use of any additional data structure. Note that the space occupied by the output array doesn't count towards the space complexity since that is a requirement of the problem itself. Space complexity comprises any `additional` space that we may have used to get to build the final array. For the previous solution, it was the intermediate arrays. In this solution, we don't have any additional space apart from a couple of variables.\n<br>\n<br>",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] findDiagonalOrder(int[][] matrix) {\n    final int m = matrix.length;\n    final int n = matrix[0].length;\n    int[] ans = new int[m * n];\n    int d = 1; // Left-bottom -> right-top\n    int row = 0;\n    int col = 0;\n\n    for (int i = 0; i < m * n; ++i) {\n      ans[i] = matrix[row][col];\n      row -= d;\n      col += d;\n      // Out of bound\n      if (row == m) {\n        row = m - 1;\n        col += 2;\n        d = -d;\n      }\n      if (col == n) {\n        col = n - 1;\n        row += 2;\n        d = -d;\n      }\n      if (row < 0) {\n        row = 0;\n        d = -d;\n      }\n      if (col < 0) {\n        col = 0;\n        d = -d;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {\n    const int m = matrix.size();\n    const int n = matrix[0].size();\n    vector<int> ans(m * n);\n    int d = 1;  // Left-bottom -> right-top\n    int row = 0;\n    int col = 0;\n\n    for (int i = 0; i < m * n; ++i) {\n      ans[i] = matrix[row][col];\n      row -= d;\n      col += d;\n      // Out of bound\n      if (row == m)\n        row = m - 1, col += 2, d = -d;\n      if (col == n)\n        col = n - 1, row += 2, d = -d;\n      if (row < 0)\n        row = 0, d = -d;\n      if (col < 0)\n        col = 0, d = -d;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/498.html",
    "category": "Algorithms",
    "acceptance_rate": 62.96871482497725,
    "topics": [
      "Array",
      "Matrix",
      "Simulation"
    ],
    "hints": [],
    "likes": 3642,
    "dislikes": 724,
    "similar_questions": "[{\"title\": \"Decode the Slanted Ciphertext\", \"titleSlug\": \"decode-the-slanted-ciphertext\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"386K\", \"totalSubmission\": \"613K\", \"totalAcceptedRaw\": 386000, \"totalSubmissionRaw\": 613004, \"acRate\": \"63.0%\"}",
    "title_pt": "Percurso em Diagonal",
    "description_pt": "<p>Dada uma matriz <code>m x n</code> <code>mat</code>, retorne <em>um array com todos os elementos do array em ordem diagonal</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/10/diag1-grid.jpg\" style=\"width: 334px; height: 334px;\" />\n<pre>\n<strong>Entrada:</strong> mat = [[1,2,3],[4,5,6],[7,8,9]]\n<strong>Saída:</strong> [1,2,4,7,5,3,6,8,9]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> mat = [[1,2],[3,4]]\n<strong>Saída:</strong> [1,2,3,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= mat[i][j] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "500",
    "paidOnly": false,
    "title": "Keyboard Row",
    "titleSlug": "keyboard-row",
    "url": "https://leetcode.com/problems/keyboard-row",
    "description_url": "https://leetcode.com/problems/keyboard-row/description/",
    "description": "<p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p>\n\n<p><strong>Note</strong> that the strings are <strong>case-insensitive</strong>, both lowercased and uppercased of the same letter are treated as if they are at the same row.</p>\n\n<p>In the <strong>American keyboard</strong>:</p>\n\n<ul>\n\t<li>the first row consists of the characters <code>&quot;qwertyuiop&quot;</code>,</li>\n\t<li>the second row consists of the characters <code>&quot;asdfghjkl&quot;</code>, and</li>\n\t<li>the third row consists of the characters <code>&quot;zxcvbnm&quot;</code>.</li>\n</ul>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/10/12/keyboard.png\" style=\"width: 800px; max-width: 600px; height: 267px;\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>Both <code>&quot;a&quot;</code> and <code>&quot;A&quot;</code> are in the 2nd row of the American keyboard due to case insensitivity.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">words = [&quot;omk&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 20</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 100</code></li>\n\t<li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/keyboard-row/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findWords(self, words: List[str]) -> List[str]:\n    ans = []\n    rows = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')]\n\n    for word in words:\n      lowerWord = set(word.lower())\n      if any(lowerWord <= row for row in rows):\n        ans.append(word)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String[] findWords(String[] words) {\n    List<String> ans = new ArrayList<>();\n    final int[] rows = {2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3,\n                        3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3};\n\n    for (final String word : words) {\n      final String lowerWord = word.toLowerCase();\n      final int row = rows[lowerWord.charAt(0) - 'a'];\n      final boolean isValid = lowerWord.chars().allMatch(c -> rows[c - 'a'] == row);\n      if (isValid)\n        ans.add(word);\n    }\n\n    return ans.toArray(new String[0]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findWords(vector<string>& words) {\n    vector<string> ans;\n    const vector<int> rows{2, 3, 3, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3,\n                           3, 1, 1, 1, 1, 2, 1, 1, 3, 1, 3, 1, 3};\n\n    for (const string& word : words) {\n      string lowerWord = word;\n      transform(begin(lowerWord), end(lowerWord), begin(lowerWord), ::tolower);\n      const int row = rows[lowerWord[0] - 'a'];\n      const bool isValid = all_of(begin(lowerWord), end(lowerWord),\n                                  [&](int c) { return rows[c - 'a'] == row; });\n      if (isValid)\n        ans.push_back(word);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/500.html",
    "category": "Algorithms",
    "acceptance_rate": 72.33892261456376,
    "topics": [
      "Array",
      "Hash Table",
      "String"
    ],
    "hints": [],
    "likes": 1696,
    "dislikes": 1151,
    "similar_questions": "[{\"title\": \"Find the Sequence of Strings Appeared on the Screen\", \"titleSlug\": \"find-the-sequence-of-strings-appeared-on-the-screen\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Original Typed String I\", \"titleSlug\": \"find-the-original-typed-string-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Original Typed String II\", \"titleSlug\": \"find-the-original-typed-string-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"277.5K\", \"totalSubmission\": \"383.7K\", \"totalAcceptedRaw\": 277529, \"totalSubmissionRaw\": 383651, \"acRate\": \"72.3%\"}",
    "title_pt": "Linha do Teclado",
    "description_pt": "<p>Dado um array de strings <code>words</code>, retorne <em>as palavras que podem ser digitadas usando letras do alfabeto em apenas uma linha de um teclado americano, como na imagem abaixo</em>.</p>\n\n<p><strong>Note</strong> que as strings são <strong>case-insensitive</strong>; tanto letras minúsculas quanto maiúsculas da mesma letra são tratadas como se estivessem na mesma linha.</p>\n\n<p>No <strong>teclado americano</strong>:</p>\n\n<ul>\n\t<li>a primeira linha consiste nos caracteres <code>&quot;qwertyuiop&quot;</code>,</li>\n\t<li>a segunda linha consiste nos caracteres <code>&quot;asdfghjkl&quot;</code>, e</li>\n\t<li>a terceira linha consiste nos caracteres <code>&quot;zxcvbnm&quot;</code>.</li>\n</ul>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2018/10/12/keyboard.png\" style=\"width: 800px; max-width: 600px; height: 267px;\" />\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">words = [&quot;Hello&quot;,&quot;Alaska&quot;,&quot;Dad&quot;,&quot;Peace&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[&quot;Alaska&quot;,&quot;Dad&quot;]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>Tanto <code>&quot;a&quot;</code> quanto <code>&quot;A&quot;</code> estão na 2ª linha do teclado americano devido à insensibilidade a maiúsculas e minúsculas.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">words = [&quot;omk&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">words = [&quot;adsdf&quot;,&quot;sfd&quot;]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[&quot;adsdf&quot;,&quot;sfd&quot;]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 20</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 100</code></li>\n\t<li><code>words[i]</code> consiste em letras inglesas (tanto minúsculas quanto maiúsculas).&nbsp;</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "501",
    "paidOnly": false,
    "title": "Find Mode in Binary Search Tree",
    "titleSlug": "find-mode-in-binary-search-tree",
    "url": "https://leetcode.com/problems/find-mode-in-binary-search-tree",
    "description_url": "https://leetcode.com/problems/find-mode-in-binary-search-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary search tree (BST) with duplicates, return <em>all the <a href=\"https://en.wikipedia.org/wiki/Mode_(statistics)\" target=\"_blank\">mode(s)</a> (i.e., the most frequently occurred element) in it</em>.</p>\n\n<p>If the tree has more than one mode, return them in <strong>any order</strong>.</p>\n\n<p>Assume a BST is defined as follows:</p>\n\n<ul>\n\t<li>The left subtree of a node contains only nodes with keys <strong>less than or equal to</strong> the node&#39;s key.</li>\n\t<li>The right subtree of a node contains only nodes with keys <strong>greater than or equal to</strong> the node&#39;s key.</li>\n\t<li>Both the left and right subtrees must also be binary search trees.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg\" style=\"width: 142px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> root = [1,null,2,2]\n<strong>Output:</strong> [2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [0]\n<strong>Output:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).",
    "solution_url": "https://leetcode.com/problems/find-mode-in-binary-search-tree/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nIn this article, we will present many different approaches to solving this problem.\n\nThe level of these approaches varies greatly. Some approaches have different time complexities, while some simply present a different way of attacking the problem.\n\nNote that not all of these approaches will be expected in an interview. At the start of each approach, there will be a comment regarding the difficulty of the approach and if it should be used in an interview.\n\nFor all approaches, we will assume that you are already familiar with how trees are given in LeetCode problems and how to traverse them.\n\n---\n\n### Approach 1: Count Frequency With Hash Map (DFS)\n\n**Intuition**\n\n> This is a great first approach to use in an interview. It is simple, easy to implement, has good complexity, and demonstrates an understanding of binary trees and hash maps. You should be prepared for follow-ups after implementing this solution.\n\nOur goal is to find all the modes in the tree. A mode is a value that has the maximum frequency. Note that there could be multiple modes: for example, if we had the following tree:\n\n![example](../Figures/501/1.png)\n<br>\n\nThe frequency of each value is as follows:\n\n| Value | Frequency |\n|:---:|:---:|\n|  4  | 2  |\n|  7  |  1 |\n|  8  | 2  | \n|  10  | 1 |\n\n<br>\n\nThe maximum frequency is `2`, thus we have two modes: `4` and `8`.\n\nWe can solve this problem by collecting the frequency of all values in the tree, finding the maximum frequency `maxFreq`, then checking which values have a frequency of `maxFreq`.\n\nTo count the frequency of each value, we will perform a depth-first search (DFS) on the tree to visit every node. We can initialize a hash map `counter` before starting the DFS. At each node we visit, we will update the frequency of `node.val` in `counter`.\n\nOnce we have finished the DFS (visited every node), `counter` will hold the frequency of all values. We will save the maximum frequency as `maxFreq`, then iterate over all the elements of `counter` and check which ones have a frequency equal to `maxFreq`. Each of those elements will be in our final answer.\n\n**Algorithm**\n\n1. Initialize a hash map `counter`.\n2. Create a function `dfs(node, counter)`:\n    - If `node` is null, immediately exit the function.\n    - Increment the frequency of `node.val` in `counter`.\n    - Call `dfs` on both children with `dfs(node.left, counter)` and `dfs(node.right, counter)`.\n3. Call `dfs(root, counter)`.\n4. Find the maximum value in `counter` as `maxFreq`.\n5. Initialize the answer list `ans`.\n6. Iterate over all key-value pairs in `counter`. If the value is equal to `maxFreq`, add the key to `ans`.\n7. Return `ans`.\n\n**Implementation**\n\n> In Python, we are using [collections.defaultdict](https://docs.python.org/3/library/collections.html#collections.defaultdict) to make the code cleaner. It is similar to `std::unordered_map` in C++.\n\n<iframe src=\"https://leetcode.com/playground/BH7zk7gP/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"BH7zk7gP\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the DFS, we visit each node once. At each node, we perform $$O(1)$$ work since hash map operations cost $$O(1)$$.\n\n    Next, we find `maxFreq`, which involves iterating over `counter`. In the worst case scenario where the tree has only unique values, `counter` will have a size of $$n$$, and thus this will cost $$O(n)$$.\n\n    Finally, we construct `ans`, which involves iterating over `counter` again. Overall, our time complexity is $$O(n)$$.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(n)$$\n\n    During DFS, recursion is executed using the call stack. This call stack is equal to the depth of the tree, which in the worst case scenario is $$O(n)$$. Also, as mentioned above, if the tree only has unique values then `counter` will have a size of $$n$$. Thus, `counter` also uses $$O(n)$$ space.\n    \n<br/>\n\n---\n\n### Approach 2: Iterative DFS\n\n**Intuition**\n\n> This approach may be asked as a follow-up to the previous approach, or vice-versa if you implement this one first. It is common for interviewers to ask you to solve a problem with DFS both recursively and iteratively.\n\nIn this approach, we will use the same algorithm from the previous approach, except that we will implement the DFS iteratively.\n\nInstead of using recursion, we will use a stack `stack`. Initially, we will have the `root` in the `stack`. Then, we will perform a DFS until the `stack` is empty using a while loop. At each iteration, we pop a `node` from the `stack`. We will increment the frequency of `node` in `counter` just like we did in the previous approach, then push the children of `node` to `stack` if they exist. In this way, we go as deep into the tree as possible before backtracking, similar to node exploration in recursive DFS.\n\nEach iteration of the while loop is analogous to a function call from the previous approach, as we are handling a given `node`.\n\n**Algorithm**\n\n1. Initialize a hash map `counter` and a stack `stack` that contains `root`.\n2. Perform a DFS. While `stack` is not empty:\n    - Pop `node` from the top of `stack`.\n    - Increment the frequency of `node.val` in `counter`.\n    - If `node.left` is not null, push it to `stack`.\n    - If `node.right` is not null, push it to `stack`.\n3. Find the maximum value in `counter` as `maxFreq`.\n4. Initialize the answer list `ans`.\n5. Iterate over all key-value pairs in `counter`. If the value is equal to `maxFreq`, add the key to `ans`.\n6. Return `ans`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/QiC3LGWA/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"QiC3LGWA\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the DFS, we visit each node once. At each node, we perform $$O(1)$$ work since hash map and stack operations cost $$O(1)$$.\n\n    Next, we find `maxFreq`, which involves iterating over `counter`. In the worst case scenario where the tree has only unique values, `counter` will have a size of $$n$$, and thus this will cost $$O(n)$$.\n\n    Finally, we construct `ans`, which involves iterating over `counter` again. Overall, our time complexity is $$O(n)$$.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(n)$$\n\n    During DFS, `stack` may grow to a size of $$O(n)$$. Also, as mentioned above, if the tree only has unique values then `counter` will have a size of $$n$$. Thus, `counter` also uses $$O(n)$$ space.\n    \n<br/>\n\n---\n\n### Approach 3: Breadth First Search (BFS)\n\n**Intuition**\n\n> Again, this approach may be asked as a follow-up if you implemented DFS first, or vice-versa. It is also common for interviewers to ask you to implement both DFS and BFS.\n>\n> We have included approaches 2 and 3 to demonstrate the usage of iterative DFS and BFS to solve this problem. We are able to do this because there isn't really a difference in using recursive DFS, iterative DFS, or BFS for this algorithm - we simply need to visit each node.\n\nIn this approach, we again use the same algorithm from the first two approaches. This time, we will perform the traversal using BFS.\n\nWith BFS, instead of using a stack (or the recursion stack) like in DFS, we use a queue. The main difference is that we handle nodes in a first-in, first-out fashion (FIFO) as opposed to in DFS where we handle nodes in a last-in, first-out (LIFO) fashion. This results in us visiting each node by depth - we can imagine the root at depth `0`, the root's children at depth `1`, the children of those children at depth `2`, and so on.\n\n![example](../Figures/501/bfs.png)\n<br>\n\nWith BFS, we visit all nodes at a depth of `x` before visiting any node at a depth of `x + 1`. While BFS excels over DFS for many problems, in this problem it is just another way for us to perform the traversal. We simply need to visit each node in the tree so that we can record the frequencies in `counter`.\n\n**Algorithm**\n\n1. Initialize a hash map `counter` and a queue `queue` that contains `root`.\n2. Perform a BFS. While `queue` is not empty:\n    - Pop `node` from the front of `queue`.\n    - Increment the frequency of `node.val` in `counter`.\n    - If `node.left` is not null, push it to `queue`.\n    - If `node.right` is not null, push it to `queue`.\n3. Find the maximum value in `counter` as `maxFreq`.\n4. Initialize the answer list `ans`.\n5. Iterate over all key-value pairs in `counter`. If the value is equal to `maxFreq`, add the key to `ans`.\n6. Return `ans`.\n\n\n**Implementation**\n\n> In Python, we are using [collections.deque](https://docs.python.org/3/library/collections.html#collections.deque) to implement an efficient queue.\n\n<iframe src=\"https://leetcode.com/playground/maqHS24V/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"maqHS24V\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the BFS, we visit each node once. At each node, we perform $$O(1)$$ work since hash map and queue operations cost $$O(1)$$. Note that this assumes that the implementation of `queue` is efficient. In the code we presented above, all implementations are efficient.\n\n    Next, we find `maxFreq`, which involves iterating over `counter`. In the worst-case scenario where the tree has only unique values, `counter` will have a size of $$n$$, and thus this will cost $$O(n)$$.\n\n    Finally, we construct `ans`, which involves iterating over `counter` again. Overall, our time complexity is $$O(n)$$.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(n)$$\n\n    During DFS, `queue` may grow to a size of $$O(n)$$. Also, as mentioned above, if the tree only has unique values then `counter` will have a size of $$n$$. Thus, `counter` also uses $$O(n)$$ space.\n    \n<br/>\n\n---\n\n### Approach 4: No Hash-Map\n\n**Intuition**\n\n> This approach is another way to attack the problem compared to the previous three approaches. It is slightly more complex and can be implemented if the interviewer asks for an alternate way to solve the problem. While this approach has the same time and space complexity as the first three, it runs slightly faster as we avoid the overhead associated with hash maps.\n\nSo far, we have not taken advantage of the fact that the input tree is a binary search tree (with duplicates). The first three approaches would work for **any** binary tree.\n\nIf you perform an inorder DFS traversal on a binary search tree (BST), you will handle the nodes in **sorted** order. Why?\n\nRecall that in a BST, all nodes to the left are less than the current node and all nodes to the right are greater than the current node. In an inorder traversal, we handle all the nodes on the left first, then the current node, and then all the nodes to the right.\n\nThe fact that there are duplicates in the BSTs given in this problem does not change this property - we will still handle nodes in sorted order during an inorder traversal. So how does this help us? If we can obtain the nodes in sorted order, then we can find the most frequent elements without needing a hash map.\n\nLet's say we have a list `values` that has all the values in the tree in sorted order. Any duplicated values must be adjacent to each other in this list since it is sorted. We can iterate over this list from left to right and keep count of a streak - how many of the same number we have seen in a row. Let's call our current streak `currStreak`, and the number we have seen most recently `currNum`. For each `num` we iterate over:\n\n- If `num = currNum`, then we can increment `currStreak` by `1`.\n- If `num != currNum`, then we must start a new streak. We update `currNum = num` and reset `currStreak = 1`.\n\nWe will also maintain the `maxStreak` we have seen so far. When we find a new streak with a longer length, i.e. `currStreak > maxStreak`, we update `maxStreak` and reset the answer, since all the numbers stored in the answer are guaranteed not to be modes. When we find that `currStreak = maxStreak`, we can add the current `num` to the answer.\n\n!?!../Documents/501.json:960,540!?!\n<br>\n\nOnce we have finished iterating through the array, `maxStreak` represents the max frequency and our answer list `ans` will hold all the values that have this frequency.\n\n**Algorithm**\n\n1. Perform an inorder DFS using a recursive `dfs` function to traverse the input tree. At each `node`, add `node.val` to a list `values`.\n2. Initialize variables `maxStreak, currStreak, currNum` to `0` and an empty list `ans`.\n3. Iterate over `values`. At each `num`:\n    - If `num = currNum`, increment `currStreak`. Otherwise, set `currStreak = 1, currNum = num`.\n    - If `currStreak > maxStreak`, update `maxStreak = currStreak` and reset `ans`.\n    - If `currStreak = maxStreak`, add `num` to `ans`.\n4. Return `ans`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/3Yvsv9sP/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3Yvsv9sP\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the DFS, we visit each node once. At each node, we perform $$O(1)$$ work.\n\n    After the DFS, we iterate over `values` which has a length of $$n$$. At each iteration, we perform $$O(1)$$ work. Overall, we perform $$O(n)$$ work.\n\n    You may notice that the runtime of this algorithm is faster than the first three approaches. This is because while hash map operations are $$O(1)$$, the constant overhead still takes a little bit of time, especially compared to just using a list.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(n)$$\n\n    During DFS, recursion is executed using the call stack. This call stack is equal to the depth of the tree, which in the worst-case scenario is $$O(n)$$. Also, the `values` array always grows to a size of $$n$$, and thus also uses $$O(n)$$ space.\n\n<br/>\n\n---\n\n### Approach 5: No \"Values\" Array\n\n**Intuition**\n\n> This approach could be asked as a follow-up to the previous approach. It also satisfies the follow-up given in the problem description (at the bottom, under the constraints). The only extra space we will use in this approach is the call stack from recursion.\n\nIn the previous approach, we perform an inorder traversal to create a `values` list. We then iterate over the `values` list. Do we need this extra list?\n\nThe answer is no: because by definition, the values we iterate over in `values` are the same values we visit during the inorder traversal, in the same order. Thus, we can perform the same logic on the fly during the inorder DFS, instead of performing DFS once to record the numbers in `values`, and then traversing `values` to count the recorded numbers.\n\nWe will use the same process: initialize `maxStreak, currStreak, currNum` as global variables. Perform an inorder traversal using recursion, and at each `node`, treat `num = node.val` and perform the same logic from the previous approach.\n\n**Algorithm**\n\n1. Initialize global variables `maxStreak, currStreak, currNum` to `0` and an empty list `ans`.\n2. Perform an inorder traversal from `root`. At each `node`:\n    - If `node` is null, immediately exit the function.\n    - Call `dfs(node.left)`.\n    - Set `num = node.val`.\n    - If `num = currNum`, increment `currStreak`. Otherwise, set `currStreak = 1, currNum = num`.\n    - If `currStreak > maxStreak`, update `maxStreak = currStreak` and reset `ans`.\n    - If `currStreak = maxStreak`, add `num` to `ans`.\n    - Call `dfs(node.right)`.\n3. Return `ans.`\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/6ueeqDnu/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"6ueeqDnu\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    We perform a DFS, visiting each node in the tree once. At each node, we perform $$O(1)$$ work.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(n)$$\n\n    During DFS, recursion is executed using the call stack. This call stack is equal to the depth of the tree, which in the worst case scenario is $$O(n)$$.\n\n    Note that space used by the answer is not considered part of the space complexity. If we don't count the recursion call stack space either (as suggested in the problem description's follow-up), then this approach uses $$O(1)$$ space as we only use a few extra variables like `maxStreak, currStreak, currNum`.\n    \n<br/>\n\n---\n\n### Approach 6: True Constant Space: Morris Traversal\n\n**Intuition**\n\n> This approach is very advanced and would not be expected in an interview. We have included it for completeness.\n\nWe will continue using the same idea from the previous approach. Is there a way for us to perform the inorder traversal without using any space, including the recursion call stack?\n\nMorris traversal is an advanced technique that allows us to traverse a binary tree with constant auxiliary space. In this approach, we will implement a variant of Morris traversal that will still allow us to achieve an $$O(1)$$ space complexity. To understand Morris traversal, we must first understand why a stack is \"necessary\" during DFS.\n\n![example](../Figures/501/10.png)\n<br>\n\nIn the above tree, we start at the root and move to the left child. Once we are finished fully handling the left subtree, we then handle the root, and finally the right subtree. The reason we use extra stack space during DFS is to \"remember\" the root and right subtree. Think about it: if we move to `root.left`, how can we get back to `root` and thus `root.right`?\n\n![example](../Figures/501/11.png)\n<br>\n\nFurthermore, when we are the green node, how do we get back to the blue nodes? Let's assign each node a **friend**. A node's friend is the **rightmost** node in the left subtree. That is, to find the friend of `node`, we first do `node = node.left`, then do `node = node.right` until there is no right child. \n\n![example](../Figures/501/12.png)\n<br>\n\nYou may notice that some nodes will not have a friend. Namely, a node will not have a friend if it does not have a left child.\n\n![example](../Figures/501/13.png)\n<br>\n\nMorris traversal takes advantage of the following facts:\n\n> 1. All friends are unique. That is, a node cannot be the friend of more than one node.\n>\n> 2. Friend nodes do not have the right children. This is because, by definition, we find friend nodes by traversing right until there is no right child.\n\nThus, we can safely assign the right child of each friend to the node it is a friend to. In the following examples, we are numbering the nodes arbitrarily (these are not the values of a binary search tree):\n\n![example](../Figures/501/14.png)\n<br>\n\nThe rightmost node in the left subtree of the root is the node labeled `4`. Thus, we can assign the right child of `4` to the root.\n\n![example](../Figures/501/15.png)\n<br>\n\nIn these example images, green edges will indicate \"friend\" edges. Notice that now, we have a way back to the root (and thus the right subtree of the root) after entering the left subtree! Let's add the other friend edges.\n\n![example](../Figures/501/16.png)\n<br>\n\nWith these friend edges, we can now perform an inorder traversal without recursion or a stack! We start by handling the `3`, then use the friend edge to get back to `1`. We handle the `1`, then the `4`, and then use the friend edge to get back to the root. After handling the root, we handle the `5`, then use the friend edge to get back to the `2`, which is the final node in our inorder traversal.\n\nNow comes the tricky part: how do we implement this idea? We will use the following process. First, initialize `curr = root`. This represents the current node that we iterating on. Next, we perform the following in a while loop until `curr = null`, indicating we have finished the traversal:\n\n- If `curr.left != null`, we will find the `friend` of `curr`. After finding `friend`, we set `friend.right = curr` then move to the left subtree with `curr = curr.left`. Once we are in the left subtree, we should delete the edge to prevent any infinite loops.\n- If `curr.left = null`, it means there is no left subtree. We can handle this node now, then move to the right with `curr = curr.right`.\n\nWe will quickly demonstrate the traversal using the previous example. At any given time, the green node is `curr`.\n\n![example](../Figures/501/17.png)\n<br>\n\nInitially, `curr = root`. Because there is a left subtree, we will find the friend.\n\n![example](../Figures/501/18.png)\n<br>\n\nWe find the friend by moving to the left subtree, then moving right as much as we can. Set `friend.right = curr`. Next, we set `curr = curr.left`.\n\n![example](../Figures/501/19.png)\n<br>\n\nAfter we move to the left subtree, we must delete the edge we used. This is is so when we return back to the root, we don't repeat the process we just performed (as without deleting the edge, `root.left != null`).\n\n![example](../Figures/501/20.png)\n<br>\n\nAgain, `curr.left != null`, so we find the `friend` and set `friend.right = curr`. Then we move to the left subtree and delete the edge.\n\n![example](../Figures/501/21.png)\n<br>\n\nAt the node labeled `3`, we have no left subtree. Thus we can now handle this node and move to `curr.right`, which you will notice is the friend edge we created earlier.\n\n![example](../Figures/501/22.png)\n<br>\n\n![example](../Figures/501/23.png)\n<br>\n\nThe next two nodes, `1` and `4` are handled the same way. Notice that so far, we have handled nodes in the order `3, 1, 4`, which is the correct order for an inorder traversal. Now, we find ourselves back at the `root`. Because we deleted the left edge earlier, we now move to handle the `root` and move right.\n\n![example](../Figures/501/24.png)\n<br>\n\n![example](../Figures/501/25.png)\n<br>\n\nWe have reached another node where `curr.left != null`. We find the friend and set the right edge.\n\n![example](../Figures/501/26.png)\n<br>\n\nAt the node labeled `5`, we find that `curr.left = null`. Thus, we handle the node and then move right (back to the `2`, as we set this \"friend\" edge earlier).\n\n![example](../Figures/501/27.png)\n<br>\n\nWe finally handle the last node. The traversal ends as we move right, but there is no right child. We handled the nodes in the correct order: `3, 1, 4, 0, 5, 2`.\n\nFinally, we solve the problem by using the same algorithm from the previous approach during our Morris traversal.\n\n**Algorithm**\n\n1. Initialize variables `maxStreak, currStreak, currNum` to `0` and an empty list `ans`. Also, initialize `curr = root`.\n2. While `curr != null`, perform Morris traversal:\n    - If `curr.left != null`:\n        - Find `friend`. We first set `friend = curr.left`, then move with `friend = friend.right` as long as `friend.right` exists.\n        - Once `friend` is found, we set `friend.right = curr`.\n        - Move to `curr.left` and delete the edge. You can do this by first saving `left = curr.left`, then setting `curr.left = null`, and finally performing `curr = left`.\n    - Otherwise, `curr.left = null`:\n        - Set `num = curr.val`.\n        - If `num = currNum`, increment `currStreak`. Otherwise, set `currStreak = 1, currNum = num`.\n        - If `currStreak > maxStreak`, update `maxStreak = currStreak` and reset `ans`.\n        - If `currStreak = maxStreak`, add `num` to `ans`.\n        - Perform `curr = curr.right`.\n3. Return `ans.`\n\n**Implementation**\n\n> Note: `friend` is a keyword in C++, so we will use `friendNode` as the variable name instead.\n\n<iframe src=\"https://leetcode.com/playground/8HrkiKo3/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8HrkiKo3\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    You may be thinking: there is a nested while loop, wouldn't this algorithm have a time complexity of $$O(n^2)$$? The answer is no because the inner while loop can only iterate $$O(n)$$ times total across the entire algorithm.\n\n    In a binary tree with $$n$$ nodes, there are $$n - 1$$ edges. This is because every node except for the root has a parent. During a Morris traversal, we never use an edge more than twice. We use each edge once to move `curr` through the tree, and we use each edge another time to find friends.\n\n    This means we have $$O(2 \\cdot (n - 1)) = O(n)$$ edge iterations. Thus, the Morris traversal overall costs $$O(n)$$, since everything else we do costs $$O(1)$$.\n\n    In Java, we need to convert `ans` to the correct type, but this doesn't change the time complexity.\n\n* Space complexity: $$O(1)$$\n\n    We don't count the answer as part of the space complexity. The only extra space we use is a few extra variables like `maxStreak, currStreak, currNum`. Thus, we have achieved a true $$O(1)$$ space complexity.\n\n    Note that we are modifying the input in this algorithm, which may be considered a bad practice. Some people will also argue that by modifying the input, we should also include it in the space complexity.\n    \n<br/>\n\n**Morris Traversal Follow-Up**\n\nAs mentioned before, what we have implemented above is a variant of the traditional Morris traversal. One drawback to this variant is that the tree is heavily modified after the traversal. With some small changes, we can actually \"repair\" the tree to its original state while still accomplishing an $$O(1)$$ space traversal!\n\nThis article focused on the variant for the sake of brevity. We encourage any eager readers to try and implement the standard traversal on their own as a follow-up.\n\n<details>\n\n<summary>Click here to see the solution!</summary>\n\n<iframe src=\"https://leetcode.com/playground/X5m5zXQy/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"X5m5zXQy\"></iframe>\n\n</details>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMode(self, root: Optional[TreeNode]) -> List[int]:\n    self.ans = []\n    self.pred = None\n    self.count = 0\n    self.maxCount = 0\n\n    def updateCount(root: Optional[TreeNode]) -> None:\n      if self.pred and self.pred.val == root.val:\n        self.count += 1\n      else:\n        self.count = 1\n\n      if self.count > self.maxCount:\n        self.maxCount = self.count\n        self.ans = [root.val]\n      elif self.count == self.maxCount:\n        self.ans.append(root.val)\n\n      self.pred = root\n\n    def inorder(root: Optional[TreeNode]) -> None:\n      if not root:\n        return\n\n      inorder(root.left)\n      updateCount(root)\n      inorder(root.right)\n\n    inorder(root)\n    return self.ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] findMode(TreeNode root) {\n    List<Integer> ans = new ArrayList<>();\n    // count[0] := currCount\n    // count[1] := maxCount\n    int[] count = new int[2];\n\n    inorder(root, count, ans);\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n\n  private TreeNode pred = null;\n\n  private void inorder(TreeNode root, int[] count, List<Integer> ans) {\n    if (root == null)\n      return;\n\n    inorder(root.left, count, ans);\n    updateCount(root, count, ans);\n    inorder(root.right, count, ans);\n  }\n\n  private void updateCount(TreeNode root, int[] count, List<Integer> ans) {\n    if (pred != null && pred.val == root.val)\n      ++count[0];\n    else\n      count[0] = 1;\n\n    if (count[0] > count[1]) {\n      count[1] = count[0];\n      ans.clear();\n      ans.add(root.val);\n    } else if (count[0] == count[1]) {\n      ans.add(root.val);\n    }\n\n    pred = root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findMode(TreeNode* root) {\n    vector<int> ans;\n    int count = 0;\n    int maxCount = 0;\n\n    inorder(root, count, maxCount, ans);\n    return ans;\n  }\n\n private:\n  TreeNode* pred = nullptr;\n\n  void inorder(TreeNode* root, int& count, int& maxCount, vector<int>& ans) {\n    if (root == nullptr)\n      return;\n\n    inorder(root->left, count, maxCount, ans);\n    updateCount(root, count, maxCount, ans);\n    inorder(root->right, count, maxCount, ans);\n  }\n\n  void updateCount(TreeNode* root, int& count, int& maxCount,\n                   vector<int>& ans) {\n    if (pred && pred->val == root->val)\n      ++count;\n    else\n      count = 1;\n\n    if (count > maxCount) {\n      maxCount = count;\n      ans = {root->val};\n    } else if (count == maxCount) {\n      ans.push_back(root->val);\n    }\n\n    pred = root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/501.html",
    "category": "Algorithms",
    "acceptance_rate": 57.40519882713405,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 3995,
    "dislikes": 801,
    "similar_questions": "[{\"title\": \"Validate Binary Search Tree\", \"titleSlug\": \"validate-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"348.5K\", \"totalSubmission\": \"607.1K\", \"totalAcceptedRaw\": 348484, \"totalSubmissionRaw\": 607059, \"acRate\": \"57.4%\"}",
    "title_pt": "Encontrar a Moda em uma Árvore Binária de Busca",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária de busca (BST) com duplicatas, retorne <em>todas as <a href=\"https://en.wikipedia.org/wiki/Mode_(statistics)\" target=\"_blank\">moda(s)</a> (isto é, o elemento que ocorreu com mais frequência) nela</em>.</p>\n\n<p>Se a árvore tiver mais de uma moda, retorne-as em <strong>qualquer ordem</strong>.</p>\n\n<p>Suponha que uma BST seja definida da seguinte forma:</p>\n\n<ul>\n\t<li>A subárvore esquerda de um nó contém apenas nós com chaves <strong>menores ou iguais a</strong> a chave do nó.</li>\n\t<li>A subárvore direita de um nó contém apenas nós com chaves <strong>maiores ou iguais a</strong> a chave do nó.</li>\n\t<li>Tanto a subárvore esquerda quanto a direita também devem ser árvores binárias de busca.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg\" style=\"width: 142px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,null,2,2]\n<strong>Saída:</strong> [2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [0]\n<strong>Saída:</strong> [0]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você poderia fazer isso sem usar nenhum espaço extra? (Assuma que o espaço implícito de pilha incorrido devido à recursão não conta).",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "502",
    "paidOnly": false,
    "title": "IPO",
    "titleSlug": "ipo",
    "url": "https://leetcode.com/problems/ipo",
    "description_url": "https://leetcode.com/problems/ipo/description/",
    "description": "<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p>\n\n<p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p>\n\n<p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p>\n\n<p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p>\n\n<p>The answer is guaranteed to fit in a 32-bit signed integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\n<strong>Output:</strong> 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li>\n\t<li><code>n == profits.length</code></li>\n\t<li><code>n == capital.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/ipo/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int pro;\n  public int cap;\n  public T(int pro, int cap) {\n    this.pro = pro;\n    this.cap = cap;\n  }\n}\n\nclass Solution {\n  public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.cap - b.cap);\n    Queue<T> maxHeap = new PriorityQueue<>((a, b) -> b.pro - a.pro);\n\n    for (int i = 0; i < Capital.length; ++i)\n      minHeap.offer(new T(Profits[i], Capital[i]));\n\n    while (k-- > 0) {\n      while (!minHeap.isEmpty() && minHeap.peek().cap <= W)\n        maxHeap.offer(minHeap.poll());\n      if (maxHeap.isEmpty())\n        break;\n      W += maxHeap.poll().pro;\n    }\n\n    return W;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int pro;\n  int cap;\n  T(int pro, int cap) : pro(pro), cap(cap) {}\n};\n\nclass Solution {\n public:\n  int findMaximizedCapital(int k, int W, vector<int>& Profits,\n                           vector<int>& Capital) {\n    auto compareC = [](const T& a, const T& b) { return a.cap > b.cap; };\n    auto compareP = [](const T& a, const T& b) { return a.pro < b.pro; };\n    priority_queue<T, vector<T>, decltype(compareC)> minHeap(compareC);\n    priority_queue<T, vector<T>, decltype(compareP)> maxHeap(compareP);\n\n    for (int i = 0; i < Capital.size(); ++i)\n      minHeap.emplace(Profits[i], Capital[i]);\n\n    while (k--) {\n      while (!minHeap.empty() && minHeap.top().cap <= W)\n        maxHeap.push(minHeap.top()), minHeap.pop();\n      if (maxHeap.empty())\n        break;\n      W += maxHeap.top().pro, maxHeap.pop();\n    }\n\n    return W;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/502.html",
    "category": "Algorithms",
    "acceptance_rate": 53.00505408900242,
    "topics": [
      "Array",
      "Greedy",
      "Sorting",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 3976,
    "dislikes": 275,
    "similar_questions": "[{\"title\": \"Maximum Subsequence Score\", \"titleSlug\": \"maximum-subsequence-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Elegance of a K-Length Subsequence\", \"titleSlug\": \"maximum-elegance-of-a-k-length-subsequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"268.9K\", \"totalSubmission\": \"507.3K\", \"totalAcceptedRaw\": 268901, \"totalSubmissionRaw\": 507312, \"acRate\": \"53.0%\"}",
    "title_pt": "IPO",
    "description_pt": "<p>Suponha que a LeetCode começará sua <strong>IPO</strong> em breve. Para vender suas ações a um bom preço para o Venture Capital, a LeetCode gostaria de trabalhar em alguns projetos para aumentar seu capital antes da <strong>IPO</strong>. Como ela tem recursos limitados, só pode concluir no máximo <code>k</code> projetos distintos antes da <strong>IPO</strong>. Ajude a LeetCode a projetar a melhor forma de maximizar seu capital total após concluir no máximo <code>k</code> projetos distintos.</p>\n\n<p>Você recebe <code>n</code> projetos, em que o projeto <code>i<sup>th</sup></code> tem um lucro puro <code>profits[i]</code> e é necessário um capital mínimo <code>capital[i]</code> para iniciá-lo.</p>\n\n<p>Inicialmente, você tem <code>w</code> de capital. Quando você conclui um projeto, obterá seu lucro puro e o lucro será adicionado ao seu capital total.</p>\n\n<p>Escolha uma lista de <strong>no máximo</strong> <code>k</code> projetos distintos dentre os projetos dados para <strong>maximizar seu capital final</strong> e retorne <em>o capital final maximizado</em>.</p>\n\n<p>A resposta é garantida caber em um inteiro assinado de 32 bits.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Como seu capital inicial é 0, você só pode iniciar o projeto indexado em 0.\nDepois de concluí-lo, você obterá lucro 1 e seu capital se tornará 1.\nCom capital 1, você pode iniciar o projeto indexado em 1 ou o projeto indexado em 2.\nComo você pode escolher no máximo 2 projetos, você precisa concluir o projeto indexado em 2 para obter o capital máximo.\nPortanto, a saída é o capital final maximizado, que é 0 + 1 + 3 = 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\n<strong>Saída:</strong> 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li>\n\t<li><code>n == profits.length</code></li>\n\t<li><code>n == capital.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "503",
    "paidOnly": false,
    "title": "Next Greater Element II",
    "titleSlug": "next-greater-element-ii",
    "url": "https://leetcode.com/problems/next-greater-element-ii",
    "description_url": "https://leetcode.com/problems/next-greater-element-ii/description/",
    "description": "<p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p>\n\n<p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn&#39;t exist, return <code>-1</code> for this number.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,1]\n<strong>Output:</strong> [2,-1,2]\nExplanation: The first 1&#39;s next greater number is 2; \nThe number 2 can&#39;t find next greater number. \nThe second 1&#39;s next greater number needs to search circularly, which is also 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,3]\n<strong>Output:</strong> [2,3,4,-1,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/next-greater-element-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Brute Force (using Double Length Array) [Time Limit Exceeded]\n\n#### Algorithm\n\nIn this method, we make use of an array $doublenums$ which is formed by concatenating two copies of the given $nums$ array one after the other. Now, when we need to find out the next greater element for $nums[i]$, we can simply scan all the elements $doublenums[j]$, such that $i < j < length(doublenums)$. The first element found satisfying the given condition is the required result for $nums[i]$. If no such element is found, we put a $\\text{-1}$ at the appropriate position in the $res$ array.\n\n \n<iframe src=\"https://leetcode.com/playground/tRcR8Lx3/shared\" frameBorder=\"0\" name=\"tRcR8Lx3\" width=\"100%\" height=\"377\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(n^2)$. The complete $doublenums$ array(of size $\\text{2n}$) is scanned for all the elements of $nums$ in the worst case.\n\n* Space complexity : $O(n)$. $doublenums$ array of size $\\text{2n}$ is used. $res$ array of size $\\text{n}$ is used.\n\n\n---\n\n### Approach 2: Better Brute Force [Accepted]\n\n#### Algorithm\n\nInstead of making a double length copy of $nums$ array , we can traverse circularly in the $nums$ array by making use of the $ \\text{modulus}$ operator. For every element $nums[i]$, we start searching in the $nums$ array(of length $n$) from the index $(i+1)%n$ and look at the next (circularly) $n-1$ elements. For $nums[i]$ we do so by scanning over $nums[j]$, such that\n$(i+1)%n &leq; j &leq; (i+(n-1))%n$, and we look for the first greater element found. If no such element is found, we put a $\\text{-1}$ at the appropriate position in the $res$ array.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/LCG759JD/shared\" frameBorder=\"0\" name=\"LCG759JD\" width=\"100%\" height=\"309\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(n^2)$. The complete $nums$ array of size $n$ is scanned for all the elements of $nums$ in the worst case.\n\n* Space complexity : $O(n)$. $res$ array of size $n$ is used.\n\n---\n\n### Approach 3: Using Stack [Accepted]\n\n\n#### Algorithm\n\nThis approach makes use of a stack. This stack stores the indices of the appropriate elements from $nums$ array.  The top of the stack refers to the index of the Next Greater Element found so far. We store the indices instead of the elements since there could be duplicates in the $nums$ array. The description of the method will make the above statement clearer.\n\nWe start traversing the $nums$ array from right towards the left. For an element $nums[i]$ encountered, we pop all the elements\n$stack[top]$ from the stack such that $nums\\big[stack[top]\\big] \\le nums[i]$. We continue the popping till we encounter a $stack[top]$ satisfying $nums\\big[stack[top]\\big] > nums[i]$. Now, it is obvious that the current $stack[top]$ only can act as the\nNext Greater Element for $nums[i]$(right now, considering only the elements lying to the right of $nums[i]$).\n\nIf no element remains on the top of the stack, it means no larger element than $nums[i]$ exists to its right. Along with this, we also push the index of the element just encountered($nums[i]$), i.e. $i$ over the top of the stack, so that $nums[i]$(or $stack[top]$) now acts as the Next Greater Element for the elements lying to its left.\n\nWe go through two such passes over the complete $nums$ array. This is done so as to complete a circular traversal over the $nums$ array. The first pass could make some wrong entries in the $res$ array since it considers only the elements lying to the right of $nums[i]$, without a circular traversal. But, these entries are corrected in the second pass.  \n\nFurther, to ensure the correctness of the method, let's look at the following cases.\n\nAssume that $nums[j]$ is the correct Next Greater Element for $nums[i]$, such that $i < j &le; stack[top]$. Now, whenever we encounter $nums[j]$, if $nums[j] > nums\\big[stack[top]\\big]$, it would have already popped the previous $stack[top]$ and $j$ would have become the topmost element. On the other hand, if  $nums[j] < nums\\big[stack[top]\\big]$, it would have become the topmost element by being pushed above the previous $stack[top]$. In both the cases, if $nums[j] > nums[i]$, it will be correctly determined to be the Next Greater Element.\n\nThe following example makes the procedure clear:\n\n<!--![Next_Greater_Element_II](../Figures/503_Next_Greater_Element_II.gif)-->\n!?!../Documents/503_Next_Greater2.json:1000,563!?!\n\nAs the animation above depicts, after the first pass, there are a number of wrong entries(marked as $\\text{-1}$) in the $res$ array, because only the elements lying to the corresponding right(non-circular) have been considered till now. But, after the second pass, the correct values are substituted.\n\n\n#### Implementation\n \n<iframe src=\"https://leetcode.com/playground/in37fqRd/shared\" frameBorder=\"0\" name=\"in37fqRd\" width=\"100%\" height=\"309\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $O(n)$. Only two traversals of the $nums$ array are done. Further, at most $\\text{2n}$ elements are pushed and popped from the stack.\n\n* Space complexity : $O(n)$. A stack of size $n$ is used. $res$ array of size $n$ is used.",
    "solution_code_python": null,
    "solution_code_java": null,
    "solution_code_cpp": null,
    "solution_code_url": "https://leetcodehelp.github.io/503.html",
    "category": "Algorithms",
    "acceptance_rate": 66.02750004116068,
    "topics": [
      "Array",
      "Stack",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 8489,
    "dislikes": 210,
    "similar_questions": "[{\"title\": \"Next Greater Element I\", \"titleSlug\": \"next-greater-element-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element III\", \"titleSlug\": \"next-greater-element-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum and Minimum Sums of at Most Size K Subarrays\", \"titleSlug\": \"maximum-and-minimum-sums-of-at-most-size-k-subarrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"561.4K\", \"totalSubmission\": \"850.3K\", \"totalAcceptedRaw\": 561426, \"totalSubmissionRaw\": 850299, \"acRate\": \"66.0%\"}",
    "title_pt": "Próximo Elemento Maior II",
    "description_pt": "<p>Dado um array inteiro circular <code>nums</code> (isto é, o próximo elemento de <code>nums[nums.length - 1]</code> é <code>nums[0]</code>), retorne <em>o <strong>próximo número maior</strong> para cada elemento em</em> <code>nums</code>.</p>\n\n<p>O <strong>próximo número maior</strong> de um número <code>x</code> é o primeiro número maior no próximo da ordem de travessia no array, o que significa que você pode pesquisar circularmente para encontrar seu próximo número maior. Se ele não existir, retorne <code>-1</code> para esse número.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,1]\n<strong>Saída:</strong> [2,-1,2]\nExplicação: O próximo número maior do primeiro 1 é 2; \nO número 2 não consegue encontrar um próximo número maior. \nO próximo número maior do segundo 1 precisa pesquisar circularmente, que também é 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,3]\n<strong>Saída:</strong> [2,3,4,-1,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "504",
    "paidOnly": false,
    "title": "Base 7",
    "titleSlug": "base-7",
    "url": "https://leetcode.com/problems/base-7",
    "description_url": "https://leetcode.com/problems/base-7/description/",
    "description": "<p>Given an integer <code>num</code>, return <em>a string of its <strong>base 7</strong> representation</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> num = 100\n<strong>Output:</strong> \"202\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> num = -7\n<strong>Output:</strong> \"-10\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/base-7/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String convertToBase7(int num) {\n    if (num < 0)\n      return \"-\" + convertToBase7(-num);\n    if (num < 7)\n      return String.valueOf(num);\n    return convertToBase7(num / 7) + String.valueOf(num % 7);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string convertToBase7(int num) {\n    if (num < 0)\n      return \"-\" + convertToBase7(-num);\n    if (num < 7)\n      return to_string(num);\n    return convertToBase7(num / 7) + to_string(num % 7);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/504.html",
    "category": "Algorithms",
    "acceptance_rate": 51.79699798239585,
    "topics": [
      "Math"
    ],
    "hints": [],
    "likes": 845,
    "dislikes": 235,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"163.5K\", \"totalSubmission\": \"315.7K\", \"totalAcceptedRaw\": 163534, \"totalSubmissionRaw\": 315721, \"acRate\": \"51.8%\"}",
    "title_pt": "Base 7",
    "description_pt": "<p>Dado um inteiro <code>num</code>, retorne <em>uma string de sua representação em <strong>base 7</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> num = 100\n<strong>Saída:</strong> \"202\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> num = -7\n<strong>Saída:</strong> \"-10\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>-10<sup>7</sup> &lt;= num &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "506",
    "paidOnly": false,
    "title": "Relative Ranks",
    "titleSlug": "relative-ranks",
    "url": "https://leetcode.com/problems/relative-ranks",
    "description_url": "https://leetcode.com/problems/relative-ranks/description/",
    "description": "<p>You are given an integer array <code>score</code> of size <code>n</code>, where <code>score[i]</code> is the score of the <code>i<sup>th</sup></code> athlete in a competition. All the scores are guaranteed to be <strong>unique</strong>.</p>\n\n<p>The athletes are <strong>placed</strong> based on their scores, where the <code>1<sup>st</sup></code> place athlete has the highest score, the <code>2<sup>nd</sup></code> place athlete has the <code>2<sup>nd</sup></code> highest score, and so on. The placement of each athlete determines their rank:</p>\n\n<ul>\n\t<li>The <code>1<sup>st</sup></code> place athlete&#39;s rank is <code>&quot;Gold Medal&quot;</code>.</li>\n\t<li>The <code>2<sup>nd</sup></code> place athlete&#39;s rank is <code>&quot;Silver Medal&quot;</code>.</li>\n\t<li>The <code>3<sup>rd</sup></code> place athlete&#39;s rank is <code>&quot;Bronze Medal&quot;</code>.</li>\n\t<li>For the <code>4<sup>th</sup></code> place to the <code>n<sup>th</sup></code> place athlete, their rank is their placement number (i.e., the <code>x<sup>th</sup></code> place athlete&#39;s rank is <code>&quot;x&quot;</code>).</li>\n</ul>\n\n<p>Return an array <code>answer</code> of size <code>n</code> where <code>answer[i]</code> is the <strong>rank</strong> of the <code>i<sup>th</sup></code> athlete.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> score = [5,4,3,2,1]\n<strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;]\n<strong>Explanation:</strong> The placements are [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> score = [10,3,8,9,4]\n<strong>Output:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;]\n<strong>Explanation:</strong> The placements are [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>].\n\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == score.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>All the values in <code>score</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/relative-ranks/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nGiven an array `score` with athletes' scores, we need to return their rank. The athlete with the highest score has the lowest place, and the athlete with the second-highest score will have the second-lowest place, and so on. The athletes in first, second, and third place receive gold, silver, and bronze medals, respectively. All other athletes receive their place as their rank.\n\n**Key Observation:**\n- All the scores are guaranteed to be unique.\n\n---\n\n### Approach 1: Sort & Reverse\n\n#### Intuition\n\nConsider Example 1 from the problem description: \n\n> **Input:** `score` = [5, 4, 3, 2, 1]\nPlacements: [1st, 2nd, 3rd, 4th, 5th]\n\nThe placements are assigned in order for this example. This works because the scores are given in decreasing order.\n\nWhen the scores are sorted in decreasing order, each athlete gets assigned the next place.\n\nWe can start developing a solution by sorting the `score` array in decreasing order.\n\nConsider Example 2 from the problem description: \n\n> **Input:** `score` = [10, 3, 8, 9, 4]\n`score` sorted in decreasing order: [10, 9, 8, 4, 3]\nPlacements: [1st, 2nd, 3rd, 4th, 5th]\n\nFor this example, we now have the scores and placements, but because we sorted `score`, we don't know the order the placements should be in the result.\n\nWe can solve this by saving each athlete's original index in a hashmap before sorting the `score` array. The key is the athlete's score, and the value is the athlete's original index.\n\n`scoreToIndex` hashmap: [10 ⟶ 0, 3 ⟶ 1, 8 ⟶ 2, 9 ⟶ 3, 4 ⟶ 4]\n\nThen, we can use the hashmap and the sorted `score` array to add the athletes' ranks to the correct index in the result.\n\n`score` sorted in decreasing order: [10, 9, 8, 4, 3]\n`scoreToIndex` hashmap: [10 ⟶ 0, 3 ⟶ 1, 8 ⟶ 2, 9 ⟶ 3, 4 ⟶ 4]\n\n- Place the 1st ranked athlete, who scored 10, at index 0.\n- Place the 2nd ranked athlete, who scored 9, at index 3.\n- Place the 3rd ranked athlete, who scored 8, at index 2.\n- Place the 4th ranked athlete, who scored 4, at index 4.\n- Place the 5th ranked athlete, who scored 3, at index 1.\n\nFor places 1st, 2nd, and 3rd, we assign medals.\n\n`rank`:\n| index | 0            | 1   | 2              | 3              |   4 |\n| ------| ------------ | --- | -------------- | -------------- | --- |\n| rank  | \"Gold Medal\" | \"5\" | \"Bronze Medal\" | \"Silver Medal\" | \"4\" |\n\n> Output: [\"Gold Medal\", \"5\", \"Bronze Medal\", \"Silver Medal\", \"4\"]\n\n#### Algorithm\n\n1. Initialize a variable `N` to the length of the `score` array.\n2. Initialize a hashmap `scoreToIndex` and save the original index of each athlete based on their `score`. The key is the `score` and the value is the original index.\n3. Sort the `score` array in descending order. Then, the scores will be in order from highest to lowest. Since the highest score corresponds to the lowest place, this means the places will be in order.\n4. Initialize a string array `rank` of size `N` for storing the result.\n5. Assign ranks to athletes. We use the `scoreToIndex` hashmap to retrieve the index in the result of the athlete with `score[i]`. For each rank `i`:\n    - If `i` is `0`, assign the athlete the \"Gold Medal\".\n    - If `i` is `1`, assign the athlete the \"Silver Medal\".\n    - If `i` is `2`, assign the athlete the \"Bronze Medal\".\n    - Otherwise, set `rank[score_to_index[score[i]]] = str(i + 1)`.\n6. Return `rank`.\n\n#### Implementation\n\n> **Notes:** \n> - The best practice is to not modify the input, so we create a copy of the `score` array in the below implementation. We sort the copy, leaving the original array unmodified.\n>\n> - Java does not have a built-in ability to sort an array in reverse order. Therefore, we sort the score array in ascending order and then traverse the array in reverse order using `n - i - 1` when we assign ranks to the athletes.\n\n<iframe src=\"https://leetcode.com/playground/JM7AVNab/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"JM7AVNab\"></iframe>\n\n#### Complexity Analysis\n\n​Let $n$ be the length of `score`.\n​\n* Time complexity: $O(n \\log n)$\n\n    We traverse the score array once and populate `scoreToIndex`. Since inserting in a hashmap takes $O(1)$ time on average, the entire operation takes $O(n)$. Collisions are unlikely since the scores are guaranteed to be unique according to the constraints.\n  \n    Sorting the the score array array takes $O(n \\log n)$.\n  \n    Finally, traversing the score array and assigning ranks to athletes takes $O(n)$.\n  \n    The dominating term is $O(n \\log n)$.\n​\n* Space complexity: $O(n)$\n\n    The hashmap `scoreToIndex` stores $n$ `(key, value)` mappings, so it requires $O(n)$ auxiliary space.\n  \n    The `rank` array is only used to store the result, so it does not contribute towards the space complexity. \n  \n    Note that some extra space is used when we sort the score array. The space complexity of the sorting algorithm depends on the programming language.\n    - In Python, the `sort` method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has $O(n)$ additional space. \n    - In Java, Arrays.sort() is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$ for sorting two arrays.\n    - In C++, the sort() function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of $O( \\log n )$.\n\n    $O(n)$ is the dominating term.\n\n---\n\n### Approach 2: Heap (Priority Queue)\n\n#### Intuition\n\nWhen we assign placements, we assign the next place to the next highest score.\n\nTo assign ranks, we can make use of a max heap. By adding all scores to a heap and subsequently removing them, they'll be in descending order.\n\nHeaps are a data structure that allows us to efficiently find the maximum or minimum value in a dataset. If you are not familiar with heaps, we recommend checking out the [Heap Explore Card](https://leetcode.com/explore/learn/card/heap/).\n\nAs discussed in the previous solution, we need to save each athlete's original index in the `score` array. For each athlete, we will create a `score, index` pair and push it to the heap.\n\nThen, we assign ranks by removing each athlete from the heap and storing their corresponding index as `originalIndex`. We assign the current athlete the next rank and place the rank in the `rank` array at index `originalIndex`. The first three ranks receive medals.\n\n#### Algorithm\n\n1. Initialize a variable `N` to the length of the `score` array.\n2. Initialize a max-heap (priority queue) that will store `(score, index)` pairs.\n3. For each index in `score`, add a pair to the heap with the score and index.\n4. Initialize a string array `rank` of size `N` for storing the answer.\n5. Initialize a varaible `place` to `1`.\n6. Assign ranks to athletes. While the heap is not empty:\n    - Pop the pair with the highest score from the heap. Save the index in `originalIndex`. \n    - Add the corresponding place to the `rank` array at index `originalIndex`:\n        - If `place` is `1`, assign the athlete the \"Gold Medal\".\n        - If `place` is `2`, assign the athlete the \"Silver Medal\".\n        - If `place` is `3`, assign the athlete the \"Bronze Medal\".\n        - Otherwise, set `rank[originalIndex] = str(place)`.\n    - Increment `place`.\n7. Return `rank`.\n\n\n#### Implementation\n\n> **Note:** The Python3 heap implementation is a min-heap by default. We achieve max-heap behavior in the above solution by negating the score when we add it to the heap. Scores with the highest absolute values have the lowest negative values.\n\n<iframe src=\"https://leetcode.com/playground/23Yn9XDm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"23Yn9XDm\"></iframe>\n\n\n#### Complexity Analysis\n\n​Let $n$ be the length of `score`.\n​\n* Time complexity: $O(n \\log n)$\n\n  We traverse the `score` array once and populate the `heap` with each score. Adding an element to the heap takes $\\log n$ time, resulting in a time complexity of $O(n \\log n)$ for this step.\n  \n  When assigning ranks to athletes, we pop each pair from the heap. Removing an element from the heap also takes $\\log n$ time, so removing $n$ elements will take $O(n \\log n)$ time.\n  \n  The overall time complexity is $O(2n \\log n)$, which we can simplify to $O(n \\log n)$.\n​\n* Space complexity: $O(n)$\n\n  The `heap` stores $n$ `(score, index)` pairs, so it requires $O(n)$ auxiliary space.\n  \n  The `rank` array is only used to store the result, so it does not contribute towards the space complexity. \n\n---\n\n### Approach 3: Array as Map\n\n#### Intuition\n\nThe above approaches both have log-linear time complexities. Let's develop a more efficient approach.\n\nIn the first approach, we used a hashmap to save the original indices of the athletes. An alternative to using a map is an array.\n\nWe can use an array `scoreToIndex` to store the athletes' original indices. The \"key\" is the score, and the \"value\" is the original index of the athlete. An athlete's original index can be found at `scoreToIndex[score[i]]`. For example, the original index of an athlete with the score `5` is stored at `scoreToIndex[5]`.\n\nConsider the example `score = [10, 3, 8, 9, 4]`.\n\nThe range of scores may not be equal to the number of athletes. Therefore, we must ensure that the `scoreToIndex` array is large enough to store the entire range of scores. As a result, we will begin by identifying the maximum score, and then declare our array `scoreToIndex` to be of size one greater than that maximum score.\n\nThere may be some indices in the `scoreToIndex` array that do not store indices of athletes, as the array may be larger than the number of athletes. Indices that do not correspond to athletes will contain `0` by default. One athlete will have the original index `0`, which cannot be differentiated from the default `0` indices if we store the athlete's original indices directly, we address this issue by adding one when adding the athletes to the `scoreToIndex` array. Later, when we iterate through the original indices, we subtract one to obtain the correct original index.\n\nThe indices of the `scoreToindex` array represent the scores. The highest score corresponds to the lowest rank, and the second-highest score corresponds to the second-lowest rank, and so on. \n\nIn the first approach, we reversed the scores so we could easily determine the ranks. We can mimic this strategy by traversing the `scoreToIndex` in reverse, from the highest index to the lowest index. We can use a variable `place` to track the placement, and we can find the position in the `rank` array by saving `scoreToIndex[i] - 1` as the `orignalIndex`.\n\n**Example:**\n\n> **Input:** `score` = [10, 3, 8, 9, 4]\n\nThe max score is 10.\n\n`scoreToIndex`:\n| index            | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |\n| ---------------- | - | - | - | - | - | - | - | - | - | - | -  |\n|original index + 1| 0 | 0 | 0 | 2 | 5 | 0 | 0 | 0 | 3 | 4 | 1  |\n \n- Place the 1st ranked athlete, who scored 10, at index 1 - 1 = 0.\n- Place the 2nd ranked athlete, who scored 9, at index 4 - 1 = 3.\n- Place the 3rd ranked athlete, who scored 8, at index 3 - 1 = 2.\n- Place the 4th ranked athlete, who scored 4, at index 5 - 1 = 4.\n- Place the 5th ranked athlete, who scored 3, at index 2 - 1 = 1.\n\nFor places 1st, 2nd, and 3rd, we assign medals.\n\n`rank`:\n| index | 0            | 1   | 2              | 3              |   4 |\n| ----- | ------------ | --- | -------------- | -------------- | --- |\n| rank  | \"Gold Medal\" | \"5\" | \"Bronze Medal\" | \"Silver Medal\" | \"4\" |\n\n> **Output:** Output: [\"Gold Medal\", \"5\", \"Bronze Medal\", \"Silver Medal\", \"4\"]\n\nIn this approach, we use a constant string array to store the medals. We use `MEDALS[place - 1]` to assign medals to the first three places instead of using an `if` statement for each medal.\n\n#### Algorithm\n\n1. Initialize a variable `N` to the length of the `score` array.\n2. Define a function `findMax` that returns the maximum score in the array.\n    - Initialize a variable `maxScore` to `0`.\n    - For each score in the `score` array, if the score is greater than `maxScore`, update `maxScore` to the new score.\n    - Return `maxScore`.\n3. Initialize a variable `M` to the result of `findMax(score)`.\n4. Initialize an array `scoretoIndex` of size `M + 1`. For each score `i` in the score array, set `scoreToIndex[score[i]]` to `i + 1`.\n5. Create a constant string array to store the `MEDALS`: `[\"Gold Medal\", \"Silver Medal\", \"Bronze Medal\"]`.\n6. Initialize a string array `rank` of size `N` for storing the answer.\n7. Initialize a variable `place` to `1`.\n8. Assign ranks to athletes using a `for` loop. For each nonzero entry of `scoreToIndex`, `i`, starting with the last and moving to the first:\n    - Set a variable `originalIndex` to `scoreToIndex[i] - 1`.\n    - Add the place to the `rank` array at index `originalIndex`:\n        - If `place` is less than `4`, assign the athlete `medals[place - 1]`.\n        - Otherwise, set `rank[originalIndex] = str(place)`.\n    - Increment `place`.\n9. Return `rank`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/o47aY2YT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"o47aY2YT\"></iframe>\n\n#### Complexity Analysis\n\n​Let $n$ be the length of `score` and $m$ be the maximum value in the array.\n​\n* Time complexity: $O(n + m)$\n\n  The `findMax` function takes $O(n)$ because it traverses `score` once. We call this function once.\n\n  Populating `scoreToIndex` takes $O(n)$ because we add one entry for each athlete.\n\n  When we assign ranks to athletes, we iterate through every index of the `scoreToIndex` array, which is size $m + 1$. The operations within the loop take constant time, so this step takes $O(m)$.\n  \n  The overall time complexity is $O(2n + m)$, which we can simplify to $O(n + m)$.\n​\n* Space complexity: $O(m)$\n\n  The `scoreToIndex` array is size $m + 1$.\n\n  The `rank` array is only used to store the result, so it does not contribute towards the space complexity. \n\n  Therefore, the overall space complexity is $O(m)$.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String[] findRelativeRanks(int[] nums) {\n    final int n = nums.length;\n    String[] ans = new String[n];\n    List<Integer> indices = new ArrayList<>();\n\n    for (int i = 0; i < n; ++i)\n      indices.add(i);\n\n    Collections.sort(indices, (a, b) -> nums[b] - nums[a]);\n\n    for (int i = 0; i < n; ++i)\n      if (i == 0)\n        ans[indices.get(0)] = \"Gold Medal\";\n      else if (i == 1)\n        ans[indices.get(1)] = \"Silver Medal\";\n      else if (i == 2)\n        ans[indices.get(2)] = \"Bronze Medal\";\n      else\n        ans[indices.get(i)] = String.valueOf(i + 1);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findRelativeRanks(vector<int>& nums) {\n    const int n = nums.size();\n    vector<string> ans(n);\n    vector<int> indices(n);\n\n    iota(begin(indices), end(indices), 0);\n\n    sort(begin(indices), end(indices),\n         [&](const int a, const int b) { return nums[a] > nums[b]; });\n\n    for (int i = 0; i < n; ++i)\n      if (i == 0)\n        ans[indices[0]] = \"Gold Medal\";\n      else if (i == 1)\n        ans[indices[1]] = \"Silver Medal\";\n      else if (i == 2)\n        ans[indices[2]] = \"Bronze Medal\";\n      else\n        ans[indices[i]] = to_string(i + 1);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/506.html",
    "category": "Algorithms",
    "acceptance_rate": 73.16413629270203,
    "topics": [
      "Array",
      "Sorting",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 2017,
    "dislikes": 138,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"347.4K\", \"totalSubmission\": \"474.8K\", \"totalAcceptedRaw\": 347402, \"totalSubmissionRaw\": 474824, \"acRate\": \"73.2%\"}",
    "title_pt": "Classificações Relativas",
    "description_pt": "<p>Você recebe um array de inteiros <code>score</code> de tamanho <code>n</code>, onde <code>score[i]</code> é a pontuação do <code>i<sup>th</sup></code> atleta em uma competição. Todas as pontuações têm garantia de serem <strong>únicas</strong>.</p>\n\n<p>Os atletas são <strong>colocados</strong> com base em suas pontuações, onde o atleta em <code>1<sup>st</sup></code> lugar tem a maior pontuação, o atleta em <code>2<sup>nd</sup></code> lugar tem a <code>2<sup>nd</sup></code> maior pontuação, e assim por diante. A colocação de cada atleta determina sua classificação:</p>\n\n<ul>\n\t<li>A classificação do atleta em <code>1<sup>st</sup></code> lugar é <code>&quot;Gold Medal&quot;</code>.</li>\n\t<li>A classificação do atleta em <code>2<sup>nd</sup></code> lugar é <code>&quot;Silver Medal&quot;</code>.</li>\n\t<li>A classificação do atleta em <code>3<sup>rd</sup></code> lugar é <code>&quot;Bronze Medal&quot;</code>.</li>\n\t<li>Para o atleta do <code>4<sup>th</sup></code> lugar até o <code>n<sup>th</sup></code> lugar, sua classificação é seu número de colocação (isto é, a classificação do atleta em <code>x<sup>th</sup></code> lugar é <code>&quot;x&quot;</code>).</li>\n</ul>\n\n<p>Retorne um array <code>answer</code> de tamanho <code>n</code> onde <code>answer[i]</code> é a <strong>classificação</strong> do <code>i<sup>th</sup></code> atleta.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> score = [5,4,3,2,1]\n<strong>Saída:</strong> [&quot;Gold Medal&quot;,&quot;Silver Medal&quot;,&quot;Bronze Medal&quot;,&quot;4&quot;,&quot;5&quot;]\n<strong>Explicação:</strong> As colocações são [1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>].</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> score = [10,3,8,9,4]\n<strong>Saída:</strong> [&quot;Gold Medal&quot;,&quot;5&quot;,&quot;Bronze Medal&quot;,&quot;Silver Medal&quot;,&quot;4&quot;]\n<strong>Explicação:</strong> As colocações são [1<sup>st</sup>, 5<sup>th</sup>, 3<sup>rd</sup>, 2<sup>nd</sup>, 4<sup>th</sup>].\n\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == score.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= score[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>Todos os valores em <code>score</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "507",
    "paidOnly": false,
    "title": "Perfect Number",
    "titleSlug": "perfect-number",
    "url": "https://leetcode.com/problems/perfect-number",
    "description_url": "https://leetcode.com/problems/perfect-number/description/",
    "description": "<p>A <a href=\"https://en.wikipedia.org/wiki/Perfect_number\" target=\"_blank\"><strong>perfect number</strong></a> is a <strong>positive integer</strong> that is equal to the sum of its <strong>positive divisors</strong>, excluding the number itself. A <strong>divisor</strong> of an integer <code>x</code> is an integer that can divide <code>x</code> evenly.</p>\n\n<p>Given an integer <code>n</code>, return <code>true</code><em> if </em><code>n</code><em> is a perfect number, otherwise return </em><code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 28\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 7\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/perfect-number/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\n**Algorithm**\n\nIn brute force approach, we consider every possible number to be a divisor of the given number $$num$$, by iterating over all the numbers lesser than $$num$$. Then, we add up all the factors to check if the given number satisfies the Perfect Number property. This approach obviously fails if the number $$num$$ is very large.\n\n<iframe src=\"https://leetcode.com/playground/6Nzf7w9h/shared\" frameBorder=\"0\" name=\"6Nzf7w9h\" width=\"100%\" height=\"343\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. We iterate over all the numbers lesser than $$n$$.\n\n* Space complexity : $$O(1)$$. Constant extra space is used.\n\n---\n\n### Approach #2 Better Brute Force [Time Limit Exceeded]\n\n**Algorithm**\n\nWe can little optimize the brute force by breaking the loop when the value of $$sum$$ increase the value of $$num$$. In that case, we can directly return $$false$$.\n\n<iframe src=\"https://leetcode.com/playground/bGGFxpmt/shared\" frameBorder=\"0\" name=\"bGGFxpmt\" width=\"100%\" height=\"377\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. In worst case, we iterate over all the numbers lesser than $$n$$.\n\n* Space complexity : $$O(1)$$. Constant extra space is used.\n\n---\n\n### Approach #3 Optimal Solution [Accepted]\n\n**Algorithm**\n\nIn this method, instead of iterating over all the integers to find the factors of $$num$$, we only iterate upto the $$\\sqrt{n}$$. The reasoning behind this can be understood as follows.\n\nConsider the given number $$num$$ which can have $$m$$ distinct factors, namely $$n_1, n_2,..., n_m$$. Now, since the number $$num$$ is divisible by $$n_i$$, it is also divisible by $$n_j=num/n_1$$ i.e. $$n_i*n_j=num$$. Also, the largest number in such a pair can only be up to $$\\sqrt{num}$$ (because $$\\sqrt{num} \\times \\sqrt{num}=num$$). Thus, we can get a significant reduction in the run-time by iterating only upto $$\\sqrt{num}$$ and considering such $$n_i$$'s and $$n_j$$'s in a single pass directly.\n\nFurther, if $$\\sqrt{num}$$ is also a factor, we have to consider the factor only once while checking for the perfect number property.\n\nWe sum up all such factors and check if the given number is a Perfect Number or not. Another point to be observed is that while considering 1 as such a factor, $$num$$ will also be considered as the other factor. Thus, we need to subtract $$num$$ from the $$sum$$.\n\n<iframe src=\"https://leetcode.com/playground/ZpHuGfHj/shared\" frameBorder=\"0\" name=\"ZpHuGfHj\" width=\"100%\" height=\"377\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(\\sqrt{n})$$. We iterate only over the range $$1 < i &leq; \\sqrt{num}$$.\n* Space complexity : $$O(1)$$. Constant extra space is used.\n\n---\n\n### Approach #4 Euclid-Euler Theorem [Accepted]\n\n**Algorithm**\n\nEuclid proved that $$2^{p−1}(2^p − 1)$$ is an even perfect number whenever $$2^p − 1$$ is prime, where $$p$$ is prime.\n\nFor example, the first four perfect numbers are generated by the formula $$2^{p−1}(2^p − 1)$$, with $$p$$ a prime number, as follows:\n\n```\nfor p = 2:   21(22 − 1) = 6\nfor p = 3:   22(23 − 1) = 28\nfor p = 5:   24(25 − 1) = 496\nfor p = 7:   26(27 − 1) = 8128.\n```\nPrime numbers of the form $$2^p − 1$$ are known as Mersenne primes. For $$2^p − 1$$ to be prime, it is necessary that $$p$$ itself be prime. However, not all numbers of the form $$2^p − 1$$ with a prime $$p$$ are prime; for example, $$2^{11} − 1 = 2047 = 23 × 89$$ is not a prime number.\n\nYou can see that for small value of $$p$$, its related perfect number goes very high. So, we need to evaluate perfect numbers for some primes $$(2, 3, 5, 7, 13, 17, 19, 31)$$ only, as for bigger prime its perfect number will not fit in 64 bits.\n\n\n<iframe src=\"https://leetcode.com/playground/kBfJ6TtU/shared\" frameBorder=\"0\" name=\"kBfJ6TtU\" width=\"100%\" height=\"292\"></iframe>\n\n**Complexity Analysis**\n\n\n* Time complexity : $$O(\\log{n})$$. Number of primes will be in order $$\\log{num}$$.\n\n* Space complexity : $$O(\\log{n})$$. Space used to store primes.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkPerfectNumber(self, num: int) -> bool:\n    return num in {6, 28, 496, 8128, 33550336}",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkPerfectNumber(int num) {\n    if (num == 1)\n      return false;\n\n    int sum = 1;\n\n    for (int i = 2; i <= Math.sqrt(num); ++i)\n      if (num % i == 0)\n        sum += i + num / i;\n\n    return sum == num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkPerfectNumber(int num) {\n    if (num == 1)\n      return false;\n\n    int sum = 1;\n\n    for (int i = 2; i <= sqrt(num); ++i)\n      if (num % i == 0)\n        sum += i + num / i;\n\n    return sum == num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/507.html",
    "category": "Algorithms",
    "acceptance_rate": 44.569015287784794,
    "topics": [
      "Math"
    ],
    "hints": [],
    "likes": 1165,
    "dislikes": 1263,
    "similar_questions": "[{\"title\": \"Self Dividing Numbers\", \"titleSlug\": \"self-dividing-numbers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"267.1K\", \"totalSubmission\": \"599.3K\", \"totalAcceptedRaw\": 267103, \"totalSubmissionRaw\": 599302, \"acRate\": \"44.6%\"}",
    "title_pt": "Número Perfeito",
    "description_pt": "<p>Um <a href=\"https://en.wikipedia.org/wiki/Perfect_number\" target=\"_blank\"><strong>número perfeito</strong></a> é um <strong>inteiro positivo</strong> que é igual à soma de seus <strong>divisores positivos</strong>, excluindo o próprio número. Um <strong>divisor</strong> de um inteiro <code>x</code> é um inteiro que pode dividir <code>x</code> exatamente.</p>\n\n<p>Dado um inteiro <code>n</code>, retorne <code>true</code><em> se </em><code>n</code><em> for um número perfeito, caso contrário retorne </em><code>false</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 28\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7 e 14 são todos divisores de 28.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 7\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= num &lt;= 10<sup>8</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "508",
    "paidOnly": false,
    "title": "Most Frequent Subtree Sum",
    "titleSlug": "most-frequent-subtree-sum",
    "url": "https://leetcode.com/problems/most-frequent-subtree-sum",
    "description_url": "https://leetcode.com/problems/most-frequent-subtree-sum/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return the most frequent <strong>subtree sum</strong>. If there is a tie, return all the values with the highest frequency in any order.</p>\n\n<p>The <strong>subtree sum</strong> of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg\" style=\"width: 207px; height: 183px;\" />\n<pre>\n<strong>Input:</strong> root = [5,2,-3]\n<strong>Output:</strong> [2,-3,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg\" style=\"width: 207px; height: 183px;\" />\n<pre>\n<strong>Input:</strong> root = [5,2,-5]\n<strong>Output:</strong> [2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/most-frequent-subtree-sum/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nIn this problem, we have to return the array of sums of subtrees with maximum frequency.        \nAnd a subtree sum is the sum of all nodes of a subtree.\n\n![subtree](../Figures/508/Slide1.png)\n\nLet's go from naive to an optimized approach for finding the frequency of all subtree sums in a given tree.\n\n---\n\n### Approach 1: Pre-Order Traversal\n\n#### Intuition\n\nWe have to find the sum of all subtrees.          \nSo, we can think of traversing the given tree in pre-order (i.e. root first, then left and right children), and for each node, we find the sum of the subtree where the current node is the root node.\n\n**Now, how we can find the sum of all nodes of a tree, provided we have a root node?**         \nRemember one thing, thinking recursively is the most easy way to solve tree problems.         \n\nHere, if we had the sum of left and right subtrees of the current root, then we can say the current subtree's sum will be:      \n`current root's value + left subtree sum + right subtree sum` \n\n![tree_sum](../Figures/508/Slide2.png)\n\nThus, we can recursively find the sum of the left and right subtrees of the given node and return the current node's tree's sum.     \nWe also need some base conditions to stop the recursion. The base condition is simply the case where we can get the result without doing any computation.       \n\n**Can you tell what will be the sum of nodes of an empty tree?**       \nExactly it can be considered 0 as there are no nodes present. Thus, this is our base case.\n\nThus, our pseudocode for finding sum of all nodes of a subtree will look like:\n\n```\nint findTreeSum(TreeNode root) {\n    // Base condition.\n    if !root {\n        return 0\n    }\n    \n    // Current root's tree's sum will be, current root's value + left subtree sum + right subtree sum.\n    return root.val + findTreeSum(root.left) + findTreeSum(root.right)\n}\n```\n\nLet's now look at this slideshow to better understand this.\n\n!?!../Documents/508/slideshow1.json:960,540!?!\n\n<br />\n\n#### Algorithm\n\n1. Initialize variables:\n    - `sumFreq`, hashmap to store frequency count of all sums.\n    - `maxFreq`, variable to store the maximum frequency.\n    - `maxFreqSums`, array to store values of all different sums whose frequency is maximum.\n\n2. Iterate over each node of the given tree using pre-order traversal:\n    - Calculate the current node's subtree's sum as discussed above.\n    - Increment the sum's frequency in `sumFreq`.\n    - If the current subtree's sum's frequency is greater than `maxFreq`, store it's frequency in `maxFreq`.\n\n3. Iterate over `sumFreq` map, and push all sums in `maxFreqSums` array whose frequency is equal to `maxFreq`.\n\n4. Return `maxFreqSums` array.\n\n\n!?!../Documents/508/slideshow2.json:960,540!?!\n\n<br />\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/HtGHE6ZM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"HtGHE6ZM\"></iframe>\n\n#### Complexity Analysis\n\nHere, $N$ is the number of nodes in the binary tree.\n\n* Time complexity: $O(N^{2})$.\n  - We iterate over each node of the tree and then calculate the sum of the node's subtree.\n  - For finding the sum of a subtree, we traverse each node of that subtree, in worst-case, tree can be skew thus it is $ O(N) $ time operation. Thus, for finding the sum of subtree for $N$ nodes, it will take $ O(N^2) $ time.\n  - In the end we traverse on all the unique sums, and as there are $ N $ subtrees, $ N $ different sums are possible, thus in worst-case we will iterate on $ N $ elements.\n  - Thus, overall we take $ O(N^2 + N) = O(N^2) $ time.\n\n* Space complexity: $O(N)$.\n  - Our hashmap, stores all different possible subtree sums. There are $ N $ nodes, which means $ N $ different subtrees are possible with different sums, thus requiring $ O(N) $ space.\n  - Both function's recursion call stack can take at most $ O(N) $ space in case of a skew tree. Thus, in the worst-case scenario, the recursive stack space used will be $ O(N + N) = O(N) $.\n\n---\n\n\n### Approach 2: Post-Order Traversal\n\n#### Intuition\n\nOne thing we can notice is that we will repeatedly traverse to the same set of nodes again and again while traversing in the pre-order direction.                  \nBecause a smaller subtree can be part of bigger subtrees.       \n\n![tree_repeat](../Figures/508/Slide40.png)\n\nNow imagine if there were hundreds of layers. The smaller subtree will be traversed a lot of times.\n\nWe know, that if we had the sum of left and right subtrees of the current root, then we can say the current subtree's sum will be:      \n`current root's value + left subtree sum + right subtree sum`.\n\nSo instead of going from root to child nodes, and repeatedly calculating the sum of the subtree of child nodes,         \nwe can traverse to child nodes first and then use the sum of the child node's subtree to get the sum of the current node's subtree.\n    \nLook at this slideshow to better understand this.\n\n!?!../Documents/508/slideshow3.json:960,540!?!\n\n<br />\n\n#### Algorithm\n\n1. Initialize variables:\n    - `sumFreq`, hashmap to store frequency count of all sums.\n    - `maxFreq`, variable to store the maximum frequency.\n    - `maxFreqSums`, array to store values of all different sums whose frequency is maximum.\n\n2. Iterate over each node of the given tree using post-order traversal:\n    - Using the left and right child's tree's sum, calculate the current node's tree's sum.\n    - Increment the sum's frequency in `sumFreq`.\n    - If the current subtree's sum's frequency is greater than `maxFreq`, update `maxFreq` as this frequency.\n\n3. Iterate over `sumFreq` map, and push all sums in the `maxFreqSums` array whose frequency is equal to `maxFreq`.\n\n4. Return `maxFreqSums` array.\n\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/XRPVqQmt/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"XRPVqQmt\"></iframe>\n\n\n#### Complexity Analysis\n\nHere, $N$ is the number of nodes in the binary tree.\n\n* Time complexity: $O(N)$.\n  - We iterate over each node of the tree only once and find its subtree sum in $ O(1) $ time. Thus, it takes $ O(N) $ time to find all the subtree sums of a tree with $ N $ nodes.\n  - In the end we traverse on all the unique sums, and as there are $ N $ subtrees, $ N $ different sums are possible, thus in worst-case we will iterate on $ N $ elements.\n  - Thus, overall we take $ O(N + N) = O(N) $ time.\n\n* Space complexity: $O(N)$.\n  - We use a hashmap to store all different possible subtree sums. There are $ N $ nodes, which means $ N $ different subtrees are possible with different sums, thus requiring $ O(N) $ space.\n  - Recursion call stack can also take at most $ O(N) $ space in case of a skew tree. \n  - Thus, overall we require $ O(N + N) = O(N) $ extra space.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n    if not root:\n      return []\n\n    count = Counter()\n\n    def dfs(root: Optional[TreeNode]) -> int:\n      if not root:\n        return 0\n\n      summ = root.val + dfs(root.left) + dfs(root.right)\n      count[summ] += 1\n      return summ\n\n    dfs(root)\n    maxFreq = max(count.values())\n    return [summ for summ in count if count[summ] == maxFreq]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] findFrequentTreeSum(TreeNode root) {\n    List<Integer> ans = new ArrayList<>();\n    Map<Integer, Integer> count = new HashMap<>();\n    int maxCount = 0;\n\n    sumDownFrom(root, count);\n\n    for (final int freq : count.values())\n      maxCount = Math.max(maxCount, freq);\n\n    for (final int sum : count.keySet())\n      if (count.get(sum) == maxCount)\n        ans.add(sum);\n\n    return ans.stream().mapToInt(Integer::intValue).toArray();\n  }\n\n  private int sumDownFrom(TreeNode root, Map<Integer, Integer> count) {\n    if (root == null)\n      return 0;\n\n    final int sum = root.val + sumDownFrom(root.left, count) + sumDownFrom(root.right, count);\n    count.merge(sum, 1, Integer::sum);\n    return sum;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findFrequentTreeSum(TreeNode* root) {\n    vector<int> ans;\n    unordered_map<int, int> count;\n    int maxCount = 0;\n\n    sumDownFrom(root, count);\n\n    for (const auto& [_, freq] : count)\n      maxCount = max(maxCount, freq);\n\n    for (const auto& [sum, freq] : count)\n      if (freq == maxCount)\n        ans.push_back(sum);\n\n    return ans;\n  }\n\n private:\n  int sumDownFrom(TreeNode* root, unordered_map<int, int>& count) {\n    if (root == nullptr)\n      return 0;\n\n    const int sum = root->val + sumDownFrom(root->left, count) +\n                    sumDownFrom(root->right, count);\n    ++count[sum];\n    return sum;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/508.html",
    "category": "Algorithms",
    "acceptance_rate": 67.74520235363492,
    "topics": [
      "Hash Table",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 2318,
    "dislikes": 325,
    "similar_questions": "[{\"title\": \"Subtree of Another Tree\", \"titleSlug\": \"subtree-of-another-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Nodes Equal to Sum of Descendants\", \"titleSlug\": \"count-nodes-equal-to-sum-of-descendants\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"158.5K\", \"totalSubmission\": \"234K\", \"totalAcceptedRaw\": 158538, \"totalSubmissionRaw\": 234021, \"acRate\": \"67.7%\"}",
    "title_pt": "Soma de Subárvore Mais Frequente",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne a <strong>soma de subárvore</strong> mais frequente. Se houver empate, retorne todos os valores com a maior frequência em qualquer ordem.</p>\n\n<p>A <strong>soma de subárvore</strong> de um nó é definida como a soma de todos os valores dos nós formados pela subárvore enraizada naquele nó (incluindo o próprio nó).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/freq1-tree.jpg\" style=\"width: 207px; height: 183px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,2,-3]\n<strong>Saída:</strong> [2,-3,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/freq2-tree.jpg\" style=\"width: 207px; height: 183px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,2,-5]\n<strong>Saída:</strong> [2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "509",
    "paidOnly": false,
    "title": "Fibonacci Number",
    "titleSlug": "fibonacci-number",
    "url": "https://leetcode.com/problems/fibonacci-number",
    "description_url": "https://leetcode.com/problems/fibonacci-number/description/",
    "description": "<p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p>\n\n<pre>\nF(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n &gt; 1.\n</pre>\n\n<p>Given <code>n</code>, calculate <code>F(n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 4\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 30</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/fibonacci-number/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fib(self, N: int) -> int:\n    if N < 2:\n      return N\n\n    dp = [0, 0, 1]\n\n    for i in range(2, N + 1):\n      dp[0] = dp[1]\n      dp[1] = dp[2]\n      dp[2] = dp[0] + dp[1]\n\n    return dp[2]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int fib(int N) {\n    if (N < 2)\n      return N;\n\n    int[] dp = {0, 0, 1};\n\n    for (int i = 2; i <= N; ++i) {\n      dp[0] = dp[1];\n      dp[1] = dp[2];\n      dp[2] = dp[0] + dp[1];\n    }\n\n    return dp[2];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int fib(int N) {\n    if (N < 2)\n      return N;\n\n    vector<int> dp{0, 0, 1};\n\n    for (int i = 2; i <= N; ++i) {\n      dp[0] = dp[1];\n      dp[1] = dp[2];\n      dp[2] = dp[0] + dp[1];\n    }\n\n    return dp.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/509.html",
    "category": "Algorithms",
    "acceptance_rate": 72.79784670663152,
    "topics": [
      "Math",
      "Dynamic Programming",
      "Recursion",
      "Memoization"
    ],
    "hints": [],
    "likes": 8675,
    "dislikes": 384,
    "similar_questions": "[{\"title\": \"Climbing Stairs\", \"titleSlug\": \"climbing-stairs\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Split Array into Fibonacci Sequence\", \"titleSlug\": \"split-array-into-fibonacci-sequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Length of Longest Fibonacci Subsequence\", \"titleSlug\": \"length-of-longest-fibonacci-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-th Tribonacci Number\", \"titleSlug\": \"n-th-tribonacci-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2.4M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 2379777, \"totalSubmissionRaw\": 3269020, \"acRate\": \"72.8%\"}",
    "title_pt": "Número de Fibonacci",
    "description_pt": "<p>Os <b>números de Fibonacci</b>, comumente denotados por <code>F(n)</code>, formam uma sequência, chamada de <b>sequência de Fibonacci</b>, tal que cada número é a soma dos dois anteriores, começando de <code>0</code> e <code>1</code>. Ou seja,</p>\n\n<pre>\nF(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n &gt; 1.\n</pre>\n\n<p>Dado <code>n</code>, calcule <code>F(n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 4\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= n &lt;= 30</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "511",
    "paidOnly": false,
    "title": "Game Play Analysis I",
    "titleSlug": "game-play-analysis-i",
    "url": "https://leetcode.com/problems/game-play-analysis-i",
    "description_url": "https://leetcode.com/problems/game-play-analysis-i/description/",
    "description": "<p>Table: <code>Activity</code></p>\n\n<pre>\n+--------------+---------+\n| Column Name  | Type    |\n+--------------+---------+\n| player_id    | int     |\n| device_id    | int     |\n| event_date   | date    |\n| games_played | int     |\n+--------------+---------+\n(player_id, event_date) is the primary key (combination of columns with unique values) of this table.\nThis table shows the activity of players of some games.\nEach row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the <strong>first login date</strong> for each player.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1         | 2         | 2016-03-01 | 5            |\n| 1         | 2         | 2016-05-02 | 6            |\n| 2         | 3         | 2017-06-25 | 1            |\n| 3         | 1         | 2016-03-02 | 0            |\n| 3         | 4         | 2018-07-03 | 5            |\n+-----------+-----------+------------+--------------+\n<strong>Output:</strong> \n+-----------+-------------+\n| player_id | first_login |\n+-----------+-------------+\n| 1         | 2016-03-01  |\n| 2         | 2017-06-25  |\n| 3         | 2016-03-02  |\n+-----------+-------------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/game-play-analysis-i/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/511.html",
    "category": "Database",
    "acceptance_rate": 75.65113217267574,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 938,
    "dislikes": 34,
    "similar_questions": "[{\"title\": \"Game Play Analysis II\", \"titleSlug\": \"game-play-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"370K\", \"totalSubmission\": \"489.1K\", \"totalAcceptedRaw\": 370043, \"totalSubmissionRaw\": 489145, \"acRate\": \"75.7%\"}",
    "title_pt": "Análise de Jogo I",
    "description_pt": "<p>Tabela: <code>Activity</code></p>\n\n<pre>\n+--------------+---------+\n| Nome da Coluna  | Tipo    |\n+--------------+---------+\n| player_id    | int     |\n| device_id    | int     |\n| event_date   | date    |\n| games_played | int     |\n+--------------+---------+\n|(player_id, event_date) é a chave primária (combinação de colunas com valores únicos) desta tabela.\nEsta tabela mostra a atividade de jogadores de alguns jogos.\nCada linha é um registro de um jogador que fez login e jogou um número de partidas (possivelmente 0) antes de sair em algum dia usando algum dispositivo.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar a <strong>data do primeiro login</strong> de cada jogador.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Activity:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1         | 2         | 2016-03-01 | 5            |\n| 1         | 2         | 2016-05-02 | 6            |\n| 2         | 3         | 2017-06-25 | 1            |\n| 3         | 1         | 2016-03-02 | 0            |\n| 3         | 4         | 2018-07-03 | 5            |\n+-----------+-----------+------------+--------------+\n<strong>Saída:</strong> \n+-----------+-------------+\n| player_id | first_login |\n+-----------+-------------+\n| 1         | 2016-03-01  |\n| 2         | 2017-06-25  |\n| 3         | 2016-03-02  |\n+-----------+-------------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "513",
    "paidOnly": false,
    "title": "Find Bottom Left Tree Value",
    "titleSlug": "find-bottom-left-tree-value",
    "url": "https://leetcode.com/problems/find-bottom-left-tree-value",
    "description_url": "https://leetcode.com/problems/find-bottom-left-tree-value/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return the leftmost value in the last row of the tree.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg\" style=\"width: 302px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [2,1,3]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg\" style=\"width: 432px; height: 421px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,null,5,6,null,null,7]\n<strong>Output:</strong> 7\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-bottom-left-tree-value/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n\n---\n\n### Overview\n\nOur objective is to find the leftmost value at the bottom level of the tree. We are provided with the root of the tree. \n\nSince we need to find a specific value at the bottom of a tree, we will need to traverse the tree, searching for the leftmost node at the bottom level. When we find that node, we can return its value.\n\n> If you are not familiar with tree traversal, check out our [Explore Card](https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/)\n\n---\n\n### Approach 1: Depth-First Search\n\n\n#### Intuition\n\nWe need to find the leftmost node in the bottom level of the tree. As we are concerned with the bottom level specifically, we will need to keep track of the current level/depth as we traverse.\n\nOne of the primary ways to traverse a tree is a Depth-First Search (DFS). We will use this approach to search for the leftmost node in the bottom level because it will be easy to keep track of the depth. We will use a preorder traversal, visiting each subtree's root first so that we can keep track of the level and visiting the left child first so that when we get to a new depth, we know that the current node is the leftmost node of that level.\n\nBinary trees are often traversed using recursive methods. Below is an example pseudocode for a preorder traversal.\n\n##### Standard Recursive Preorder Traversal\n1. If the tree is empty, return.\n2. Handle the root.\n3. Traverse the left subtree - call Preorder(root.left).\n4. Traverse the right subtree - call Preorder(root.right).\n\nBelow is an example tree, with each level's depth labeled.\n\n![Binary Tree with \\[1, 2, 3, 4, null, 5, 6, null, null, 7\\]](../Figures/513/513_1.png)\n\nA preorder traversal visits the nodes in this order: 1, 2, 4, 3, 5, 7, 6.\n\nWe can implement a recursive function `dfs` to search for the leftmost node in the bottom level, which we will call `bottomLeftValue`. \n\nGenerally, when working recursively with trees, the base case is when the tree is empty. If the current node is empty, we return. \n\nFrom there, we can build the rest of our recursive function `dfs`. We keep track of the deepest level of the tree we have encountered so far in `maxDepth`. We store the value of the deepest leftmost node we have found thus far in `bottomLeftValue`. To perform a pre-order traversal, we first handle the root, then recursively search the left subtree, then the right subtree. Each time we recursively call `dfs`, we increment the depth by one because the left or right child of the current node is one level deeper than the current node. When we visit the current node, we will check if it is deeper than any node we have discovered yet. If the current node is the deepest we have found so far, we have discovered a new level of the tree. We visit nodes to the left first, so we know this is the leftmost node in this level. We can update `bottomLeftValue` to the current node's value and also update `maxDepth`.\n\nAfter defining `dfs`, all we have to do to solve the problem is call the function and then return `bottomLeftValue``.\n\n\n#### Algorithm\n\n1. Initialize a variable `maxDepth` to store the depth of the bottom level of the tree.\n2. Initialize a variable `bottomLeftValue` to store the leftmost value in the last row of the tree.\n3. Implement a recursive function, `dfs`, that traverses the tree and finds the leftmost value in the last row of the tree. The parameters are `current`, the current node, and `depth`, its depth.\n    1. Check whether `current` is empty. If so, return.\n    2. Check if the current depth exceeds the global variable `maxDepth`. If it does, that means we have found a new level.\n        1. Set `maxDepth` to `depth`.\n        2. Set `bottomLeftValue` to the value of the current node.\n    3. Recursively call `dfs` on the current node's left subtree and increment `depth` by one.\n    4. Recursively call `dfs` on the current node's right subtree and increment `depth` by one.\n4. Call `dfs` with `root` and the initial `depth` of `0`.\n5. Return `bottomLeftValue`.\n\n\n#### Implementation\n\n\n\n<iframe src=\"https://leetcode.com/playground/795bdDWi/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"795bdDWi\"></iframe>\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes in the tree.\n\n- Time complexity: $O(n)$\n\n    Traversing the tree with a DFS costs $O(n)$ as we visit each node exactly once. At each visit, we perform $O(1)$ work.\n\n\n- Space complexity: $O(n)$\n\n    The space complexity of DFS, when implemented recursively, is determined by the maximum depth of the call stack, which corresponds to the depth of the tree. In the worst case, if the tree is entirely unbalanced (e.g., a linked list), the call stack can grow as deep as the number of nodes, resulting in a space complexity of $O(n)$.\n\n---\n\n### Approach 2: Breadth-First Search Right to Left\n\n#### Intuition\n\nThe other primary way to traverse a tree is a Breath-First Search (BFS). This traversal method, also known as level-order traversal, could apply to this problem because the algorithm visits all the nodes in each level before moving on to the next level. BFS could be helpful because we are concerned with the last level specifically, and visiting the levels in order means that the final nodes we encounter are on the bottom level. The general algorithm for Breadth-First Search is below.\n\n##### Standard Breadth-First Search\n1. Create a queue for storing the nodes on each level.\n2. Add the root node to the queue.\n3. While the queue is not empty:\n    1. Remove the front node of the queue.\n    2. Handle the node and add its children to the back of the queue.\n\n\nBelow is an example tree to visualize how BFS works.\n\n![Binary Tree with \\[1, 2, 3, 4, null, 5, 6, null, null, 7\\]](../Figures/513/513_2.png)\n\nBreath First Search visits the nodes in this order: 1, 2, 3, 4, 5, 6, 7.\n\nIn the depth-first search implementation above, we kept track of the depth and `maxDepth` of the tree using a variable. We could use the same strategy to track the depth during the BFS, but it may not be necessary. BFS performs a level order search, meaning the last nodes we encounter will be on the bottom level. We are searching for the leftmost node in the bottom level of the tree. \n\n> How can we find the leftmost node in the bottom level?  \n\nBFS of a tree is often implemented such that the left child of a given node is visited first, then the right child. If we implement BFS such that the right child of a given node is visited first, then the left child, the last node we visit is the leftmost node in the bottom level of the tree. This makes a variable for depth unnecessary. We can just return the value of the last node we encounter during the search.\n\n\n\n#### Algorithm\n\n1. Initialize a Queue `queue` for storing the nodes on each level.\n2. Create a new node `current` and set it to `root`.\n3. Add `current` to `queue`.\n4. While `queue` is not empty:\n    1. Remove the front node from the queue and save it in `current`.\n    2. If the `current` has a right child, add it to `queue`.\n    3. If the `current` has a left child, add it to `queue`.\n5. After the while loop, each node in the tree has been visited. The search traversed the whole tree, top to bottom, right to left, so the last node stored in `current` is the leftmost node in the bottom level of the tree, and we return its value.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/g6zXpErc/shared\" frameBorder=\"0\" width=\"100%\" height=\"446\" name=\"g6zXpErc\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of nodes in the tree.\n\n* Time complexity: $O(n)$\n\n    We perform BFS, which costs $O(n)$ because we don't visit a node more than once. At each node, we perform $O(1)$ work.\n\n\n* Space complexity: $O(n)$\n\n    We require $O(n)$ space for the queue during the BFS for `queue`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n    q = deque([root])\n\n    while q:\n      root = q.popleft()\n      if root.right:\n        q.append(root.right)\n      if root.left:\n        q.append(root.left)\n\n    return root.val",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findBottomLeftValue(TreeNode root) {\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n    TreeNode node = null;\n\n    while (!q.isEmpty()) {\n      node = q.poll();\n      if (node.right != null)\n        q.offer(node.right);\n      if (node.left != null)\n        q.offer(node.left);\n    }\n\n    return node.val;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findBottomLeftValue(TreeNode* root) {\n    queue<TreeNode*> q{{root}};\n    TreeNode* node = nullptr;\n\n    while (!q.empty()) {\n      node = q.front();\n      q.pop();\n      if (node->right)\n        q.push(node->right);\n      if (node->left)\n        q.push(node->left);\n    }\n\n    return node->val;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/513.html",
    "category": "Algorithms",
    "acceptance_rate": 71.70861486033459,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 3897,
    "dislikes": 297,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"401.1K\", \"totalSubmission\": \"559.3K\", \"totalAcceptedRaw\": 401067, \"totalSubmissionRaw\": 559301, \"acRate\": \"71.7%\"}",
    "title_pt": "Encontrar o Valor Mais à Esquerda na Última Linha da Árvore",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne o valor mais à esquerda na última linha da árvore.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/14/tree1.jpg\" style=\"width: 302px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,1,3]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/14/tree2.jpg\" style=\"width: 432px; height: 421px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,null,5,6,null,null,7]\n<strong>Saída:</strong> 7\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "514",
    "paidOnly": false,
    "title": "Freedom Trail",
    "titleSlug": "freedom-trail",
    "url": "https://leetcode.com/problems/freedom-trail",
    "description_url": "https://leetcode.com/problems/freedom-trail/description/",
    "description": "<p>In the video game Fallout 4, the quest <strong>&quot;Road to Freedom&quot;</strong> requires players to reach a metal dial called the <strong>&quot;Freedom Trail Ring&quot;</strong> and use the dial to spell a specific keyword to open the door.</p>\n\n<p>Given a string <code>ring</code> that represents the code engraved on the outer ring and another string <code>key</code> that represents the keyword that needs to be spelled, return <em>the minimum number of steps to spell all the characters in the keyword</em>.</p>\n\n<p>Initially, the first character of the ring is aligned at the <code>&quot;12:00&quot;</code> direction. You should spell all the characters in <code>key</code> one by one by rotating <code>ring</code> clockwise or anticlockwise to make each character of the string key aligned at the <code>&quot;12:00&quot;</code> direction and then by pressing the center button.</p>\n\n<p>At the stage of rotating the ring to spell the key character <code>key[i]</code>:</p>\n\n<ol>\n\t<li>You can rotate the ring clockwise or anticlockwise by one place, which counts as <strong>one step</strong>. The final purpose of the rotation is to align one of <code>ring</code>&#39;s characters at the <code>&quot;12:00&quot;</code> direction, where this character must equal <code>key[i]</code>.</li>\n\t<li>If the character <code>key[i]</code> has been aligned at the <code>&quot;12:00&quot;</code> direction, press the center button to spell, which also counts as <strong>one step</strong>. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/ring.jpg\" style=\"width: 450px; height: 450px;\" />\n<pre>\n<strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot;\n<strong>Output:</strong> 4\n<strong>Explanation:</strong>\nFor the first key character &#39;g&#39;, since it is already in place, we just need 1 step to spell this character. \nFor the second key character &#39;d&#39;, we need to rotate the ring &quot;godding&quot; anticlockwise by two steps to make it become &quot;ddinggo&quot;.\nAlso, we need 1 more step for spelling.\nSo the final output is 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot;\n<strong>Output:</strong> 13\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li>\n\t<li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li>\n\t<li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/freedom-trail/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nOur objective is to find the minimum number of steps required to spell the keyword (given as `key`), using the metal dial (given as `ring`). The characters of the keyword must be spelled in order.\n\nAny one of the following operations counts as one step:\n1. Rotate the metal dial clockwise by one place. \n2. Rotate the metal dial anticlockwise by one place. \n3. Press the center button to spell a character.\n\nWhen spelling a given character `key[i]`, the number of steps it takes to spell the character will be the number of rotations made to put the character in the `\"12:00\"` position plus one, which represents pressing the center button to spell the character.\n\n---\n\n### Approach 1: Top-Down Dynamic Programming\n\n#### Intuition\n\nWe want to find the minimum number of steps required to spell the keyword, which is made up of one or more characters. Let's start by finding the minimum number of steps required to spell one character. \n\nTo spell a character, we must align the character with the `\"12:00\"` direction on the metal dial `ring`. To determine the number of steps required to do so, let's define a function called `countSteps`. The parameters for this function are:\n- `curr`: the position, or index, in the `ring` of the character currently located at the `\"12:00\"` position.\n- `next`: the index in the `ring` of the character that needs to be spelled out in `key`.\n\nThe metal dial can be turned clockwise or anticlockwise to reach the desired character in `key`.  \n\nAssuming `curr` comes before `next`, we calculate the difference between `curr` and `next`, denoted as `curr - next`. Since `next` could be either before or after `curr`, potentially resulting in a negative difference, we obtain the absolute value of the difference to represent the number of steps between the indices. Let's store this value in the variable `stepsBetween`.\n\n> An example of this process is the string `godding`, where `'o'` is at index `1` and `'n'` is at index `5`. When `curr = 1` and `next = 5`, we compute `|5 - 1| = 4`, and when `cur = 5` and `next = 1`  we compute `|1 - 5| = 4`. \n>\n> |0|1|2|3|4|5|6|\n> |-|-|-|-|-|-|-|\n> |g|o|d|d|i|n|g|\n\nTo calculate the steps required to rotate from `curr` to `next` by wrapping around the metal dial, we subtract the value of `stepsBetween` from the length of the `ring`, denoted as `ringLength - stepsBetween`. Let's store this result in the variable `stepsAround`.\n\n> Using the previous example, traversing `'o'` to `'n'`,  `ringLength` is `7` and `stepsBetween` is 4.  `7 - 4 = 3`. \n\nFinally, `countSteps` returns the minimum of the two distances, `stepsAround` and `stepsBetween`.\n\n![Possible Paths Between o and n](../Figures/514/metal_dial.png)\n\n> Steps from `'o'` to `'n'` in `godding`.\n> - The red arrow represents `stepsBetween`, where `'n'` is reached without wrapping around the end of the string.\n> - The blue arrow represents `stepsAround`, where `'n'` is reached by wrapping around the end of the string.\n\n**`countSteps` function**    \n1. Calculate `stepsBetween` by taking the absolute value of `curr - next`.\n2. Calculate `stepsAround` using `ringLength - stepsBetween`.\n3. Return `min(steps_around, steps_between)`.\n\n**Brute Force**    \n\nTo achieve our goal using a naive approach, we could calculate the minimum steps for each character in the keyword individually and then sum them to find the minimum steps needed to spell the entire keyword. This method would be considered greedy because it selects the locally optimal next character. However, what if a word has multiple occurrences of the same character? \n\nLet's understand this through example. Assume the `ring` is `repetitive` and the key is `per`. \n\n|0|1|2|3|4|5|6|7|8|9|\n|-|-|-|-|-|-|-|-|-|-|\n|r|e|p|e|t|i|t|i|v|e|\n\nThere are at least two ways to spell the keyword:\n\n1. - Let's spell the `p` at index `2`. It will take `|2 - 0| + 1 = 3` steps.\n   - Then, let's choose the `e` at index `3`. It will take `|3 - 2| + 1 = 2` steps.\n   - Going back to `r` at index `0` will take `|0 - 3| + 1 = 4` steps.\n\n   This totals `9` steps.\n\n2. - Let's spell the `p` at index `2`. It will take `|2 - 0| + 1 = 3` steps.\n   - Then, let's choose the `e` at index `1`. It will take `|1 - 2| + 1 = 2` steps.\n   - Going back to `r` at index `0` will take `|0 - 1| + 1 = 2` steps.\n\n   This totals `7` steps.\n\nTherefore, we need to consider which character we were at previously.\n\nFor this problem, the greedy method does not lead to an optimal solution. If a word has multiple occurrences of the same character, the minimum steps to the next character are affected by which character was previously at the `\"12:00\"` position.\n\nWe will define a recursive function, `tryLock`, to calculate the number of steps to spell the keyword. The parameters are: \n- `ringIndex`: the current index of `ring`. \n- `keyIndex`: the current index of `key`.\n- `minSteps`: the minimum steps to spell the keyword so far. \n\nThis function returns the minimum number of steps required to spell the whole keyword, stored in the variable `minSteps`. \n\nWhen we reach the end of the keyword, we have spelled the whole word. Therefore, our base case is `keyIndex == key.length()`. At that point, the `keyIndex` is past the end of the keyword, and no steps need to be taken, so we return zero.\n\nGiven two characters, if there is only one occurrence of each character in `ring`, then there are only two ways between those characters. Our function `countSteps` will provide the number of steps of the better way. We simply need to add one to signify pressing the center button.\n\nTo find `minSteps` for the whole word based on a given choice between characters, we can recursively call `tryLock`, calculating the steps from the character we just visited to the next character in `key`. This will tell us how visiting a given occurrence of a character affects the overall `minSteps`. Since there are multiple options for spelling when there are multiple occurrences of a character, we will loop through the keyword and calculate `bestSteps` for each duplicate occurrence.\n\nWhen we call `tryLock`, we will pass the largest integer as a parameter because a path has not been determined between the zeroth index of `ring` and the first character in `key`. This way, when we update `minSteps`, the calculation will always be less than the initial amount, so we can accurately calculate the number of steps.\n\n**Brute Force Algorithm** \n\n1. Define a function `countSteps` that gives the minimum path between two indices of `ring`.\n2. Define a function `tryLock` that returns the minimum number of steps to spell the keyword. The parameters are `ringIndex`, the current index of `ring`, `keyIndex`, the current index of `key`, and `minSteps`, the minimum steps to spell the keyword so far:\n    1. If `key_index` is equal to `key.length()`, then return `0`; `key` has been spelled.\n    2. Iterate through each character in the `ring` using `i`:\n        1. If `ring[i]` equals the current character `key[keyIndex]`:\n            - Calculate `totalSteps`, the steps it takes to spell `key` when we visit `ring[i]` by adding the following three terms: \n                - The output of `countSteps` which finds the number of steps from the `ringIndex` to `ring[i]`.\n                - `1`, signifying pressing the center button.\n                - The output of `tryLock`, which calculates how many steps to each character in `key` are required if we choose to visit `ring[i]`.\n            - Save the minimum between `totalSteps` and the best so far in `minSteps`.\n    3. Return `minSteps`.\n3. Call `tryLock(0, 0, INT_MAX)` as we start with the zeroth index of `ring` in the  `\"12:00\"` position and start spelling with the first character in `key`. The largest integer is passed as the final parameter because a path has not been determined between the zeroth index of `ring` and the first character in `key`.\n\n<iframe src=\"https://leetcode.com/playground/Hs2Uuf4G/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Hs2Uuf4G\"></iframe>\n\nThis solution is inefficient and is not accepted because the time limit is exceeded. We compute the output of the same argument multiple times. \n\n![repeated_subproblems](../Figures/514/repeated_subproblems.png)\n\nIs there a more efficient way to solve this problem? The problem involves finding a minimum, which is a hint that it could be solved with a greedy or dynamic programming approach. Since one decision affects others, a greedy approach is not likely to solve the problem, but dynamic programming could be an effective approach. Can we use dynamic programming to make this approach more efficient?  \n\n> Dynamic programming is a programming paradigm in which we break a problem into sub-problems, store the result of each sub-problem, and use it when required. If you are not familiar with dynamic programming, we recommend checking out [Dynamic Programming Explore Card](https://leetcode.com/explore/featured/card/dynamic-programming/).\n\nWe can optimize our calculations by storing values as we calculate them. To do this, we can utilize a map called `bestSteps`, where we store the best path we have found to reach a particular `keyIndex` of `key` when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position. \n\nWe adjust our `tryLock` function in two ways:\n1. We check whether the `ringIndex` and `keyIndex` pair is already in the map. If it is, we return the stored `minSteps` value.\n2. We only calculate the optimum for new `(ringIndex, keyIndex)` pairs, and when we do, we add them to the map.\n\nThis approach saves computational time by avoiding redundant calculations and utilizing stored values whenever possible.\n\n#### Algorithm\n\n1. Define a function `countSteps` that gives the minimum path between two indices of `ring`.\n2. Create the variables `ringLen` to store the length of the `ring` and `keyLen` to store the length of the `key`.\n3. Create a map, `bestSteps`, to store the minimum number of steps to find the character at `keyIndex` when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position. \n4. Define a function `tryLock` that returns the minimum number of steps to spell the keyword. The parameters are `ringIndex`, `keyIndex`, and `minSteps`, the minimum steps to spell the keyword so far:\n    1. Check whether `keyIndex` equals `keyLen`; if so return `0`; `key` has been spelled.\n    2. Check whether the `(ringIndex, keyIndex)` pair is in `bestSteps`. If it is, return `bestSteps[ringIndex][keyIndex]`; we have already calculated the best path.\n    3. Iterate through each `charIndex` in `ring`:\n        1. If `ring[charIndex]` equals the current character `key[keyIndex]`:\n           - Calculate `totalSteps`, the steps it takes to spell `key` when we visit this occurrence of `ring[charIndex]` by adding the following three terms:\n                - The output of `countSteps`, which finds the number of steps from the `ringIndex` to the `ring[charIndex]`.\n                - `1`, which signifies pressing the center button.\n                - The output of `tryLock`, which calculates the number of steps to each character in `key`, granted we chose to visit this occurrence of `ring[charIndex]`.\n            - Save the minimum between `totalSteps` and the best so far in `minSteps`.\n            - Save the `minSteps` for this `(ringIndex, keyIndex)` pair in `bestSteps`.\n    4. Return `minSteps`.\n5. Call `tryLock(0, 0, INT_MAX)` as we start with the zeroth index of `ring` in the `\"12:00\"` position and start spelling with the first character in `key`. The largest integer is passed as the final parameter because a path has not been determined between the zeroth index of `ring` and the first character in `key`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/avfRubs9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"avfRubs9\"></iframe>\n\n#### Complexity Analysis\n\nLet $R$ be the length of `ring` and $K$ be the length of `key`.\n\n* Time Complexity: $O(K \\cdot R^2)$. \n\n    When every character in `ring` is unique, $K$ recursive calls are made, one for each letter in the keyword.\n    \n    At worst, when every character of `ring` is the same, we initially call `trylock` $R$ times. For each of these $R$ recursive calls, `tryLock` is called for each occurrence of the character in `ring` for each character in the keyword. This means the `trylock` function is called a total of $R \\cdot K \\cdot R$ times.\n    \n    Therefore, the overall time complexity is $O(K \\cdot R^2)$.\n\n* Space Complexity: $O(K \\cdot R)$ \n\n    $O(K \\cdot R)$ space is used for the map. The call stack can grow as deep as $K$ since a recursive call is made for each character in `key`. This makes the overall space complexity $O(K \\cdot R)$.\n\n---\n\n### Approach 2: Bottom-Up Dynamic Programming \n\n#### Intuition\n\nThe top-down solution involves recursion, which requires a significant amount of overhead to maintain the call stack. We can convert our top-down solution to a bottom-up solution to save space. \n\nWe can utilize the previously defined `tryLock` function. Additionally, we create a variable `ringLen` to store the length of the `ring` and a variable `keyLen` to store the length of the `key`.\n\nIn our top-down solution, we use a map `bestSteps` to store the minimum number of steps to `keyIndex` starting from the `ringIndex` of `ring`. To generate a bottom-up solution, we will use a 2D array `bestSteps[ringIndex][keyIndex]` to store the minimum number of steps to the `keyIndex` when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position.\n\nWe declare the 2D array `bestSteps` with `ringLen` in the `ringIndex` dimension and `keyLen + 1` in the `keyIndex` dimension because our base case is when the whole `key` has been spelled, and zero additional steps need to be taken. We initialize every value in the array to the largest integer value. This way, when we iterate through the array updating the minimum number of steps, the steps calculation will always be less than the initialized amount, allowing us to correctly calculate the number of steps.\n\nIn a bottom-up solution, we start by addressing the base case. For every index pair `(ringIndex, keyLen)` in `bestSteps`, we initialize the value to zero because when the entire `key` has been spelled, no additional steps are needed.\n\nOur bottom-up solution will be iterative. We need to iterate through both dimensions of `bestSteps`, so we'll use a nested for loop. We iterate through the indices `keyIndex` of `key`, starting with the last character in `key`, and for each, we iterate through the indices `ringIndex` of `ring`.\n\nSimilar to our top-down solution, we iterate through the characters using `charIndex` of `ring`, searching for indices in `ring` that contain the same character as `key[keyIndex]`. Each iteration of the innermost loop represents a state. We can utilize the function call we made in the top-down solution to build our recurrence relation. The calculations we performed in the top-down solution will be replicated here, but instead of recursion, we'll use our array `bestSteps`.\n\nThe recurrence relation calculates the minimum number of steps to find the character at `keyIndex` of `key` when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position. Our recurrence relation is:\n\n> `bestSteps[r][k] = min(bestSteps[r][k], 1 + countSteps[r, charIndex] + bestSteps[charIndex][key_index + 1])` \n\nThe terms in the recurrence relation represent: \n\n- `bestSteps[ringIndex][keyIndex]`: the previous minimum number of steps to that occurrence of that character. \n- `countSteps[ringIndex, charIndex]`: the minimum number of steps between the `ringIndex` aligned with the `\"12:00\"` position of `ring`, and the index of `charIndex`, the next character of the `key`.\n- `1`: represents selecting the character by pressing the center button.\n- `bestSteps[charIndex][keyIndex + 1]`: the number of steps it took to reach `charIndex` from the last character `key[keyIndex + 1]` the `ring` spelled.\n\nAfter iterating through both strings, we return `bestSteps[0][0]` which stores the minimum number of steps it took to spell `key` when `ring` begins with its zeroth index in the `\"12:00\"` position.\n\n#### Algorithm\n\n1. Define a function `countSteps` that gives the minimum path between two indices of `ring`.\n2. Create the variables `ringLen` to store the length of `ring` and `keyLen` to store the length of `key`.\n3. Declare a 2D array `bestSteps`. It will have `ringLen` rows and `keyLen + 1` columns. \n\n    > `bestSteps` has one extra column because we want to store the base case of `0` steps. \n    \n4. Initialize all values in `bestSteps` to the largest integer to indicate that a path has not been determined.\n5. Set each index `ringIndex, keyLength` of `bestSteps`, to `0` for the base case of zero steps.\n6. Iterate from the end to the beginning of `key` with `keyIndex` and through `ring` with `ringIndex`:\n    - For each character `ring[charIndex]` in `ring`:\n        - If `ring[charIndex]` equals `key` at `keyIndex`: Use the recurrence relation `bestSteps[ringIndex][k] = min(bestSteps[ringIndex][k], 1 + countSteps[ringIndex, charIndex] + bestSteps[charIndex][keyIndex + 1])` to calculate the minimum number of steps to find the character at `keyIndex` of the keyword when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position. \n7. Return `bestSteps[0][0]` which stores the minimum number of steps to spell `key` when `ring` begins with its zeroth index in the `\"12:00\"` position.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/modUNNXg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"modUNNXg\"></iframe>\n\n#### Complexity Analysis\n\nLet $R$ be the length of `ring` and $K$ be the length of `key`.\n\n* Time Complexity: $O(K \\cdot R^2)$\n\n    We use nested loops iterating $K$ times through `key` and $R$ times through `ring` for all $R$ characters in `ring`. This gives an overall time complexity of $O(K \\cdot R^2)$.\n\n* Space Complexity: $O(KR)$ \n\n    We use a 2D array with the dimensions $K + 1$ and $R$.\n\n---\n\n### Approach 3: Space-Optimized Bottom-Up Dynamic Programming\n\n#### Intuition\n\nUpon analyzing the bottom-up solution, we observe that when calculating the minimum number of steps for the `keyIndex` column of `bestSteps`, the only other column we refer to is the `keyIndex + 1` column. This means we can space-optimize the bottom-up solution, using two 1-D arrays to store the step calculations we need to reference. One array is for the current column, and the other array is for the previous column.\n\nWe will create the array `prev` to store the values of the last column and `curr` to store the values of the current column. We initialize the indices of `prev` to zero to represent that when the whole `key` has been spelled, zero additional steps need to be taken. We initialize the indices of `curr` to the largest integer to indicate that a path has not been determined between those indices.\n\nFor the space-optimized approach, we iterate through `key` and `ring` similarly to the bottom-up approach, but we adjust the recurrence relation to use our two columns `prev` and `curr`. \n\nThe recurrence relation finds the minimum number of steps to find the `key[keyIndex]` when the `ring[ringIndex]` is aligned with the `\"12:00\"` position and stores it in `curr[ringIndex]`. The adjusted relation is:\n\n`curr[ringIndex] = min(curr[ringIndex], 1 + countSteps[ringIndex, charIndex] + prev[charIndex])` \n\nThe terms in the recurrence relation represent:\n\n- `curr[ringIndex]`: the current minimum number of steps to that index. \n- `1`: represents selecting the character by pressing the center button.\n- `countSteps[ringIndex, charIndex]`: gives the minimum number of steps between `ringIndex`, the index aligned with the position of `ring`, and the index of `charIndex`, the next character of the `key`.\n- `prev[charIndex]`: the number of steps it took to reach `charIndex` from the last character the `key[keyIndex + 1]` the `ring` spelled.\n  \nAfter iterating through both strings, we return `prev[0]` which stores the minimum number of steps to spell `key` when `ring` begins with its index `0` in the `\"12:00\"` position.\n\n#### Algorithm\n\n1. Define a function `countSteps` that gives the minimum path between two indices of `ring`.\n2. Create the variables `ringLen` to store the length of `ring` and `keyLen` to store the length of `key`.\n3. Declare a 1D array `prev` of size `ringLen` to store the previous column and initialize all indices to `0` for the base case of zero steps.\n4. Declare a 1D array `curr` of size `ringLen` to store the current column and initialize all indices to the largest integer to indicate that a path has not been determined.\n5. Iterate from the end to the beginning of `key` with `keyIndex`:\n    - Reset all of the indices of `curr` to the largest integer.\n    - For each character `charIndex` in `ring`:\n        - If `ring` at `charIndex` equals `key` at `keyIndex`:\n        - Use the recurrence relation `curr[ringIndex] = min(curr[ringIndex], 1 + countSteps[ringIndex, charIndex] + prev[charIndex])` to calculate the minimum number of steps to find the character at `keyIndex` of key when the `ringIndex` of `ring` is aligned with the `\"12:00\"` position. \n    - Set `prev` to `curr`.\n6. Return `prev[0]` which stores the minimum number of steps to spell `key` when `ring` begins with its zeroth index in the `\"12:00\"` position.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/gSzUnwFA/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"gSzUnwFA\"></iframe>\n\n#### Complexity Analysis\n\nLet $R$ be the length of `ring` and $K$ be the length of `key`.\n\n* Time Complexity: $O(K \\cdot R^2)$ \n\n    We use nested loops iterating $K$ times through `key` and $R$ times through `ring` for all $R$ characters in `ring`. This gives an overall time complexity of $O(K \\cdot R^2)$.\n\n* Space Complexity: $O(R)$. \n\n    We used two arrays of length $R$ to store the minimum steps between the characters. This gives an overall space complexity of $O(R)$.\n\n---\n\n### Approach 4: Shortest Path\n\n#### Intuition\n\nIf we think of the possible paths between the characters as a graph, we can spell the keyword using a modified Dijkstra’s algorithm. Dijkstra’s algorithm is used to find the shortest path from a source vertex to each of the other vertices in a weighted graph. It uses a priority queue (min-heap) to greedily determine which edges to use to find the shortest path to the other vertices.\n\n> If you are not familiar with Dijkstra’s algorithm, we suggest you read our relevant [Leetcode Explore Card](https://leetcode.com/explore/featured/card/graph/622/single-source-shortest-path-algorithm/3862/).\n\nWe discussed in the first approach that a greedy solution that just considers the locally optimal next character will not solve the problem optimally. This shortest path solution works because we always choose the next character with the shortest total steps, not the shortest next steps.\n\nFor our purposes, each vertex is a character in the `ring` that is present in the keyword.\n\nDijkstra's algorithm generally uses an adjacency list that contains the neighbors of each vertex. We must visit vertices, or characters, in a certain order to spell the keyword. We need to decide which occurrence of a given character in `ring` we should visit. We use a hash map that stores the indices of each character in `ring`, where the key is the character and the value is the list of indices where it occurs in `ring`. The duplicate occurrences of specific characters are the \"neighbors\".\n\nDijkstra's algorithm often uses a data structure to store vertices that have already been visited. We can use a hash map to store `(keyIndex, ringIndex)` pairs we have seen before.\n\nWe can track how many steps it takes to spell each character with `totalSteps`.\n\nWe use a min-heap to store the steps it takes to spell a given character in the keyword from a given index in `ring`. We start by adding the initial indices to the heap.\n\nWhen we reach the end of the keyword, we have spelled the whole word. Therefore, our base case is when `keyIndex` equals `keyLen`. `totalSteps` accounts for the steps taken to spell the characters in the keyword but does not account for pressing the center button to spell a character. We press the center button exactly `keyLen` times to spell the keyword, once for each character. Therefore, we return the sum of `totalSteps` and `keyLen`.\n\nWhen the keyword has not yet been spelled, we first check whether this `(keyIndex, ringIndex)` pair has been seen before. If so, we continue.\n\nIf we haven't seen this pair before, we need to find the minimum number of steps between the current and next character of the keyword using the metal dial.\n\nFor each occurrence of the current `key[keyIndex]` in `ring`, `nextIndex`, we add an entry to the heap that represents turning the metal dial to the next character in the keyword. The entry consists of three parts:\n- `totalSteps`: the sum of `toalSteps` and the output of `count_steps(ringIndex, nextIndex)`.\n- `nextIndex`: the index of `ring` that will be at the `\"12:00\"` position, and\n- `keyIndex + 1`: the next character in the keyword.\n\nOnce the keyword has been spelled, we will have the answer, because we have greedily chosen the next character with the lowest total steps.\n\n![graph](../Figures/514/graph.png)\n\n> Possible paths to spell the keyword visualized as a graph. The shortest path is highlighted in green.\n\n#### Algorithm\n\n1. Define a function `countSteps` that gives the minimum path between two indices of `ring`.\n2. Create the variables `ringLen` to store the length of `ring` and `keyLen` to store the length of `key`.\n3. Create a hash map `characterIndices` and add each character in `ring` as a key and a list with the indices of the occurrences as the value.\n4. Initialize a priority queue (min-heap) `heap` that stores the `totalSteps` for a `ringIndex` and `keyIndex` pair. The top of the heap will contain the smallest `totalSteps`. Add the starting steps, ring position, and key position, which are all `0` to the heap.\n5. Create a hash set `seen` to store `ringIndex` and `keyIndex` pairs we have already seen.\n6. While the `heap` is not empty:\n    - Pop the element from the top of the heap.\n    - Check whether the `keyIndex` equals the `keyLen`. If so, we have spelled the whole keyword.\n    - Check whether this `ringIndex` and `keyIndex` pair has already been seen. If so, continue.\n    - Otherwise, add this `ringIndex` and `keyIndex` pair to `seen`.\n    - For each occurrence `nextIndex` in `ring` of the letter `key[keyIndex]`:\n        - Add a heap entry that calculates the steps from `nextIndex` to the next character in `key`. The values for this entry are as follows:\n        - `totalSteps`: `totalSteps + count_steps(ringIndex, nextIndex)`.\n        - `ringIndex`: `nextIndex`.\n        - `keyIndex`: `keyIndex + 1`.\n7. Return `totalSteps + keyLen`. We add `keyLen` to the steps to account for the center button being pressed once for each character in `key`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/c2CkhwRQ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"c2CkhwRQ\"></iframe>\n\n#### Complexity Analysis\n\nLet $R$ be the length of `ring` and $K$ be the length of `key`. \n\n* Time complexity: $O(RK \\cdot \\log (RK))$\n\n    Building the `characterIndices` hashmap takes $O(R)$ time as we add an entry for each character in `ring`.\n\n    The main loop will run once for each pair that we visit. We use the `seen` set, so we never visit the same `(keyIndex, ringIndex)` pair more than once. The maximum number of pairs we visit is the number of unique possible pairs, which is $R \\cdot K$.\n     \n    Looking up a pair in `seen` takes $O(1)$ time in the average case.\n\n    It takes the priority queue $O(RK \\cdot \\log (RK))$ time to push or pop $R \\cdot K$ elements from the queue.\n\n    Therefore, the overall time complexity is $O(RK \\cdot \\log (RK))$.\n\n* Space complexity: $O(R \\cdot K)$\n\n    The `characterIndices` hashmap is size $R$ because it stores a total of $R$ `(character, index)` mappings.\n\n    The main space used is by the priority queue, which can store up to $R \\cdot K$ pairs.\n\n    We also use the `seen` hash set, which can grow up to size $R \\cdot K$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findRotateSteps(self, ring: str, key: str) -> int:\n    # Number of rotates of ring to match key[index:]\n    @functools.lru_cache(None)\n    def dfs(ring: str, index: int) -> int:\n      if index == len(key):\n        return 0\n\n      ans = math.inf\n\n      # For each ring[i] == key[index]\n      # We rotate the ring to match ring[i] w/ key[index]\n      # Then recursively match newRing w/ key[index + 1:]\n      for i, r in enumerate(ring):\n        if r == key[index]:\n          minRotates = min(i, len(ring) - i)\n          newRing = ring[i:] + ring[:i]\n          remainingRotates = dfs(newRing, index + 1)\n          ans = min(ans, minRotates + remainingRotates)\n\n      return ans\n\n    return dfs(ring, 0) + len(key)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findRotateSteps(String ring, String key) {\n    Map<String, Integer> memo = new HashMap<>();\n    return dfs(ring, key, 0, memo) + key.length();\n  }\n\n  // # of rotates of ring to match key[index:]\n  private int dfs(final String ring, final String key, int index, Map<String, Integer> memo) {\n    if (index == key.length())\n      return 0;\n    // Add the index to prevent duplicate\n    final String hashKey = ring + index;\n    if (memo.containsKey(hashKey))\n      return memo.get(hashKey);\n\n    int ans = Integer.MAX_VALUE;\n\n    // For each ring[i] == key[index]\n    // We rotate the ring to match ring[i] w/ key[index]\n    // Then recursively match newRing w/ key[index + 1:]\n    for (int i = 0; i < ring.length(); ++i)\n      if (ring.charAt(i) == key.charAt(index)) {\n        final int minRotates = Math.min(i, ring.length() - i);\n        final String newRing = ring.substring(i) + ring.substring(0, i);\n        final int remainingRotates = dfs(newRing, key, index + 1, memo);\n        ans = Math.min(ans, minRotates + remainingRotates);\n      }\n\n    memo.put(hashKey, ans);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findRotateSteps(string ring, string key) {\n    return dfs(ring, key, 0, {}) + key.length();\n  }\n\n private:\n  // # of rotates of ring to match key[index:]\n  int dfs(const string& ring, const string& key, int index,\n          unordered_map<string, int>&& memo) {\n    if (index == key.length())\n      return 0;\n    // Add the index to prevent duplicate\n    const string hashKey = ring + to_string(index);\n    if (memo.count(hashKey))\n      return memo[hashKey];\n\n    int ans = INT_MAX;\n\n    // For each ring[i] == key[index]\n    // We rotate the ring to match ring[i] w/ key[index]\n    // Then recursively match newRing w/ key[index + 1:]\n    for (size_t i = 0; i < ring.length(); ++i)\n      if (ring[i] == key[index]) {\n        const int minRotates = min(i, ring.length() - i);\n        const string& newRing = ring.substr(i) + ring.substr(0, i);\n        const int remainingRotates = dfs(newRing, key, index + 1, move(memo));\n        ans = min(ans, minRotates + remainingRotates);\n      }\n\n    return memo[hashKey] = ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/514.html",
    "category": "Algorithms",
    "acceptance_rate": 58.835583780548426,
    "topics": [
      "String",
      "Dynamic Programming",
      "Depth-First Search",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 1529,
    "dislikes": 81,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"116K\", \"totalSubmission\": \"197.1K\", \"totalAcceptedRaw\": 115992, \"totalSubmissionRaw\": 197146, \"acRate\": \"58.8%\"}",
    "title_pt": "Trilha da Liberdade",
    "description_pt": "<p>No videogame Fallout 4, a missão <strong>&quot;Road to Freedom&quot;</strong> exige que os jogadores alcancem um mostrador de metal chamado <strong>&quot;Freedom Trail Ring&quot;</strong> e usem o mostrador para soletrar uma palavra-chave específica para abrir a porta.</p>\n\n<p>Dada uma string <code>ring</code> que representa o código gravado no anel externo e outra string <code>key</code> que representa a palavra-chave que precisa ser soletrada, retorne <em>o número mínimo de passos para soletrar todos os caracteres da palavra-chave</em>.</p>\n\n<p>Inicialmente, o primeiro caractere do anel está alinhado na direção de <code>&quot;12:00&quot;</code>. Você deve soletrar todos os caracteres em <code>key</code> um por um, girando <code>ring</code> no sentido horário ou anti-horário para fazer cada caractere da string key ficar alinhado na direção de <code>&quot;12:00&quot;</code> e então pressionando o botão central.</p>\n\n<p>Na etapa de girar o anel para soletrar o caractere <code>key[i]</code>:</p>\n\n<ol>\n\t<li>Você pode girar o anel no sentido horário ou anti-horário por uma posição, o que conta como <strong>um passo</strong>. O objetivo final da rotação é alinhar um dos caracteres de <code>ring</code> na direção de <code>&quot;12:00&quot;</code>, onde esse caractere deve ser igual a <code>key[i]</code>.</li>\n\t<li>Se o caractere <code>key[i]</code> tiver sido alinhado na direção de <code>&quot;12:00&quot;</code>, pressione o botão central para soletrar, o que também conta como <strong>um passo</strong>. Depois da pressão, você pode começar a soletrar o próximo caractere da key (próxima etapa). Caso contrário, você terá concluído toda a soletração.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/22/ring.jpg\" style=\"width: 450px; height: 450px;\" />\n<pre>\n<strong>Entrada:</strong> ring = &quot;godding&quot;, key = &quot;gd&quot;\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong>\nPara o primeiro caractere de key, &#39;g&#39;, como ele já está na posição correta, precisamos de apenas 1 passo para soletrar esse caractere. \nPara o segundo caractere de key, &#39;d&#39;, precisamos girar o anel &quot;godding&quot; no sentido anti-horário por dois passos para fazê-lo se tornar &quot;ddinggo&quot;.\nAlém disso, precisamos de mais 1 passo para a soletração.\nPortanto, a saída final é 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ring = &quot;godding&quot;, key = &quot;godding&quot;\n<strong>Saída:</strong> 13\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= ring.length, key.length &lt;= 100</code></li>\n\t<li><code>ring</code> and <code>key</code> consist of only lower case English letters.</li>\n\t<li>It is guaranteed that <code>key</code> could always be spelled by rotating <code>ring</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "515",
    "paidOnly": false,
    "title": "Find Largest Value in Each Tree Row",
    "titleSlug": "find-largest-value-in-each-tree-row",
    "url": "https://leetcode.com/problems/find-largest-value-in-each-tree-row",
    "description_url": "https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg\" style=\"width: 300px; height: 172px;\" />\n<pre>\n<strong>Input:</strong> root = [1,3,2,5,3,null,9]\n<strong>Output:</strong> [1,3,9]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1,2,3]\n<strong>Output:</strong> [1,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-largest-value-in-each-tree-row/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Breadth First Search (BFS)\n\n**Intuition**\n\n> If you are not familiar with BFS traversal, we suggest you read our relevant [LeetCode Explore Card](https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/1376/).\n\nBFS is perfect when we are dealing specifically with rows/levels of a binary tree. With BFS, we handle one row of the tree at a time.\n\nHere, we need to find the maximum value in each row. We can simply perform a BFS and for each row, keep track of the maximum value we have seen so far. We will initialize an integer `currMax` to a small value like negative infinity. Then we go through the row and try to update `currMax` when we see larger values. After handling the row, we add `currMax` to our answer.\n\n**Algorithm**\n\n1. If the `root` is null (empty) tree, just return an empty list.\n2. Initialize the answer list `ans` and a `queue` with the `root` to perform BFS.\n3. Perform BFS - while the `queue` is not empty:\n    - Initialize `currMax` to a small value and save the length of the queue in `currentLength`.\n    - Iterate `currentLength` times:\n        - Remove a `node` from the `queue`.\n        - Update `currMax` with `node.val` if it is larger.\n        - For each child of `node`, if it is not null, push it to the `queue`.\n    - Add `currMax` to `ans`.\n4. Return `ans`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/P7pFhbid/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"P7pFhbid\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the BFS, we visit each node in the tree once. At each node, we perform $$O(1)$$ work.\n\n* Space complexity: $$O(n)$$\n\n    In a perfect binary tree, the final row has $$O(\\frac{n}{2}) = O(n)$$ nodes, all of which will be in `queue`.\n    \n<br/>\n\n---\n\n### Approach 2: Depth First Search (DFS)\n\n**Intuition**\n\n> Note: This problem is perfect for BFS, but an interviewer might you to implement DFS as a follow-up. We have included a DFS approach for completeness.\n\nIn BFS, we handle each row explicitly, so it's easy to just keep track of the maximum value as we traverse through the row.\n\nIn DFS, the order in which we move through the tree is not related to the rows. Thus, we need to be more creative to find the maximum value in each row. The first observation to make is that each row can be described by the depth of its nodes.\n\n![depth](../Figures/515/1.png)\n<br>\n\nThe depth of a node is its distance from the root. The root has a depth of `0`, and every child has a depth of `1` greater than its parent. You may also notice that in terms of indices, each node's depth corresponds to its index in the answer.\n\nFor example, if `ans` is our answer list, then `ans[2]` holds the maximum value of all nodes with depth `2`.\n\nIf we keep track of each node's depth during the traversal, then we can update `ans` directly. How do we keep track of the depth? We will pass an additional argument `depth` in our `dfs` function. When we initially call `dfs` with `root`, we will pass `depth = 0`. When we call `dfs` on a child, we will pass `depth + 1`.\n\nThere is one problem: how do we know what length `ans` should be? We will initialize `ans` as an empty list. If we are at a `depth` that would be out of bounds if we tried to access `ans[depth]`, then we will simply initialize the current `node.val` as the maximum value seen at `depth` so far by pushing `node.val` to `ans`.\n\n**Algorithm**\n\n1. Initialize `ans` as an empty list.\n2. Define a function `dfs(node, depth)`:\n    - If `node` is null, return.\n    - If `depth == ans.length`, then push `node.val` to `ans`. Otherwise, try to update `ans[depth]` with `node.val` if its larger.\n    - Call `dfs` on `node.left` and `node.right` with `depth + 1` as the second argument.\n3. Call `dfs(root, 0)` and then `return ans`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/CmiiemQN/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"CmiiemQN\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree and $$h$$ as the max depth of the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the DFS, we visit each node in the tree once. At each node, we perform $$O(1)$$ work.\n\n* Space complexity: $$O(h)$$\n\n    We use extra space for the recursion call stack. The most calls in the call stack at any given time will be the max depth of the tree. In the worst-case scenario where the tree is like a linked list, the max depth will be $$O(n)$$.\n    \n<br/>\n\n---\n\n### Approach 3: DFS, Iterative\n\n**Intuition**\n\nWe can also implement DFS iteratively using a stack. Each entry in the stack will be a pair `node, depth`. We will use a while loop to perform the DFS, with each iteration being analogous to a function call from the previous approach. As such, we will perform the same process in each while loop iteration: try to update `ans` with `node.val`, then push the children of `node` to the stack if they exist.\n\n**Algorithm**\n\n1. If the `root` is null (empty) tree, just return an empty list.\n2. Initialize the answer list `ans` and a `stack` with `(root, 0)`.\n3. While the `stack` is not empty:\n    - Pop `(node, depth)` from the stack.\n    - If `depth == ans.length`, then push `node.val` to `ans`. Otherwise, try to update `ans[depth]` with `node.val` if its larger.\n    - If `node.left` is not null, push `(node.left, depth + 1)` to `stack`.\n    - If `node.right` is not null, push `(node.right, depth + 1)` to `stack`.\n4. Return `ans`.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/Gc9wyzzK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Gc9wyzzK\"></iframe>\n\n**Complexity Analysis**\n\nGiven $$n$$ as the number of nodes in the tree and $$h$$ as the max depth of the tree,\n\n* Time complexity: $$O(n)$$\n\n    During the DFS, we visit each node in the tree once. At each node, we perform $$O(1)$$ work.\n\n* Space complexity: $$O(h)$$\n\n    We use extra space for the recursion call stack. The most calls in the call stack at any given time will be the max depth of the tree. In the worst-case scenario where the tree is like a linked list, the max depth will be $$O(n)$$.\n\n    We pop the top node from the stack and then push its child nodes onto the stack based on the DFS traversal strategy. This process of pushing and popping forms a path-like structure within the stack, and the length of this path will not exceed the height of the tree. Therefore, $$O(h)$$ space will be used.\n    \n<br/>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def largestValues(self, root: Optional[TreeNode]) -> List[int]:\n    if not root:\n      return []\n\n    ans = []\n    q = deque([root])\n\n    while q:\n      maxi = -math.inf\n      for _ in range(len(q)):\n        root = q.popleft()\n        maxi = max(maxi, root.val)\n        if root.left:\n          q.append(root.left)\n        if root.right:\n          q.append(root.right)\n      ans.append(maxi)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> largestValues(TreeNode root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<Integer> ans = new ArrayList<>();\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      int max = Integer.MIN_VALUE;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode node = q.poll();\n        max = Math.max(max, node.val);\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n      }\n      ans.add(max);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> largestValues(TreeNode* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<int> ans;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      int maxi = INT_MIN;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode* node = q.front();\n        q.pop();\n        maxi = max(maxi, node->val);\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n      }\n      ans.push_back(maxi);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/515.html",
    "category": "Algorithms",
    "acceptance_rate": 66.27357739395106,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 4052,
    "dislikes": 128,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"478.6K\", \"totalSubmission\": \"722.1K\", \"totalAcceptedRaw\": 478589, \"totalSubmissionRaw\": 722141, \"acRate\": \"66.3%\"}",
    "title_pt": "Encontrar o Maior Valor em Cada Nível da Árvore",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>um array com o maior valor em cada linha</em> da árvore <strong>(indexado em 0)</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg\" style=\"width: 300px; height: 172px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,3,2,5,3,null,9]\n<strong>Saída:</strong> [1,3,9]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,2,3]\n<strong>Saída:</strong> [1,3]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore estará no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "516",
    "paidOnly": false,
    "title": "Longest Palindromic Subsequence",
    "titleSlug": "longest-palindromic-subsequence",
    "url": "https://leetcode.com/problems/longest-palindromic-subsequence",
    "description_url": "https://leetcode.com/problems/longest-palindromic-subsequence/description/",
    "description": "<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p>\n\n<p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;bbbab&quot;\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;cbbd&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consists only of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-palindromic-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestPalindromeSubseq(self, s: str) -> int:\n    # Dp(i, j) := LPS's length in s[i..j]\n    @functools.lru_cache(None)\n    def dp(i: int, j: int) -> int:\n      if i > j:\n        return 0\n      if i == j:\n        return 1\n      if s[i] == s[j]:\n        return 2 + dp(i + 1, j - 1)\n      return max(dp(i + 1, j), dp(i, j - 1))\n\n    return dp(0, len(s) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestPalindromeSubseq(String s) {\n    final int n = s.length();\n    // dp[i][j] := LPS's length in s[i..j]\n    dp = new int[n][n];\n    return lps(s, 0, n - 1);\n  }\n\n  private int[][] dp;\n\n  private int lps(final String s, int i, int j) {\n    if (i > j)\n      return 0;\n    if (i == j)\n      return 1;\n    if (dp[i][j] > 0)\n      return dp[i][j];\n\n    if (s.charAt(i) == s.charAt(j))\n      dp[i][j] = 2 + lps(s, i + 1, j - 1);\n    else\n      dp[i][j] = Math.max(lps(s, i + 1, j), lps(s, i, j - 1));\n\n    return dp[i][j];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestPalindromeSubseq(string s) {\n    const int n = s.length();\n    // dp[i][j] := LPS's length in s[i..j]\n    dp.resize(n, vector<int>(n));\n    return lps(s, 0, n - 1);\n  }\n\n private:\n  vector<vector<int>> dp;\n\n  int lps(const string& s, int i, int j) {\n    if (i > j)\n      return 0;\n    if (i == j)\n      return 1;\n    if (dp[i][j])\n      return dp[i][j];\n\n    if (s[i] == s[j])\n      dp[i][j] = 2 + lps(s, i + 1, j - 1);\n    else\n      dp[i][j] = max(lps(s, i + 1, j), lps(s, i, j - 1));\n\n    return dp[i][j];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/516.html",
    "category": "Algorithms",
    "acceptance_rate": 63.93320447204866,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 9920,
    "dislikes": 335,
    "similar_questions": "[{\"title\": \"Longest Palindromic Substring\", \"titleSlug\": \"longest-palindromic-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindromic Substrings\", \"titleSlug\": \"palindromic-substrings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Different Palindromic Subsequences\", \"titleSlug\": \"count-different-palindromic-subsequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Longest Common Subsequence\", \"titleSlug\": \"longest-common-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Palindromic Subsequence II\", \"titleSlug\": \"longest-palindromic-subsequence-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximize Palindrome Length From Subsequences\", \"titleSlug\": \"maximize-palindrome-length-from-subsequences\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Product of the Length of Two Palindromic Subsequences\", \"titleSlug\": \"maximum-product-of-the-length-of-two-palindromic-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"614.2K\", \"totalSubmission\": \"960.7K\", \"totalAcceptedRaw\": 614211, \"totalSubmissionRaw\": 960713, \"acRate\": \"63.9%\"}",
    "title_pt": "Subsequência Palindrômica Mais Longa",
    "description_pt": "<p>Dada uma string <code>s</code>, encontre <em>o comprimento da mais longa <strong>subsequência</strong> palindrômica em</em> <code>s</code>.</p>\n\n<p>Uma <strong>subsequência</strong> é uma sequência que pode ser derivada de outra sequência ao deletar alguns ou nenhum elemento sem alterar a ordem dos elementos restantes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;bbbab&quot;\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Uma possível subsequência palindrômica mais longa é &quot;bbbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;cbbd&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Uma possível subsequência palindrômica mais longa é &quot;bb&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do alfabeto ইংlês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "517",
    "paidOnly": false,
    "title": "Super Washing Machines",
    "titleSlug": "super-washing-machines",
    "url": "https://leetcode.com/problems/super-washing-machines",
    "description_url": "https://leetcode.com/problems/super-washing-machines/description/",
    "description": "<p>You have <code>n</code> super washing machines on a line. Initially, each washing machine has some dresses or is empty.</p>\n\n<p>For each move, you could choose any <code>m</code> (<code>1 &lt;= m &lt;= n</code>) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.</p>\n\n<p>Given an integer array <code>machines</code> representing the number of dresses in each washing machine from left to right on the line, return <em>the minimum number of moves to make all the washing machines have the same number of dresses</em>. If it is not possible to do it, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> machines = [1,0,5]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\n1st move:    1     0 &lt;-- 5    =&gt;    1     1     4\n2nd move:    1 &lt;-- 1 &lt;-- 4    =&gt;    2     1     3\n3rd move:    2     1 &lt;-- 3    =&gt;    2     2     2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> machines = [0,3,0]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong>\n1st move:    0 &lt;-- 3     0    =&gt;    1     2     0\n2nd move:    1     2 --&gt; 0    =&gt;    1     1     1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> machines = [0,2,0]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>\nIt&#39;s impossible to make all three washing machines have the same number of dresses.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == machines.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/super-washing-machines/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMinMoves(self, machines: List[int]) -> int:\n    dresses = sum(machines)\n\n    if dresses % len(machines) != 0:\n      return -1\n\n    ans = 0\n    average = dresses // len(machines)\n    inout = 0\n\n    for dress in machines:\n      inout += dress - average\n      ans = max(ans, abs(inout), dress - average)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMinMoves(int[] machines) {\n    int dresses = Arrays.stream(machines).sum();\n    if (dresses % machines.length != 0)\n      return -1;\n\n    int ans = 0;\n    int inout = 0;\n    final int average = dresses / machines.length;\n\n    for (final int dress : machines) {\n      inout += dress - average;\n      ans = Math.max(ans, Math.max(Math.abs(inout), dress - average));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMinMoves(vector<int>& machines) {\n    const int dresses = accumulate(begin(machines), end(machines), 0);\n    if (dresses % machines.size() != 0)\n      return -1;\n\n    int ans = 0;\n    int inout = 0;\n    const int average = dresses / machines.size();\n\n    for (const int dress : machines) {\n      inout += dress - average;\n      ans = max({ans, abs(inout), dress - average});\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/517.html",
    "category": "Algorithms",
    "acceptance_rate": 42.37485881666646,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 790,
    "dislikes": 218,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"34.1K\", \"totalSubmission\": \"80.6K\", \"totalAcceptedRaw\": 34141, \"totalSubmissionRaw\": 80569, \"acRate\": \"42.4%\"}",
    "title_pt": "Máquinas de Lavar Superpotentes",
    "description_pt": "<p>Você tem <code>n</code> máquinas de lavar superpotentes em uma linha. Inicialmente, cada máquina de lavar tem algumas roupas ou está vazia.</p>\n\n<p>Em cada movimento, você pode escolher quaisquer <code>m</code> (<code>1 &lt;= m &lt;= n</code>) máquinas de lavar e passar uma roupa de cada máquina de lavar para uma de suas máquinas de lavar adjacentes ao mesmo tempo.</p>\n\n<p>Dado um array de inteiros <code>machines</code> representando o número de roupas em cada máquina de lavar, da esquerda para a direita na linha, retorne <em>o número mínimo de movimentos para fazer com que todas as máquinas de lavar tenham o mesmo número de roupas</em>. Se não for possível fazer isso, retorne <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> machines = [1,0,5]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>\n1º movimento:    1     0 &lt;-- 5    =&gt;    1     1     4\n2º movimento:    1 &lt;-- 1 &lt;-- 4    =&gt;    2     1     3\n3º movimento:    2     1 &lt;-- 3    =&gt;    2     2     2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> machines = [0,3,0]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong>\n1º movimento:    0 &lt;-- 3     0    =&gt;    1     2     0\n2º movimento:    1     2 --&gt; 0    =&gt;    1     1     1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> machines = [0,2,0]\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong>\nÉ impossível fazer com que todas as três máquinas de lavar tenham o mesmo número de roupas.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == machines.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= machines[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "518",
    "paidOnly": false,
    "title": "Coin Change II",
    "titleSlug": "coin-change-ii",
    "url": "https://leetcode.com/problems/coin-change-ii",
    "description_url": "https://leetcode.com/problems/coin-change-ii/description/",
    "description": "<p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>\n\n<p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p>\n\n<p>You may assume that you have an infinite number of each kind of coin.</p>\n\n<p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> amount = 5, coins = [1,2,5]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> amount = 3, coins = [2]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> amount = 10, coins = [10]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= coins.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= coins[i] &lt;= 5000</code></li>\n\t<li>All the values of <code>coins</code> are <strong>unique</strong>.</li>\n\t<li><code>0 &lt;= amount &lt;= 5000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/coin-change-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def change(self, amount: int, coins: List[int]) -> int:\n    dp = [1] + [0] * amount\n\n    for coin in coins:\n      for i in range(coin, amount + 1):\n        dp[i] += dp[i - coin]\n\n    return dp[amount]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int change(int amount, int[] coins) {\n    int[] dp = new int[amount + 1];\n    dp[0] = 1;\n\n    for (final int coin : coins)\n      for (int i = coin; i <= amount; ++i)\n        dp[i] += dp[i - coin];\n\n    return dp[amount];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int change(int amount, vector<int>& coins) {\n    vector<int> dp(amount + 1);\n    dp[0] = 1;\n\n    for (const int coin : coins)\n      for (int i = coin; i <= amount; ++i)\n        dp[i] += dp[i - coin];\n\n    return dp[amount];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/518.html",
    "category": "Algorithms",
    "acceptance_rate": 62.686469464158826,
    "topics": [
      "Array",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 9746,
    "dislikes": 208,
    "similar_questions": "[{\"title\": \"Maximum Value of K Coins From Piles\", \"titleSlug\": \"maximum-value-of-k-coins-from-piles\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Earn Points\", \"titleSlug\": \"number-of-ways-to-earn-points\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count of Sub-Multisets With Bounded Sum\", \"titleSlug\": \"count-of-sub-multisets-with-bounded-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Length of the Longest Subsequence That Sums to Target\", \"titleSlug\": \"length-of-the-longest-subsequence-that-sums-to-target\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Number of Ways to Make the Sum\", \"titleSlug\": \"the-number-of-ways-to-make-the-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"794.8K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 794836, \"totalSubmissionRaw\": 1267944, \"acRate\": \"62.7%\"}",
    "title_pt": "Troca de Moedas II",
    "description_pt": "<p>Você recebe um array de inteiros <code>coins</code> representando moedas de diferentes denominações e um inteiro <code>amount</code> representando um valor total em dinheiro.</p>\n\n<p>Retorne <em>o número de combinações que somam esse valor</em>. Se esse valor em dinheiro não puder ser formado por qualquer combinação das moedas, retorne <code>0</code>.</p>\n\n<p>Você pode assumir que tem uma quantidade infinita de cada tipo de moeda.</p>\n\n<p>A resposta tem garantia de caber em um inteiro com sinal de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> amount = 5, coins = [1,2,5]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> há quatro maneiras de formar o valor:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> amount = 3, coins = [2]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> o valor 3 não pode ser formado apenas com moedas de 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> amount = 10, coins = [10]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= coins.length &lt;= 300</code></li>\n\t<li><code>1 &lt;= coins[i] &lt;= 5000</code></li>\n\t<li>Todos os valores de <code>coins</code> são <strong>únicos</strong>.</li>\n\t<li><code>0 &lt;= amount &lt;= 5000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "519",
    "paidOnly": false,
    "title": "Random Flip Matrix",
    "titleSlug": "random-flip-matrix",
    "url": "https://leetcode.com/problems/random-flip-matrix",
    "description_url": "https://leetcode.com/problems/random-flip-matrix/description/",
    "description": "<p>There is an <code>m x n</code> binary grid <code>matrix</code> with all the values set <code>0</code> initially. Design an algorithm to randomly pick an index <code>(i, j)</code> where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>. All the indices <code>(i, j)</code> where <code>matrix[i][j] == 0</code> should be equally likely to be returned.</p>\n\n<p>Optimize your algorithm to minimize the number of calls made to the <strong>built-in</strong> random function of your language and optimize the time and space complexity.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(int m, int n)</code> Initializes the object with the size of the binary matrix <code>m</code> and <code>n</code>.</li>\n\t<li><code>int[] flip()</code> Returns a random index <code>[i, j]</code> of the matrix where <code>matrix[i][j] == 0</code> and flips it to <code>1</code>.</li>\n\t<li><code>void reset()</code> Resets all the values of the matrix to be <code>0</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;reset&quot;, &quot;flip&quot;]\n[[3, 1], [], [], [], [], []]\n<strong>Output</strong>\n[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]\n\n<strong>Explanation</strong>\nSolution solution = new Solution(3, 1);\nsolution.flip();  // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip();  // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip();  // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip();  // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li>There will be at least one free cell for each call to <code>flip</code>.</li>\n\t<li>At most <code>1000</code> calls will be made to <code>flip</code> and <code>reset</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/random-flip-matrix/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int n_rows, int n_cols) {\n    this.rows = n_rows;\n    this.cols = n_cols;\n    this.total = n_rows * n_cols;\n  }\n\n  public int[] flip() {\n    // All candidates are used out\n    if (used.size() == total)\n      return new int[] {};\n\n    int index = new Random().nextInt(total);\n    while (used.contains(index))\n      index = ++index % total;\n    used.add(index);\n\n    return new int[] {index / cols, index % cols};\n  }\n\n  public void reset() {\n    used.clear();\n  }\n\n  private Set<Integer> used = new HashSet<>();\n  private int rows;\n  private int cols;\n  private int total;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(int n_rows, int n_cols)\n      : rows(n_rows), cols(n_cols), total(n_rows * n_cols) {}\n\n  vector<int> flip() {\n    // All candidates are used out\n    if (used.size() == total)\n      return {};\n\n    int index = rand() % total;\n    while (used.count(index))\n      index = ++index % total;\n    used.insert(index);\n\n    return {index / cols, index % cols};\n  }\n\n  void reset() {\n    used = {};\n  }\n\n private:\n  unordered_set<int> used;\n  int rows;\n  int cols;\n  int total;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/519.html",
    "category": "Algorithms",
    "acceptance_rate": 43.382190218409,
    "topics": [
      "Hash Table",
      "Math",
      "Reservoir Sampling",
      "Randomized"
    ],
    "hints": [],
    "likes": 449,
    "dislikes": 132,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"25.5K\", \"totalSubmission\": \"58.7K\", \"totalAcceptedRaw\": 25484, \"totalSubmissionRaw\": 58743, \"acRate\": \"43.4%\"}",
    "title_pt": "Matriz com Flip Aleatório",
    "description_pt": "<p>Há uma grade binária <code>m x n</code> <code>matrix</code> com todos os valores definidos como <code>0</code> inicialmente. Projete um algoritmo para escolher aleatoriamente um índice <code>(i, j)</code> onde <code>matrix[i][j] == 0</code> e alterná-lo para <code>1</code>. Todos os índices <code>(i, j)</code> em que <code>matrix[i][j] == 0</code> devem ter a mesma probabilidade de serem retornados.</p>\n\n<p>Otimize seu algoritmo para minimizar o número de chamadas feitas à função aleatória <strong>embutida</strong> da sua linguagem e otimize a complexidade de tempo e espaço.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(int m, int n)</code> Inicializa o objeto com o tamanho da matriz binária <code>m</code> e <code>n</code>.</li>\n\t<li><code>int[] flip()</code> Retorna um índice aleatório <code>[i, j]</code> da matriz em que <code>matrix[i][j] == 0</code> e alterna-o para <code>1</code>.</li>\n\t<li><code>void reset()</code> Redefine todos os valores da matriz para <code>0</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;flip&quot;, &quot;reset&quot;, &quot;flip&quot;]\n[[3, 1], [], [], [], [], []]\n<strong>Saída</strong>\n[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]\n\n<strong>Explicação</strong>\nSolution solution = new Solution(3, 1);\nsolution.flip();  // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip();  // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip();  // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip();  // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li>There will be at least one free cell for each call to <code>flip</code>.</li>\n\t<li>At most <code>1000</code> calls will be made to <code>flip</code> and <code>reset</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "520",
    "paidOnly": false,
    "title": "Detect Capital",
    "titleSlug": "detect-capital",
    "url": "https://leetcode.com/problems/detect-capital",
    "description_url": "https://leetcode.com/problems/detect-capital/description/",
    "description": "<p>We define the usage of capitals in a word to be right when one of the following cases holds:</p>\n\n<ul>\n\t<li>All letters in this word are capitals, like <code>&quot;USA&quot;</code>.</li>\n\t<li>All letters in this word are not capitals, like <code>&quot;leetcode&quot;</code>.</li>\n\t<li>Only the first letter in this word is capital, like <code>&quot;Google&quot;</code>.</li>\n</ul>\n\n<p>Given a string <code>word</code>, return <code>true</code> if the usage of capitals in it is right.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> word = \"USA\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> word = \"FlaG\"\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length &lt;= 100</code></li>\n\t<li><code>word</code> consists of lowercase and uppercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/detect-capital/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def detectCapitalUse(self, word: str) -> bool:\n    return word.isupper() or word.islower() or word.istitle()",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean detectCapitalUse(String word) {\n    return word.equals(word.toUpperCase()) ||\n        word.substring(1).equals(word.substring(1).toLowerCase());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool detectCapitalUse(string word) {\n    for (int i = 1; i < word.length(); ++i)\n      if (isupper(word[1]) != isupper(word[i]) ||\n          islower(word[0]) && isupper(word[i]))\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/520.html",
    "category": "Algorithms",
    "acceptance_rate": 56.13633222092771,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 3480,
    "dislikes": 465,
    "similar_questions": "[{\"title\": \"Capitalize the Title\", \"titleSlug\": \"capitalize-the-title\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Special Characters II\", \"titleSlug\": \"count-the-number-of-special-characters-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Special Characters I\", \"titleSlug\": \"count-the-number-of-special-characters-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"483.3K\", \"totalSubmission\": \"860.9K\", \"totalAcceptedRaw\": 483276, \"totalSubmissionRaw\": 860897, \"acRate\": \"56.1%\"}",
    "title_pt": "Detectar Uso Correto de Maiúsculas",
    "description_pt": "<p>Definimos o uso de maiúsculas em uma palavra como correto quando um dos seguintes casos ocorre:</p>\n\n<ul>\n\t<li>Todas as letras desta palavra são maiúsculas, como <code>&quot;USA&quot;</code>.</li>\n\t<li>Todas as letras desta palavra não são maiúsculas, como <code>&quot;leetcode&quot;</code>.</li>\n\t<li>Apenas a primeira letra desta palavra é maiúscula, como <code>&quot;Google&quot;</code>.</li>\n</ul>\n\n<p>Dada uma string <code>word</code>, retorne <code>true</code> se o uso de maiúsculas nela estiver correto.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> word = \"USA\"\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> word = \"FlaG\"\n<strong>Saída:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word.length &lt;= 100</code></li>\n\t<li><code>word</code> consiste em letras inglesas minúsculas e maiúsculas.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "521",
    "paidOnly": false,
    "title": "Longest Uncommon Subsequence I",
    "titleSlug": "longest-uncommon-subsequence-i",
    "url": "https://leetcode.com/problems/longest-uncommon-subsequence-i",
    "description_url": "https://leetcode.com/problems/longest-uncommon-subsequence-i/description/",
    "description": "<p>Given two strings <code>a</code> and <code>b</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between </em><code>a</code> <em>and</em> <code>b</code>. <em>If no such uncommon subsequence exists, return</em> <code>-1</code><em>.</em></p>\n\n<p>An <strong>uncommon subsequence</strong> between two strings is a string that is a <strong><span data-keyword=\"subsequence-string\">subsequence</span> of exactly one of them</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> One longest uncommon subsequence is &quot;aba&quot; because &quot;aba&quot; is a subsequence of &quot;aba&quot; but not &quot;cdc&quot;.\nNote that &quot;cdc&quot; is also a longest uncommon subsequence.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>&nbsp;The longest uncommon subsequences are &quot;aaa&quot; and &quot;bbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot;\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>&nbsp;Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be <code>-1</code>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 100</code></li>\n\t<li><code>a</code> and <code>b</code> consist of lower-case English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-uncommon-subsequence-i/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n\n---\n\n### Overview\n\nA subsequence of a string is a sequence of its characters. It maintains the order of the characters but does not need to be continuous. Each character may occur up to as many times as it occurs in the original string.\n\n> An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.\n\nOur objective is to find the length of the longest uncommon subsequence between two strings, `a` and `b`. If none exists, we must return `-1`.\n\nA real-world application of finding uncommon subsequences is plagiarism detection, where long common subsequences could signify plagiarism.\n\n---\n\n### Approach: Maximum Length\n\n#### Intuition\n\nLet's approach this problem by viewing some examples. \n\n**What are the characteristics of `a` and `b` when no uncommon subsequence exists?**\n\n##### Example 1: (Example 3 from the problem description)\n\n>***Input:*** a = \"aaa\", b = \"aaa\" \\\n***Output:*** = -1 \\\n***Explanation:*** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.\n\n##### Example 2: \n\n>***Input:*** a = \"xyz\", b = \"xyz\" \\\n***Output:*** = -1 \\\n***Explanation:*** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.\n\nWhat do these two examples have in common? Strings `a` and `b` contain the same characters in the same order. We realize that if `a` and `b` are equal, an uncommon subsequence does not exist.\n\n---\n\n**What patterns can we observe between the longest uncommon subsequences?**\n\n##### Example 3: \n\n>***Input:*** a = \"xyz\", b = \"wxyz\" \\\n***Output:*** = 4 \\\n***Explanation:*** Every subsequence of string a is also a subsequence of string b. The subsequence \"wxyz\" is an uncommon subsequence, as it is not a subsequence of `a`.\n\n##### Example 4:  (Example 1 from the problem description)\n\n>***Input:*** a = \"aba\", b = \"cdc\" \\\n***Output:*** = 3 \\\n***Explanation:*** One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.\n\n We can observe that the longest uncommon subsequences in examples 3 and 4 are all entire strings. We notice that \"cd\" is an uncommon subsequence of `b` in the above example, but it is not the longest. We can reason that if the two strings are not identical, then the longest uncommon subsequence will be the longer string because it has some additional character(s) that guarantee it is uncommon from the other string, and it is also the longest possible subsequence we can create. If both strings are the same length but are not identical, they will both be longest uncommon subsequences, as in example 4, and we can return the length of either.\n\n\n\n#### Algorithm\n\n1. If `a` is equal to `b`:\n    1. Return `-1`, there is no uncommon subsequence.\n2. Else:\n    1. Calculate the lengths of `a` and `b` and return the length of the longer string.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/iV7XKwVJ/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"iV7XKwVJ\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n)$ \n    \n    In the worst case, string comparison will take $O(n)$. \n    \n    In the best case, string comparison can take $O(1)$. Some languages, including Java, optimize string comparison and can determine immediately that the strings are not the same if they are not the same length. For these languages, it still takes $O(n)$ in the worst case when the strings are the same.\n\n* Space complexity:\n  \n    $O(1)$ because we do not use data structures that require additional space.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLUSlength(self, a: str, b: str) -> int:\n    return -1 if a == b else max(len(a), len(b))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findLUSlength(String a, String b) {\n    return a.equals(b) ? -1 : Math.max(a.length(), b.length());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLUSlength(string a, string b) {\n    return a == b ? -1 : max(a.length(), b.length());\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/521.html",
    "category": "Algorithms",
    "acceptance_rate": 61.30474303694208,
    "topics": [
      "String"
    ],
    "hints": [
      "Think very simple.",
      "If <code>a == b</code>, the answer is -1.",
      "Otherwise, the answer is the string <code>a</code> or the string <code>b</code>."
    ],
    "likes": 75,
    "dislikes": 255,
    "similar_questions": "[{\"title\": \"Longest Uncommon Subsequence II\", \"titleSlug\": \"longest-uncommon-subsequence-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"131.5K\", \"totalSubmission\": \"214.5K\", \"totalAcceptedRaw\": 131514, \"totalSubmissionRaw\": 214525, \"acRate\": \"61.3%\"}",
    "title_pt": "Subsequência Incomum Mais Longa I",
    "description_pt": "<p>Dadas duas strings <code>a</code> e <code>b</code>, retorne <em>o comprimento da <strong>subsequência incomum mais longa</strong> entre </em><code>a</code> <em>e</em> <code>b</code>. <em>Se não existir tal subsequência incomum, retorne</em> <code>-1</code><em>.</em></p>\n\n<p>Uma <strong>subsequência incomum</strong> entre duas strings é uma string que é uma <strong><span data-keyword=\"subsequence-string\">subsequência</span> de exatamente uma delas</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = &quot;aba&quot;, b = &quot;cdc&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Uma subsequência incomum mais longa é &quot;aba&quot;, porque &quot;aba&quot; é uma subsequência de &quot;aba&quot;, mas não de &quot;cdc&quot;.\nObserve que &quot;cdc&quot; também é uma subsequência incomum mais longa.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = &quot;aaa&quot;, b = &quot;bbb&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>&nbsp;As subsequências incomuns mais longas são &quot;aaa&quot; e &quot;bbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = &quot;aaa&quot;, b = &quot;aaa&quot;\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong>&nbsp;Toda subsequência da string a também é uma subsequência da string b. Da mesma forma, toda subsequência da string b também é uma subsequência da string a. Portanto, a resposta seria <code>-1</code>.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 100</code></li>\n\t<li><code>a</code> e <code>b</code> consistem em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Pense de forma bem simples.",
      "Dica 2: Se <code>a == b</code>, a resposta é -1.",
      "Dica 3: Caso contrário, a resposta é a string <code>a</code> ou a string <code>b</code>."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "522",
    "paidOnly": false,
    "title": "Longest Uncommon Subsequence II",
    "titleSlug": "longest-uncommon-subsequence-ii",
    "url": "https://leetcode.com/problems/longest-uncommon-subsequence-ii",
    "description_url": "https://leetcode.com/problems/longest-uncommon-subsequence-ii/description/",
    "description": "<p>Given an array of strings <code>strs</code>, return <em>the length of the <strong>longest uncommon subsequence</strong> between them</em>. If the longest uncommon subsequence does not exist, return <code>-1</code>.</p>\n\n<p>An <strong>uncommon subsequence</strong> between an array of strings is a string that is a <strong>subsequence of one string but not the others</strong>.</p>\n\n<p>A <strong>subsequence</strong> of a string <code>s</code> is a string that can be obtained after deleting any number of characters from <code>s</code>.</p>\n\n<ul>\n\t<li>For example, <code>&quot;abc&quot;</code> is a subsequence of <code>&quot;aebdc&quot;</code> because you can delete the underlined characters in <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> to get <code>&quot;abc&quot;</code>. Other subsequences of <code>&quot;aebdc&quot;</code> include <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, and <code>&quot;&quot;</code> (empty string).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> strs = [\"aba\",\"cdc\",\"eae\"]\n<strong>Output:</strong> 3\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> strs = [\"aaa\",\"aaa\",\"aa\"]\n<strong>Output:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= strs.length &lt;= 50</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 10</code></li>\n\t<li><code>strs[i]</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-uncommon-subsequence-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLUSlength(self, strs: List[str]) -> int:\n    def isSubsequence(a: str, b: str) -> bool:\n      i = 0\n      j = 0\n\n      while i < len(a) and j < len(b):\n        if a[i] == b[j]:\n          i += 1\n        j += 1\n\n      return i == len(a)\n\n    seen = set()\n    duplicates = set()\n\n    for s in strs:\n      if s in seen:\n        duplicates.add(s)\n      seen.add(s)\n\n    strs.sort(key=lambda s: -len(s))\n\n    for i in range(len(strs)):\n      if strs[i] in duplicates:\n        continue\n      isASubsequence = False\n      for j in range(i):\n        isASubsequence |= isSubsequence(strs[i], strs[j])\n      if not isASubsequence:\n        return len(strs[i])\n\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findLUSlength(String[] strs) {\n    Set<String> seen = new HashSet<>();\n    Set<String> duplicates = new HashSet<>();\n\n    for (final String str : strs)\n      if (seen.contains(str))\n        duplicates.add(str);\n      else\n        seen.add(str);\n\n    Arrays.sort(strs, (a, b) -> b.length() - a.length());\n\n    for (int i = 0; i < strs.length; ++i) {\n      if (duplicates.contains(strs[i]))\n        continue;\n      boolean isASubsequence = false;\n      for (int j = 0; j < i; ++j)\n        isASubsequence |= isSubsequence(strs[i], strs[j]);\n      if (!isASubsequence)\n        return strs[i].length();\n    }\n\n    return -1;\n  }\n\n  // Returns true if a is a subsequence of b\n  private boolean isSubsequence(final String a, final String b) {\n    int i = 0;\n    for (final char c : b.toCharArray())\n      if (i < a.length() && c == a.charAt(i))\n        ++i;\n    return i == a.length();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLUSlength(vector<string>& strs) {\n    unordered_set<string> seen;\n    unordered_set<string> duplicates;\n\n    for (const string& str : strs)\n      if (seen.count(str))\n        duplicates.insert(str);\n      else\n        seen.insert(str);\n\n    sort(begin(strs), end(strs),\n         [](const auto& a, const auto& b) { return a.length() > b.length(); });\n\n    for (int i = 0; i < strs.size(); ++i) {\n      if (duplicates.count(strs[i]))\n        continue;\n      bool isASubsequence = false;\n      for (int j = 0; j < i; ++j)\n        isASubsequence |= isSubsequence(strs[i], strs[j]);\n      if (!isASubsequence)\n        return strs[i].length();\n    }\n\n    return -1;\n  }\n\n private:\n  // Returns true if a is a subsequence of b\n  bool isSubsequence(const string& a, const string& b) {\n    int i = 0;\n    for (const char c : b)\n      if (i < a.length() && c == a[i])\n        ++i;\n    return i == a.length();\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/522.html",
    "category": "Algorithms",
    "acceptance_rate": 42.922707231358736,
    "topics": [
      "Array",
      "Hash Table",
      "Two Pointers",
      "String",
      "Sorting"
    ],
    "hints": [],
    "likes": 533,
    "dislikes": 1348,
    "similar_questions": "[{\"title\": \"Longest Uncommon Subsequence I\", \"titleSlug\": \"longest-uncommon-subsequence-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"59.5K\", \"totalSubmission\": \"138.6K\", \"totalAcceptedRaw\": 59480, \"totalSubmissionRaw\": 138574, \"acRate\": \"42.9%\"}",
    "title_pt": "Subsequência Incomum Mais Longa II",
    "description_pt": "<p>Dado um array de strings <code>strs</code>, retorne <em>o comprimento da <strong>subsequência incomum mais longa</strong> entre elas</em>. Se a subsequência incomum mais longa não existir, retorne <code>-1</code>.</p>\n\n<p>Uma <strong>subsequência incomum</strong> entre um array de strings é uma string que é uma <strong>subsequência de uma string, mas não das outras</strong>.</p>\n\n<p>Uma <strong>subsequência</strong> de uma string <code>s</code> é uma string que pode ser obtida após deletar qualquer número de caracteres de <code>s</code>.</p>\n\n<ul>\n\t<li>Por exemplo, <code>&quot;abc&quot;</code> é uma subsequência de <code>&quot;aebdc&quot;</code> porque você pode deletar os caracteres sublinhados em <code>&quot;a<u>e</u>b<u>d</u>c&quot;</code> para obter <code>&quot;abc&quot;</code>. Outras subsequências de <code>&quot;aebdc&quot;</code> incluem <code>&quot;aebdc&quot;</code>, <code>&quot;aeb&quot;</code>, e <code>&quot;&quot;</code> (string vazia).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> strs = [\"aba\",\"cdc\",\"eae\"]\n<strong>Saída:</strong> 3\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> strs = [\"aaa\",\"aaa\",\"aa\"]\n<strong>Saída:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= strs.length &lt;= 50</code></li>\n\t<li><code>1 &lt;= strs[i].length &lt;= 10</code></li>\n\t<li><code>strs[i]</code> consiste de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "523",
    "paidOnly": false,
    "title": "Continuous Subarray Sum",
    "titleSlug": "continuous-subarray-sum",
    "url": "https://leetcode.com/problems/continuous-subarray-sum",
    "description_url": "https://leetcode.com/problems/continuous-subarray-sum/description/",
    "description": "<p>Given an integer array nums and an integer k, return <code>true</code> <em>if </em><code>nums</code><em> has a <strong>good subarray</strong> or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>A <strong>good subarray</strong> is a subarray where:</p>\n\n<ul>\n\t<li>its length is <strong>at least two</strong>, and</li>\n\t<li>the sum of the elements of the subarray is a multiple of <code>k</code>.</li>\n</ul>\n\n<p><strong>Note</strong> that:</p>\n\n<ul>\n\t<li>A <strong>subarray</strong> is a contiguous part of the array.</li>\n\t<li>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6\n<strong>Output:</strong> true\n<strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [23,2,6,4,7], k = 13\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/continuous-subarray-sum/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nThe problem asks us to determine if there exists a subarray in the given integer array `nums` where the sum of its elements is divisible by an integer `k`. \n\n**Key Observations:**\n1. The length of the subarray should be at least two.\n2. The constraints indicate that the problem must be solved in linear or log-linear time complexity, in terms of the size of the given array.\n\n---\n\n### Approach 1: Prefix Sum and Hashing\n\n#### Intuition\n\nOne brute force approach for this problem can be to find out the sum of all subarrays of the array and check if there exists a subarray with a sum divisible by `k`. Since the number of subarrays in an array of size `n` is `n * (n - 1) / 2`, the time complexity to calculate all possible subarrays is $O(n^2)$, and calculating the sum for each subarray takes $O(n)$. Therefore, the total time complexity is $O(n^3)$, which will give a Time Limit Exceeded judgment.\n\nRecall that prefix sums are particularly useful to calculate the sum of subarrays. The sum of the subarray starting at the index `i + 1` and ending at `j` (inclusive) is computed by $prefix_j - prefix_i$ where $prefix_i$ denotes the prefix sum up to index `i`. We can find out if there exists a subarray with a sum divisible by `k`, as shown below:\n\n![prefix sum formula](../Figures/523/Slide1.png)\n\nSince we are only concerned with the modulo of the prefix sum, we start with an integer `prefixMod` to store the remainder of the `prefixSum` with `k` progressively. We can find the longest subarray that satisfies the above conditions by calculating the difference between the current index and the first index with the value `prefixMod`. This is explained with an example shown below:\n\n![prefix sum formula2](../Figures/523/Slide2.png)\n\nA hashmap provides constant lookup and insertion time for the values in the list. Therefore, we initialize a hashmap `modSeen` with `prefixMod` as the key and the first index of each value of `prefixMod` as the value.\n\nWe iterate over all the elements from the beginning of `nums`. We set `prefixMod = (prefixMod + nums[i]) % k` for each element to find the remainder of the prefix sum when divided by `k`. \n\nIf the key `prefixMod` exists in the hashmap and the size of the subarray is at least 1, then we can return `true` as the output. If the key does not exist, we can store the current index in the hashmap with `prefixMod` as the key.\n\n#### Algorithm\n\n1. Initialize an integer `prefixMod = 0` and a hashmap `modSeen`. Initialize `modSeen[0]` with -1 to account for the initial value of prefixMod.\n2. Iterate over all the elements of `nums`:\n   - Compute the `prefixMod` as `prefixMod = (prefixMod + nums[i]) % k`.\n   - If `prefixMod` exists in the hashmap:\n     - If the size of the longest subarray with modulo `k` is at least 2.\n       - Return `true`.  \n   - If `prefixMod` doesn't exist in the hashmap:\n     - Set `modSeen[prefixMod] = i`. \n3. Return `false`.\n\n!?!../Documents/523/slideshow1.json:960,540!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/8p3J3RiG/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8p3J3RiG\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of elements in `nums`.\n\n- Time complexity: $O(n)$\n\n We iterate through the array exactly once. In each iteration, we perform a search operation in the hashmap that takes $O(1)$ time. Therefore, the time complexity can be stated as $O(n)$.\n\n- Space complexity: $O(n)$\n\n In each iteration, we insert a key-value pair in the hashmap. The space complexity is $O(n)$ because the size of the hashmap is proportional to the size of the list after $n$ iterations.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n    prefix = 0\n    prefixToIndex = {0: -1}\n\n    for i, num in enumerate(nums):\n      prefix += num\n      if k != 0:\n        prefix %= k\n      if prefix in prefixToIndex:\n        if i - prefixToIndex[prefix] > 1:\n          return True\n      else:\n        prefixToIndex[prefix] = i\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkSubarraySum(int[] nums, int k) {\n    int prefix = 0;\n    Map<Integer, Integer> prefixToIndex = new HashMap<>();\n    prefixToIndex.put(0, -1);\n\n    for (int i = 0; i < nums.length; ++i) {\n      prefix += nums[i];\n      if (k != 0)\n        prefix %= k;\n      if (prefixToIndex.containsKey(prefix)) {\n        if (i - prefixToIndex.get(prefix) > 1)\n          return true;\n      } else {\n        // Only add if absent, because the previous index is better\n        prefixToIndex.put(prefix, i);\n      }\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkSubarraySum(vector<int>& nums, int k) {\n    unordered_map<int, int> prefixToIndex{{0, -1}};\n    int prefix = 0;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      prefix += nums[i];\n      if (k != 0)\n        prefix %= k;\n      if (prefixToIndex.count(prefix)) {\n        if (i - prefixToIndex[prefix] > 1)\n          return true;\n      } else {\n        // Only add if absent, because the previous index is better\n        prefixToIndex[prefix] = i;\n      }\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/523.html",
    "category": "Algorithms",
    "acceptance_rate": 30.858130103346397,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 6595,
    "dislikes": 688,
    "similar_questions": "[{\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Make Array Continuous\", \"titleSlug\": \"minimum-number-of-operations-to-make-array-continuous\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Intervals Between Identical Elements\", \"titleSlug\": \"intervals-between-identical-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Apply Operations to Make All Array Elements Equal to Zero\", \"titleSlug\": \"apply-operations-to-make-all-array-elements-equal-to-zero\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"677.1K\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 677110, \"totalSubmissionRaw\": 2194270, \"acRate\": \"30.9%\"}",
    "title_pt": "Soma Contínua de Subarray",
    "description_pt": "<p>Dado um array de inteiros nums e um inteiro k, retorne <code>true</code> <em>se </em><code>nums</code><em> tiver um <strong>subarray bom</strong> ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>Um <strong>subarray bom</strong> é um subarray em que:</p>\n\n<ul>\n\t<li>seu tamanho é de <strong>pelo menos dois</strong>, e</li>\n\t<li>a soma dos elementos do subarray é um múltiplo de <code>k</code>.</li>\n</ul>\n\n<p><strong>Nota</strong> que:</p>\n\n<ul>\n\t<li>Um <strong>subarray</strong> é uma parte contígua do array.</li>\n\t<li>Um inteiro <code>x</code> é um múltiplo de <code>k</code> se existir um inteiro <code>n</code> tal que <code>x = n * k</code>. <code>0</code> é <strong>sempre</strong> um múltiplo de <code>k</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [23,<u>2,4</u>,6,7], k = 6\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> [2, 4] é um subarray contínuo de tamanho 2 cujos elementos somam 6.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [<u>23,2,6,4,7</u>], k = 6\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> [23, 2, 6, 4, 7] é um subarray contínuo de tamanho 5 cujos elementos somam 42.\n42 é um múltiplo de 6 porque 42 = 7 * 6 e 7 é um inteiro.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [23,2,6,4,7], k = 13\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "524",
    "paidOnly": false,
    "title": "Longest Word in Dictionary through Deleting",
    "titleSlug": "longest-word-in-dictionary-through-deleting",
    "url": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting",
    "description_url": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/",
    "description": "<p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;]\n<strong>Output:</strong> &quot;apple&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]\n<strong>Output:</strong> &quot;a&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li>\n\t<li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Brute Force\n\n**Algorithm**\n\nThe idea behind this approach is as follows. We create a list of all the possible strings that can be formed by deleting one or more characters from the given string $$s$$. In order to do so, we make use of a recursive function `generate(s, str, i, l)` which creates a string by adding and by removing the current character($$i^{th}$$) from the string $$s$$ to the string $$str$$ formed till the index $$i$$. Thus, it adds the $$i^{th}$$ character to $$str$$ and calls itself as `generate(s, str + s.charAt(i), i + 1, l)`. It also omits the $$i^{th}$$ character to $$str$$ and calls itself as `generate(s, str, i + 1, l)`.\n\nThus, at the end the list $$l$$ contains all the required strings that can be formed using $$s$$. Then, we look for the strings formed in $$l$$ into the dictionary available to see if a match is available. Further, in case of a match, we check for the length of the matched string to maximize the length and we also take care to consider the lexicographically smallest string in case of length match as well.\n\n<iframe src=\"https://leetcode.com/playground/Jgw3jgjB/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"Jgw3jgjB\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(2^n)$$. `generate` calls itself $$2^n$$ times. Here, $$n$$ refers to the length of string $$s$$. \n\n* Space complexity : $$O(2^n)$$. List $$l$$ contains $$2^n$$ strings.\n<br>\n<br>\n\n---\n### Approach 2: Iterative Brute Force\n\n**Algorithm**\n\nInstead of using recursive `generate` to create the list of possible strings that can be formed using $$s$$ by performing delete operations, we can also do the same process iteratively. To do so, we use the concept of binary number generation. \n\nWe can treat the given string $$s$$ along with a binary represenation corresponding to the indices of $$s$$. The rule is that the character at the position $$i$$ has to be added to the newly formed string $$str$$ only if there is a boolean 1 at the corresponding index in the binary representation of a number currently considered.\n\nWe know a total of $$2^n$$ such binary numbers are possible if there are $$n$$ positions to be filled($$n$$ also corresponds to the number of characters in $$s$$). Thus, we consider all the numbers from $$0$$ to $$2^n$$ in their binary representation in a serial order and generate all the strings possible using the above rule.\n\nThe figure below shows an example of the strings generated for the given string $$s$$:\"sea\".\n\n![Longest_Word](../Figures/524_Longest_Word_Binary.PNG)\n\nA problem with this method is that the maximum length of the string can be 32 only, since we make use of an integer and perform the shift operations on it to generate the binary numbers.\n\n<iframe src=\"https://leetcode.com/playground/8pWWaJ9v/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"8pWWaJ9v\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(2^n)$$. $$2^n$$ strings are generated. \n\n* Space complexity : $$O(2^n)$$. List $$l$$ contains $$2^n$$ strings.\n<br>\n<br>\n\n---\n### Approach 3: Sorting and Checking Subsequence\n\n**Algorithm**\n\nThe matching condition in the given problem requires that we need to consider the matching string in the dictionary with the longest length and in case of same length, the string which is smallest lexicographically. To ease the searching process, we can sort the given dictionary's strings based on the same criteria, such that the more favorable string appears earlier in the sorted dictionary.\n\nNow, instead of performing the deletions in $$s$$, we can directly check if any of the words given in the dictionary(say $$x$$) is a subsequence of the given string $$s$$, starting from the beginning of the dictionary. This is because, if $$x$$ is a subsequence of $$s$$, we can obtain $$x$$ by performing delete operations on $$s$$. \n\nIf $$x$$ is a subsequence of $$s$$ every character of $$x$$ will be present in $$s$$. The following figure shows the way the subsequence check is done for one example:\n\n!?!../Documents/524_Longest_Word.json:1000,563!?!\n\nAs soon as we find any such $$x$$, we can stop the search immediately since we've already processed $$d$$ to our advantage.\n\n<iframe src=\"https://leetcode.com/playground/fQ4iHKAy/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"fQ4iHKAy\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n \\cdot x \\log n + n \\cdot x)$$. Here $$n$$ refers to the number of strings in list $$d$$ and $$x$$ refers to average string length. Sorting takes $$O(n\\log n)$$ and `isSubsequence` takes $$O(x)$$ to check whether a string is a subsequence of another string or not.  \n\n* Space complexity : $$O(\\log n)$$. Sorting takes $$O(\\log n)$$ space in average case.\n<br>\n<br>\n\n---\n### Approach 4: Without Sorting\n\n**Algorithm**\n\nSince sorting the dictionary could lead to a huge amount of extra effort, we can skip the sorting and directly look for the strings $$x$$ in the unsorted dictionary $$d$$ such that $$x$$ is a subsequence in $$s$$. If such a string $$x$$ is found, we compare it with the other matching strings found till now based on the required length and lexicographic criteria. Thus, after considering every string in $$d$$, we can obtain the required result.\n\n<iframe src=\"https://leetcode.com/playground/ZQKm8jBh/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"ZQKm8jBh\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n \\cdot x)$$. One iteration over all strings is required. Here $$n$$ refers to the number of strings in list $$d$$ and $$x$$ refers to average string length.\n\n* Space complexity : $$O(x)$$. $$max\\_str$$ variable is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLongestWord(self, s: str, d: List[str]) -> str:\n    ans = ''\n\n    for word in d:\n      i = 0\n      for c in s:\n        if i < len(word) and c == word[i]:\n          i += 1\n      if i == len(word):\n        if len(word) > len(ans) or len(word) == len(ans) and word < ans:\n          ans = word\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String findLongestWord(String s, List<String> d) {\n    String ans = \"\";\n\n    for (final String word : d)\n      if (isSubsequence(word, s))\n        if (word.length() > ans.length() ||\n            word.length() == ans.length() && word.compareTo(ans) < 0)\n          ans = word;\n\n    return ans;\n  }\n\n  // Returns true if a is a subsequence of b\n  private boolean isSubsequence(final String a, final String b) {\n    int i = 0;\n    for (final char c : b.toCharArray())\n      if (i < a.length() && c == a.charAt(i))\n        ++i;\n    return i == a.length();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string findLongestWord(string s, vector<string>& d) {\n    string ans;\n\n    for (const string& word : d)\n      if (isSubsequence(word, s))\n        if (word.length() > ans.length() ||\n            word.length() == ans.length() && word.compare(ans) < 0)\n          ans = word;\n\n    return ans;\n  }\n\n private:\n  // Returns true if a is a subsequence of b\n  bool isSubsequence(const string& a, const string& b) {\n    int i = 0;\n    for (const char c : b)\n      if (i < a.length() && c == a[i])\n        ++i;\n    return i == a.length();\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/524.html",
    "category": "Algorithms",
    "acceptance_rate": 51.712933705319294,
    "topics": [
      "Array",
      "Two Pointers",
      "String",
      "Sorting"
    ],
    "hints": [],
    "likes": 1829,
    "dislikes": 361,
    "similar_questions": "[{\"title\": \"Longest Word in Dictionary\", \"titleSlug\": \"longest-word-in-dictionary\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"167.7K\", \"totalSubmission\": \"324.4K\", \"totalAcceptedRaw\": 167749, \"totalSubmissionRaw\": 324385, \"acRate\": \"51.7%\"}",
    "title_pt": "Maior Palavra no Dicionário por Deleção",
    "description_pt": "<p>Dada uma string <code>s</code> e um array de strings <code>dictionary</code>, retorne <em>a string mais longa no dicionário que pode ser formada ao deletar alguns caracteres da string dada</em>. Se houver mais de um possível resultado, retorne a palavra mais longa com a menor ordem lexicográfica. Se não houver resultado possível, retorne a string vazia.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;ale&quot;,&quot;apple&quot;,&quot;monkey&quot;,&quot;plea&quot;]\n<strong>Saída:</strong> &quot;apple&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abpcplea&quot;, dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;]\n<strong>Saída:</strong> &quot;a&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li>\n\t<li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "525",
    "paidOnly": false,
    "title": "Contiguous Array",
    "titleSlug": "contiguous-array",
    "url": "https://leetcode.com/problems/contiguous-array",
    "description_url": "https://leetcode.com/problems/contiguous-array/description/",
    "description": "<p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,0]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,1,1,1,1,0,0,0]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/contiguous-array/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\n#### Algorithm\n\nThe brute force approach is really simple. We consider every possible subarray within the given array and count the number of zeros and ones in each subarray. Then, we find out the maximum size subarray with equal no. of zeros and ones out of them.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/sPZqbexo/shared\" frameBorder=\"0\" name=\"sPZqbexo\" width=\"100%\" height=\"428\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(n^2)$$. We consider every possible subarray by traversing over the complete array for every start point possible.\n\n* Space complexity : $$O(1)$$. Only two variables $$zeroes$$ and $$ones$$ are required.\n\n---\n\n### Approach #2 Using Hash Map [Accepted]\n\n#### Algorithm\n\nImagine a `count` variable, which is used to store the relative number of ones and zeros encountered so far while traversing the array. The `count` variable is incremented by one for every $$\\text{1}$$ encountered and the same is decremented by one for every $$\\text{0}$$ encountered.\n\nWe start traversing the array from the beginning. If at any moment, the $$count$$ becomes zero, it implies that we've encountered an equal number of zeros and ones from the beginning till the current index of the array($$i$$). Not only this, another point to be noted is that if we encounter the same $$count$$ twice (for any value, not just 0) while traversing the array, it means that the number of zeros and ones are equal between the indices corresponding to the equal $$count$$ values. The following figure illustrates the observation for the sequence `[0 0 1 0 0 0 1 1]`:\n\n![Contiguous_Array](../Figures/535_Contiguous_Array.PNG)\n\nIn the above figure, the subarrays between (A,B), (B,C), and (A,C) (lying between indices corresponding to $$count = -2$$) have an equal number of zeros and ones.\n\nAnother point to be noted is that the largest subarray is the one between the points (A, C). Thus, if we keep a track of the indices corresponding to the same $$count$$ values that lie farthest apart, we can determine the size of the largest subarray with equal no. of zeros and ones easily.\n\nWe can use a hash map that maps values of `count` to the first index where that `count` was seen. We maintain the value of `count` and at each index, if we have seen the same value of `count` before, it means the subarray starting from where we saw that value of `count` and ending at the current index has an equal number of 0s and 1s. Otherwise, we put `count` in the map for future iterations.\n\nThe following animation depicts the process:\n<!--![Contiguous_Array](../Figures/525_Contiguous_Array.gif)-->\n!?!../Documents/525_Contiguous_Array.json:1000,563!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/DUzWHXUN/shared\" frameBorder=\"0\" width=\"100%\" height=\"378\" name=\"DUzWHXUN\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(n)$$. The entire array is traversed only once.\n\n* Space complexity : $$O(n)$$. Maximum size of the HashMap $$map$$ will be $$\\text{n}$$, if all the elements are either 1 or 0.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMaxLength(self, nums: List[int]) -> int:\n    ans = 0\n    prefix = 0\n    prefixToIndex = {0: -1}\n\n    for i, num in enumerate(nums):\n      prefix += 1 if num else -1\n      if prefix in prefixToIndex:\n        ans = max(ans, i - prefixToIndex[prefix])\n      else:\n        prefixToIndex[prefix] = i\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMaxLength(int[] nums) {\n    int ans = 0;\n    int prefix = 0;\n    Map<Integer, Integer> prefixToIndex = new HashMap<>();\n    prefixToIndex.put(0, -1);\n\n    for (int i = 0; i < nums.length; ++i) {\n      prefix += nums[i] == 1 ? 1 : -1;\n      if (prefixToIndex.containsKey(prefix))\n        ans = Math.max(ans, i - prefixToIndex.get(prefix));\n      else\n        prefixToIndex.put(prefix, i);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMaxLength(vector<int>& nums) {\n    int ans = 0;\n    int prefix = 0;\n    unordered_map<int, int> prefixToIndex{{0, -1}};\n\n    for (int i = 0; i < nums.size(); ++i) {\n      prefix += nums[i] ? 1 : -1;\n      if (prefixToIndex.count(prefix))\n        ans = max(ans, i - prefixToIndex[prefix]);\n      else\n        prefixToIndex[prefix] = i;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/525.html",
    "category": "Algorithms",
    "acceptance_rate": 49.19439389100098,
    "topics": [
      "Array",
      "Hash Table",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 8329,
    "dislikes": 424,
    "similar_questions": "[{\"title\": \"Maximum Size Subarray Sum Equals k\", \"titleSlug\": \"maximum-size-subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All Possible Stable Binary Arrays I\", \"titleSlug\": \"find-all-possible-stable-binary-arrays-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All Possible Stable Binary Arrays II\", \"titleSlug\": \"find-all-possible-stable-binary-arrays-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"556K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 556025, \"totalSubmissionRaw\": 1130263, \"acRate\": \"49.2%\"}",
    "title_pt": "Array Contíguo",
    "description_pt": "<p>Dado um array binário <code>nums</code>, retorne <em>o comprimento máximo de um subarray contíguo com a mesma quantidade de </em><code>0</code><em> e </em><code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> [0, 1] é o subarray contíguo mais longo com a mesma quantidade de 0 e 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,0]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> [0, 1] (ou [1, 0]) é um dos subarrays contíguos mais longos com a mesma quantidade de 0 e 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,1,1,1,1,0,0,0]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> [1,1,1,0,0,0] é o subarray contíguo mais longo com a mesma quantidade de 0 e 1.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums[i]</code> é ou <code>0</code> ou <code>1</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "526",
    "paidOnly": false,
    "title": "Beautiful Arrangement",
    "titleSlug": "beautiful-arrangement",
    "url": "https://leetcode.com/problems/beautiful-arrangement",
    "description_url": "https://leetcode.com/problems/beautiful-arrangement/description/",
    "description": "<p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p>\n\n<ul>\n\t<li><code>perm[i]</code> is divisible by <code>i</code>.</li>\n\t<li><code>i</code> is divisible by <code>perm[i]</code>.</li>\n</ul>\n\n<p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 2\n<b>Explanation:</b> \nThe first beautiful arrangement is [1,2]:\n    - perm[1] = 1 is divisible by i = 1\n    - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n    - perm[1] = 2 is divisible by i = 1\n    - i = 2 is divisible by perm[2] = 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 15</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/beautiful-arrangement/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\n#### Algorithm\n\nIn the brute force method, we can find out all the arrays that can be formed using the numbers from 1 to N(by creating every possible permutation of the given elements). Then, we iterate over all the elements of every permutation generated and check for the required conditions of divisibility.\n\nIn order to generate all the possible pairings, we make use of a function `permute(nums, current_index)`. This function creates all the possible permutations of the elements of the given array.\n\nTo do so, `permute` takes the index of the current element $$current_index$$ as one of the arguments. Then, it swaps the current element with every other element in the array, lying towards its right, so as to generate a new ordering of the array elements. After the swapping has been done, it makes another call to permute but this time with the index of the next element in the array. While returning back, we reverse the swapping done in the current function call.\n\nThus, when we reach the end of the array, a new ordering of the array's elements is generated. The following animation depicts the process of generating the permutations.\n\n!?!../Documents/561_Array.json:1000,563!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5cbz54de/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5cbz54de\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(n!)$$. A total of $$n!$$ permutations will be generated for an array of length $$n$$.\n\n* Space complexity : $$O(n)$$. The depth of the recursion tree can go upto $$n$$. $$nums$$ array of size $$n$$ is used.\n\n---\n### Approach #2 Better Brute Force [Accepted]\n\n#### Algorithm\n\nIn the brute force approach, we create the full array for every permutation and then check the array for the given divisibilty conditions. But this method can be optimized to a great extent. To do so, we can keep checking the elements while being added to the permutation array at every step for the divisibility condition and  can stop creating it any further as soon as we find out the element just added to the permutation violates the divisiblity condition. \n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/D4dVJwn7/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"D4dVJwn7\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(k)$$. $$k$$ refers to the number of valid permutations.\n\n* Space complexity : $$O(n)$$. The depth of recursion tree can go upto $$n$$. Further, $$nums$$ array of size $$n$$ is used, where, $$n$$ is the given number.\n\n---\n\n### Approach #3 Backtracking [Accepted]\n\n#### Algorithm\n\n\nThe idea behind this approach is simple. We try to create all the permutations of numbers from 1 to N. We can fix one number at a particular position and check for the divisibility criteria of that number at the particular position. But, we need to keep a track of the numbers which have already been considered earlier so that they aren't reconsidered while generating the permutations. If the current \nnumber doesn't satisfy the divisibility criteria, we can leave all the permutations that can be generated with that number at the particular position. This helps to prune the search space of the permutations to a great extent. We do so by trying to place each of the numbers at each position.\n\n\nWe make use of a visited array of size $$N$$. Here, $$visited[i]$$ refers to the $$i^{th}$$ number being already placed/not placed in the array being formed till now(True indicates that the number has already been placed).\n\nWe make use of a `calculate` function, which puts all the numbers pending numbers from 1 to N(i.e. not placed till now in the array), indicated by a $$False$$ at the corresponding $$visited[i]$$ position, and tries to create all the permutations with those numbers starting from the $$pos$$ index onwards in the current array. While putting the $$pos^{th}$$ number, we check whether the $$i^{th}$$ number satisfies the divisibility criteria on the go i.e. we continue forward with creating the permutations with the number $$i$$ at the $$pos^{th}$$ position only if the number $$i$$ and $$pos$$ satisfy the given criteria. Otherwise, we continue with putting the next numbers at the same position and keep on generating the permutations.\n\nLook at the animation below for a better understanding of the methodology:\n\n!?!../Documents/526_Beautiful.json:1000,563!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/EVQebXTW/shared\" frameBorder=\"0\" width=\"100%\" height=\"480\" name=\"EVQebXTW\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity : $$O(k)$$. $$k$$ refers to the number of valid permutations.\n\n* Space complexity : $$O(n)$$. $$visited$$ array of size $$n$$ is used. The depth of recursion tree will also go upto $$n$$. Here, $$n$$ refers to the given integer $$n$$.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countArrangement(int N) {\n    final String filled = \"x\".repeat(N + 1);\n    StringBuilder sb = new StringBuilder(filled);\n    Map<String, Integer> memo = new HashMap<>();\n\n    return dfs(N, 1, sb, memo);\n  }\n\n  private int dfs(int N, int num, StringBuilder sb, Map<String, Integer> memo) {\n    if (num == N + 1)\n      return 1;\n    final String filled = sb.toString();\n    if (memo.containsKey(filled))\n      return memo.get(filled);\n\n    int count = 0;\n\n    for (int i = 1; i <= N; ++i)\n      if (sb.charAt(i) == 'x' && (num % i == 0 || i % num == 0)) {\n        sb.setCharAt(i, 'o');\n        count += dfs(N, num + 1, sb, memo);\n        sb.setCharAt(i, 'x');\n      }\n\n    memo.put(filled, count);\n    return count;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countArrangement(int N) {\n    return dfs(N, 1, string(N + 1, 'x'), {});\n  }\n\n private:\n  int dfs(int N, int num, string&& filled, unordered_map<string, int>&& memo) {\n    if (num == N + 1)\n      return 1;\n    if (memo.count(filled))\n      return memo[filled];\n\n    int count = 0;\n\n    for (int i = 1; i <= N; ++i)\n      if (filled[i] == 'x' && (num % i == 0 || i % num == 0)) {\n        filled[i] = 'o';\n        count += dfs(N, num + 1, move(filled), move(memo));\n        filled[i] = 'x';\n      }\n\n    return memo[filled] = count;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/526.html",
    "category": "Algorithms",
    "acceptance_rate": 64.49386604119174,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Backtracking",
      "Bit Manipulation",
      "Bitmask"
    ],
    "hints": [],
    "likes": 3324,
    "dislikes": 381,
    "similar_questions": "[{\"title\": \"Beautiful Arrangement II\", \"titleSlug\": \"beautiful-arrangement-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"195.8K\", \"totalSubmission\": \"303.6K\", \"totalAcceptedRaw\": 195774, \"totalSubmissionRaw\": 303555, \"acRate\": \"64.5%\"}",
    "title_pt": "Arranjo Bonito",
    "description_pt": "<p>Suponha que você tenha <code>n</code> inteiros rotulados de <code>1</code> até <code>n</code>. Uma permutação desses <code>n</code> inteiros <code>perm</code> (<strong>indexado em 1</strong>) é considerada um <strong>arranjo bonito</strong> se, para todo <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>uma das</strong> seguintes condições for verdadeira:</p>\n\n<ul>\n\t<li><code>perm[i]</code> é divisível por <code>i</code>.</li>\n\t<li><code>i</code> é divisível por <code>perm[i]</code>.</li>\n</ul>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>o <strong>número</strong> de <strong>arranjos bonitos</strong> que você pode construir</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 2\n<b>Explicação:</b> \nO primeiro arranjo bonito é [1,2]:\n    - perm[1] = 1 é divisível por i = 1\n    - perm[2] = 2 é divisível por i = 2\nO segundo arranjo bonito é [2,1]:\n    - perm[1] = 2 é divisível por i = 1\n    - i = 2 é divisível por perm[2] = 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 15</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "528",
    "paidOnly": false,
    "title": "Random Pick with Weight",
    "titleSlug": "random-pick-with-weight",
    "url": "https://leetcode.com/problems/random-pick-with-weight",
    "description_url": "https://leetcode.com/problems/random-pick-with-weight/description/",
    "description": "<p>You are given a <strong>0-indexed</strong> array of positive integers <code>w</code> where <code>w[i]</code> describes the <strong>weight</strong> of the <code>i<sup>th</sup></code> index.</p>\n\n<p>You need to implement the function <code>pickIndex()</code>, which <strong>randomly</strong> picks an index in the range <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) and returns it. The <strong>probability</strong> of picking an index <code>i</code> is <code>w[i] / sum(w)</code>.</p>\n\n<ul>\n\t<li>For example, if <code>w = [1, 3]</code>, the probability of picking index <code>0</code> is <code>1 / (1 + 3) = 0.25</code> (i.e., <code>25%</code>), and the probability of picking index <code>1</code> is <code>3 / (1 + 3) = 0.75</code> (i.e., <code>75%</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;,&quot;pickIndex&quot;]\n[[[1]],[]]\n<strong>Output</strong>\n[null,0]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;]\n[[[1,3]],[],[],[],[],[]]\n<strong>Output</strong>\n[null,1,1,1,1,0]\n\n<strong>Explanation</strong>\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pickIndex</code> will be called at most <code>10<sup>4</sup></code> times.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/random-pick-with-weight/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self, w: List[int]):\n    self.prefix = list(itertools.accumulate(w))\n\n  def pickIndex(self) -> int:\n    target = randint(0, self.prefix[-1] - 1)\n    l = 0\n    r = len(self.prefix)\n\n    while l < r:\n      m = (l + r) // 2\n      if self.prefix[m] > target:\n        r = m\n      else:\n        l = m + 1\n\n    return l",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int[] w) {\n    prefix = w;\n    for (int i = 1; i < prefix.length; ++i)\n      prefix[i] += prefix[i - 1];\n  }\n\n  public int pickIndex() {\n    final int target = rand.nextInt(prefix[prefix.length - 1]);\n    int l = 0;\n    int r = prefix.length;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (prefix[m] > target)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n\n  private int[] prefix;\n  private Random rand = new Random();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(vector<int>& w) : prefix(w.size()) {\n    partial_sum(begin(w), end(w), begin(prefix));\n  }\n\n  int pickIndex() {\n    const int target = rand() % prefix.back();\n    int l = 0;\n    int r = prefix.size();\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (prefix[m] > target)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n\n private:\n  vector<int> prefix;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/528.html",
    "category": "Algorithms",
    "acceptance_rate": 48.16897953046293,
    "topics": [
      "Array",
      "Math",
      "Binary Search",
      "Prefix Sum",
      "Randomized"
    ],
    "hints": [],
    "likes": 2128,
    "dislikes": 988,
    "similar_questions": "[{\"title\": \"Random Pick Index\", \"titleSlug\": \"random-pick-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Random Pick with Blacklist\", \"titleSlug\": \"random-pick-with-blacklist\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Random Point in Non-overlapping Rectangles\", \"titleSlug\": \"random-point-in-non-overlapping-rectangles\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"608.7K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 608654, \"totalSubmissionRaw\": 1263582, \"acRate\": \"48.2%\"}",
    "title_pt": "Randomização de Índice com Peso",
    "description_pt": "<p>Você recebe um array <strong>indexado em 0</strong> de inteiros positivos <code>w</code>, em que <code>w[i]</code> descreve o <strong>peso</strong> do <code>i<sup>ésimo</sup></code> índice.</p>\n\n<p>Você precisa implementar a função <code>pickIndex()</code>, que escolhe <strong>aleatoriamente</strong> um índice no intervalo <code>[0, w.length - 1]</code> (<strong>inclusive</strong>) e o retorna. A <strong>probabilidade</strong> de escolher um índice <code>i</code> é <code>w[i] / sum(w)</code>.</p>\n\n<ul>\n\t<li>Por exemplo, se <code>w = [1, 3]</code>, a probabilidade de escolher o índice <code>0</code> é <code>1 / (1 + 3) = 0.25</code> (ou seja, <code>25%</code>), e a probabilidade de escolher o índice <code>1</code> é <code>3 / (1 + 3) = 0.75</code> (ou seja, <code>75%</code>).</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;,&quot;pickIndex&quot;]\n[[[1]],[]]\n<strong>Saída</strong>\n[null,0]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // retorna 0. A única opção é retornar 0, pois há apenas um elemento em w.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;,&quot;pickIndex&quot;]\n[[[1,3]],[],[],[],[],[]]\n<strong>Saída</strong>\n[null,1,1,1,1,0]\n\n<strong>Explicação</strong>\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // retorna 1. Está retornando o segundo elemento (index = 1) que tem probabilidade de 3/4.\nsolution.pickIndex(); // retorna 1\nsolution.pickIndex(); // retorna 1\nsolution.pickIndex(); // retorna 1\nsolution.pickIndex(); // retorna 0. Está retornando o primeiro elemento (index = 0) que tem probabilidade de 1/4.\n\nComo este é um problema de randomização, múltiplas respostas são permitidas.\nTodos os seguintes resultados podem ser considerados corretos:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\ne assim por diante.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= w.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= w[i] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>pickIndex</code> será chamada no máximo <code>10<sup>4</sup></code> vezes.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "529",
    "paidOnly": false,
    "title": "Minesweeper",
    "titleSlug": "minesweeper",
    "url": "https://leetcode.com/problems/minesweeper",
    "description_url": "https://leetcode.com/problems/minesweeper/description/",
    "description": "<p>Let&#39;s play the minesweeper game (<a href=\"https://en.wikipedia.org/wiki/Minesweeper_(video_game)\" target=\"_blank\">Wikipedia</a>, <a href=\"http://minesweeperonline.com\" target=\"_blank\">online game</a>)!</p>\n\n<p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p>\n\n<ul>\n\t<li><code>&#39;M&#39;</code> represents an unrevealed mine,</li>\n\t<li><code>&#39;E&#39;</code> represents an unrevealed empty square,</li>\n\t<li><code>&#39;B&#39;</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li>\n\t<li>digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) represents how many mines are adjacent to this revealed square, and</li>\n\t<li><code>&#39;X&#39;</code> represents a revealed mine.</li>\n</ul>\n\n<p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>).</p>\n\n<p>Return <em>the board after revealing this position according to the following rules</em>:</p>\n\n<ol>\n\t<li>If a mine <code>&#39;M&#39;</code> is revealed, then the game is over. You should change it to <code>&#39;X&#39;</code>.</li>\n\t<li>If an empty square <code>&#39;E&#39;</code> with no adjacent mines is revealed, then change it to a revealed blank <code>&#39;B&#39;</code> and all of its adjacent unrevealed squares should be revealed recursively.</li>\n\t<li>If an empty square <code>&#39;E&#39;</code> with at least one adjacent mine is revealed, then change it to a digit (<code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>) representing the number of adjacent mines.</li>\n\t<li>Return the board when no more squares will be revealed.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2023/08/09/untitled.jpeg\" style=\"width: 500px; max-width: 400px; height: 269px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0]\n<strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2023/08/09/untitled-2.jpeg\" style=\"width: 489px; max-width: 400px; height: 269px;\" />\n<pre>\n<strong>Input:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2]\n<strong>Output:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>board[i][j]</code> is either <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, or a digit from <code>&#39;1&#39;</code> to <code>&#39;8&#39;</code>.</li>\n\t<li><code>click.length == 2</code></li>\n\t<li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li>\n\t<li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li>\n\t<li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>&#39;M&#39;</code> or <code>&#39;E&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minesweeper/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n    if board[click[0]][click[1]] == 'M':\n      board[click[0]][click[1]] = 'X'\n      return board\n\n    dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1),\n            (0, 1), (1, -1), (1, 0), (1, 1)]\n\n    def getMinesCount(i: int, j: int) -> int:\n      minesCount = 0\n      for dx, dy in dirs:\n        x = i + dx\n        y = j + dy\n        if x < 0 or x == len(board) or y < 0 or y == len(board[0]):\n          continue\n        if board[x][y] == 'M':\n          minesCount += 1\n      return minesCount\n\n    def dfs(i: int, j: int) -> None:\n      if i < 0 or i == len(board) or j < 0 or j == len(board[0]):\n        return\n      if board[i][j] != 'E':\n        return\n\n      minesCount = getMinesCount(i, j)\n      board[i][j] = 'B' if minesCount == 0 else str(minesCount)\n\n      if minesCount == 0:\n        for dx, dy in dirs:\n          dfs(i + dx, j + dy)\n\n    dfs(click[0], click[1])\n\n    return board",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public char[][] updateBoard(char[][] board, int[] click) {\n    if (board[click[0]][click[1]] == 'M') {\n      board[click[0]][click[1]] = 'X';\n      return board;\n    }\n\n    dfs(board, click[0], click[1]);\n\n    return board;\n  }\n\n  private static final int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},\n                                       {0, 1},   {1, -1}, {1, 0},  {1, 1}};\n\n  private void dfs(char[][] board, int i, int j) {\n    if (i < 0 || i == board.length || j < 0 || j == board[0].length)\n      return;\n    if (board[i][j] != 'E')\n      return;\n\n    final int minesCount = getMinesCount(board, i, j);\n    board[i][j] = minesCount == 0 ? 'B' : (char) ('0' + minesCount);\n\n    if (minesCount == 0)\n      for (int[] dir : dirs)\n        dfs(board, i + dir[0], j + dir[1]);\n  }\n\n  private int getMinesCount(char[][] board, int i, int j) {\n    int minesCount = 0;\n    for (final int[] dir : dirs) {\n      final int x = i + dir[0];\n      final int y = j + dir[1];\n      if (x < 0 || x == board.length || y < 0 || y == board[0].length)\n        continue;\n      if (board[x][y] == 'M')\n        ++minesCount;\n    }\n    return minesCount;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<char>> updateBoard(vector<vector<char>>& board,\n                                   vector<int>& click) {\n    if (board[click[0]][click[1]] == 'M') {\n      board[click[0]][click[1]] = 'X';\n      return board;\n    }\n\n    dfs(board, click[0], click[1]);\n\n    return board;\n  }\n\n private:\n  const vector<pair<int, int>> dirs{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},\n                                    {0, 1},   {1, -1}, {1, 0},  {1, 1}};\n\n  void dfs(vector<vector<char>>& board, int i, int j) {\n    if (i < 0 || i == board.size() || j < 0 || j == board[0].size())\n      return;\n    if (board[i][j] != 'E')\n      return;\n\n    const int minesCount = getMinesCount(board, i, j);\n    board[i][j] = minesCount == 0 ? 'B' : '0' + minesCount;\n\n    if (minesCount == 0)\n      for (const auto& [dx, dy] : dirs)\n        dfs(board, i + dx, j + dy);\n  }\n\n  int getMinesCount(const vector<vector<char>>& board, int i, int j) {\n    int minesCount = 0;\n    for (const auto& [dx, dy] : dirs) {\n      const int x = i + dx;\n      const int y = j + dy;\n      if (x < 0 || x == board.size() || y < 0 || y == board[0].size())\n        continue;\n      if (board[x][y] == 'M')\n        ++minesCount;\n    }\n    return minesCount;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/529.html",
    "category": "Algorithms",
    "acceptance_rate": 67.99241728447673,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 2037,
    "dislikes": 1081,
    "similar_questions": "[{\"title\": \"Detonate the Maximum Bombs\", \"titleSlug\": \"detonate-the-maximum-bombs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"185.1K\", \"totalSubmission\": \"272.2K\", \"totalAcceptedRaw\": 185073, \"totalSubmissionRaw\": 272197, \"acRate\": \"68.0%\"}",
    "title_pt": "Campo Minado",
    "description_pt": "<p>Vamos jogar o jogo Campo Minado (<a href=\"https://en.wikipedia.org/wiki/Minesweeper_(video_game)\" target=\"_blank\">Wikipedia</a>, <a href=\"http://minesweeperonline.com\" target=\"_blank\">jogo online</a>)!</p>\n\n<p>Você recebe uma matriz de caracteres <code>m x n</code> <code>board</code> representando o tabuleiro do jogo, em que:</p>\n\n<ul>\n\t<li><code>&#39;M&#39;</code> representa uma mina não revelada,</li>\n\t<li><code>&#39;E&#39;</code> representa uma casa vazia não revelada,</li>\n\t<li><code>&#39;B&#39;</code> representa uma casa em branco revelada que não tem minas adjacentes (isto é, acima, abaixo, à esquerda, à direita e todas as 4 diagonais),</li>\n\t<li>um dígito (<code>&#39;1&#39;</code> a <code>&#39;8&#39;</code>) representa quantas minas são adjacentes a esta casa revelada, e</li>\n\t<li><code>&#39;X&#39;</code> representa uma mina revelada.</li>\n</ul>\n\n<p>Você também recebe um array inteiro <code>click</code> em que <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> representa a próxima posição de clique entre todas as casas não reveladas (<code>&#39;M&#39;</code> ou <code>&#39;E&#39;</code>).</p>\n\n<p>Retorne <em>o tabuleiro após revelar esta posição de acordo com as seguintes regras</em>:</p>\n\n<ol>\n\t<li>Se uma mina <code>&#39;M&#39;</code> for revelada, então o jogo termina. Você deve alterá-la para <code>&#39;X&#39;</code>.</li>\n\t<li>Se uma casa vazia <code>&#39;E&#39;</code> sem minas adjacentes for revelada, então altere-a para uma casa em branco revelada <code>&#39;B&#39;</code> e todas as suas casas adjacentes não reveladas devem ser reveladas recursivamente.</li>\n\t<li>Se uma casa vazia <code>&#39;E&#39;</code> com pelo menos uma mina adjacente for revelada, então altere-a para um dígito (<code>&#39;1&#39;</code> a <code>&#39;8&#39;</code>) representando o número de minas adjacentes.</li>\n\t<li>Retorne o tabuleiro quando nenhuma casa puder mais ser revelada.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2023/08/09/untitled.jpeg\" style=\"width: 500px; max-width: 400px; height: 269px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;M&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;],[&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;,&quot;E&quot;]], click = [3,0]\n<strong>Saída:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2023/08/09/untitled-2.jpeg\" style=\"width: 489px; max-width: 400px; height: 269px;\" />\n<pre>\n<strong>Entrada:</strong> board = [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;M&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]], click = [1,2]\n<strong>Saída:</strong> [[&quot;B&quot;,&quot;1&quot;,&quot;E&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;X&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;B&quot;],[&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == board.length</code></li>\n\t<li><code>n == board[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>board[i][j]</code> é ou <code>&#39;M&#39;</code>, <code>&#39;E&#39;</code>, <code>&#39;B&#39;</code>, ou um dígito de <code>&#39;1&#39;</code> a <code>&#39;8&#39;</code>.</li>\n\t<li><code>click.length == 2</code></li>\n\t<li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li>\n\t<li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li>\n\t<li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> é ou <code>&#39;M&#39;</code> ou <code>&#39;E&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "530",
    "paidOnly": false,
    "title": "Minimum Absolute Difference in BST",
    "titleSlug": "minimum-absolute-difference-in-bst",
    "url": "https://leetcode.com/problems/minimum-absolute-difference-in-bst",
    "description_url": "https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/",
    "description": "<p>Given the <code>root</code> of a Binary Search Tree (BST), return <em>the minimum absolute difference between the values of any two different nodes in the tree</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg\" style=\"width: 292px; height: 301px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,6,1,3]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg\" style=\"width: 282px; height: 301px;\" />\n<pre>\n<strong>Input:</strong> root = [1,0,48,null,null,12,49]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[2, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 783: <a href=\"https://leetcode.com/problems/minimum-distance-between-bst-nodes/\" target=\"_blank\">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/minimum-absolute-difference-in-bst/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  // Very simliar to 94. Binary Tree Inorder Traversal\n  public int getMinimumDifference(TreeNode root) {\n    int ans = Integer.MAX_VALUE;\n    int prev = -1;\n    Deque<TreeNode> stack = new ArrayDeque<>();\n\n    while (root != null || !stack.isEmpty()) {\n      while (root != null) {\n        stack.push(root);\n        root = root.left;\n      }\n      root = stack.pop();\n      if (prev >= 0)\n        ans = Math.min(ans, root.val - prev);\n      prev = root.val;\n      root = root.right;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  // Very simliar to 94. Binary Tree Inorder Traversal\n  int getMinimumDifference(TreeNode* root) {\n    int ans = INT_MAX;\n    int prev = -1;\n    stack<TreeNode*> stack;\n\n    while (root || !stack.empty()) {\n      while (root) {\n        stack.push(root);\n        root = root->left;\n      }\n      root = stack.top(), stack.pop();\n      if (prev >= 0)\n        ans = min(ans, root->val - prev);\n      prev = root->val;\n      root = root->right;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/530.html",
    "category": "Algorithms",
    "acceptance_rate": 58.76254981815015,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 4583,
    "dislikes": 257,
    "similar_questions": "[{\"title\": \"K-diff Pairs in an Array\", \"titleSlug\": \"k-diff-pairs-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"512.7K\", \"totalSubmission\": \"872.4K\", \"totalAcceptedRaw\": 512654, \"totalSubmissionRaw\": 872419, \"acRate\": \"58.8%\"}",
    "title_pt": "Diferença Absoluta Mínima em uma BST",
    "description_pt": "<p>Dado o <code>root</code> de uma Árvore Binária de Busca (BST), retorne <em>a diferença absoluta mínima entre os valores de quaisquer dois nós diferentes na árvore</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg\" style=\"width: 292px; height: 301px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,6,1,3]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg\" style=\"width: 282px; height: 301px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,0,48,null,null,12,49]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[2, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Este problema é o mesmo que 783: <a href=\"https://leetcode.com/problems/minimum-distance-between-bst-nodes/\" target=\"_blank\">https://leetcode.com/problems/minimum-distance-between-bst-nodes/</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "532",
    "paidOnly": false,
    "title": "K-diff Pairs in an Array",
    "titleSlug": "k-diff-pairs-in-an-array",
    "url": "https://leetcode.com/problems/k-diff-pairs-in-an-array",
    "description_url": "https://leetcode.com/problems/k-diff-pairs-in-an-array/description/",
    "description": "<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p>\n\n<p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j &lt; nums.length</code></li>\n\t<li><code>i != j</code></li>\n\t<li><code>|nums[i] - nums[j]| == k</code></li>\n</ul>\n\n<p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [3,1,4,1,5], k = 2\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,5], k = 1\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,1,5,4], k = 0\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/k-diff-pairs-in-an-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findPairs(self, nums: List[int], k: int) -> int:\n    ans = 0\n    numToIndex = {num: i for i, num in enumerate(nums)}\n\n    for i, num in enumerate(nums):\n      target = num + k\n      if target in numToIndex and numToIndex[target] != i:\n        ans += 1\n        del numToIndex[target]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findPairs(int[] nums, int k) {\n    int ans = 0;\n    Map<Integer, Integer> numToIndex = new HashMap<>();\n\n    for (int i = 0; i < nums.length; ++i)\n      numToIndex.put(nums[i], i);\n\n    for (int i = 0; i < nums.length; ++i) {\n      final int target = nums[i] + k;\n      if (numToIndex.containsKey(target) && numToIndex.get(target) != i) {\n        ++ans;\n        numToIndex.remove(target);\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findPairs(vector<int>& nums, int k) {\n    int ans = 0;\n    unordered_map<int, int> numToIndex;\n\n    for (int i = 0; i < nums.size(); ++i)\n      numToIndex[nums[i]] = i;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const int target = nums[i] + k;\n      if (numToIndex.count(target) && numToIndex[target] != i) {\n        ++ans;\n        numToIndex.erase(target);\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/532.html",
    "category": "Algorithms",
    "acceptance_rate": 44.524208490078884,
    "topics": [
      "Array",
      "Hash Table",
      "Two Pointers",
      "Binary Search",
      "Sorting"
    ],
    "hints": [],
    "likes": 4032,
    "dislikes": 2279,
    "similar_questions": "[{\"title\": \"Minimum Absolute Difference in BST\", \"titleSlug\": \"minimum-absolute-difference-in-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Number of Pairs With Absolute Difference K\", \"titleSlug\": \"count-number-of-pairs-with-absolute-difference-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Product of Two Sorted Arrays\", \"titleSlug\": \"kth-smallest-product-of-two-sorted-arrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Number of Bad Pairs\", \"titleSlug\": \"count-number-of-bad-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Pairs Satisfying Inequality\", \"titleSlug\": \"number-of-pairs-satisfying-inequality\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Absolute Difference Between Elements With Constraint\", \"titleSlug\": \"minimum-absolute-difference-between-elements-with-constraint\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"387.1K\", \"totalSubmission\": \"869.5K\", \"totalAcceptedRaw\": 387141, \"totalSubmissionRaw\": 869506, \"acRate\": \"44.5%\"}",
    "title_pt": "Pares K-diff em um Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>o número de pares k-diff <b>únicos</b> no array</em>.</p>\n\n<p>Um par <strong>k-diff</strong> é um par de inteiros <code>(nums[i], nums[j])</code>, em que as seguintes condições são verdadeiras:</p>\n\n<ul>\n\t<li><code>0 &lt;= i, j &lt; nums.length</code></li>\n\t<li><code>i != j</code></li>\n\t<li><code>|nums[i] - nums[j]| == k</code></li>\n</ul>\n\n<p><strong>Observe</strong> que <code>|val|</code> denota o valor absoluto de <code>val</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [3,1,4,1,5], k = 2\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Há dois pares 2-diff no array, (1, 3) e (3, 5).\nEmbora tenhamos dois 1s na entrada, devemos retornar apenas o número de pares <strong>únicos</strong>.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4,5], k = 1\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Há quatro pares 1-diff no array, (1, 2), (2, 3), (3, 4) e (4, 5).\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,1,5,4], k = 0\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Há um par 0-diff no array, (1, 1).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "535",
    "paidOnly": false,
    "title": "Encode and Decode TinyURL",
    "titleSlug": "encode-and-decode-tinyurl",
    "url": "https://leetcode.com/problems/encode-and-decode-tinyurl",
    "description_url": "https://leetcode.com/problems/encode-and-decode-tinyurl/description/",
    "description": "<blockquote>Note: This is a companion problem to the <a href=\"https://leetcode.com/discuss/interview-question/system-design/\" target=\"_blank\">System Design</a> problem: <a href=\"https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/\" target=\"_blank\">Design TinyURL</a>.</blockquote>\n\n<p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p>\n\n<p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution()</code> Initializes the object of the system.</li>\n\t<li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li>\n\t<li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot;\n<strong>Output:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot;\n\n<strong>Explanation:</strong>\nSolution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after decoding it.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>url</code> is guranteed to be a valid URL.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/encode-and-decode-tinyurl/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Codec:\n  alphabets = string.ascii_letters + '0123456789'\n  urlToCode = {}\n  codeToUrl = {}\n\n  def encode(self, longUrl: str) -> str:\n    while longUrl not in self.urlToCode:\n      code = ''.join(random.choice(self.alphabets) for _ in range(6))\n      if code not in self.codeToUrl:\n        self.codeToUrl[code] = longUrl\n        self.urlToCode[longUrl] = code\n    return 'http://tinyurl.com/' + self.urlToCode[longUrl]\n\n  def decode(self, shortUrl: str) -> str:\n    return self.codeToUrl[shortUrl[-6:]]",
    "solution_code_java": "\t\t\t\n\npublic class Codec {\n  public String encode(String longUrl) {\n    while (!urlToCode.containsKey(longUrl)) {\n      StringBuilder sb = new StringBuilder();\n      for (int i = 0; i < 6; ++i) {\n        final char nextChar = alphabets.charAt(rand.nextInt(alphabets.length()));\n        sb.append(nextChar);\n      }\n      final String code = sb.toString();\n      if (!codeToUrl.containsKey(code)) {\n        codeToUrl.put(code, longUrl);\n        urlToCode.put(longUrl, code);\n        return \"http://tinyurl.com/\" + code;\n      }\n    }\n\n    throw new IllegalArgumentException();\n  }\n\n  public String decode(String shortUrl) {\n    return codeToUrl.get(shortUrl.substring(19));\n  }\n\n  private static final String alphabets =\n      \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n  private Map<String, String> urlToCode = new HashMap<>();\n  private Map<String, String> codeToUrl = new HashMap<>();\n  private Random rand = new Random();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string encode(string longUrl) {\n    while (!urlToCode.count(longUrl)) {\n      string code;\n      for (int i = 0; i < 6; ++i)\n        code += alphabets[rand() % alphabets.size()];\n      if (!codeToUrl.count(code)) {\n        codeToUrl[code] = longUrl;\n        urlToCode[longUrl] = code;\n        return \"http://tinyurl.com/\" + code;\n      }\n    }\n\n    throw;\n  }\n\n  string decode(string shortUrl) {\n    return codeToUrl[shortUrl.substr(19)];\n  }\n\n private:\n  const string alphabets =\n      \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n  unordered_map<string, string> urlToCode;\n  unordered_map<string, string> codeToUrl;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/535.html",
    "category": "Algorithms",
    "acceptance_rate": 86.3226813668242,
    "topics": [
      "Hash Table",
      "String",
      "Design",
      "Hash Function"
    ],
    "hints": [],
    "likes": 2069,
    "dislikes": 3802,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"285.3K\", \"totalSubmission\": \"330.5K\", \"totalAcceptedRaw\": 285312, \"totalSubmissionRaw\": 330518, \"acRate\": \"86.3%\"}",
    "title_pt": "Codificar e Decodificar TinyURL",
    "description_pt": "<blockquote>Nota: Este é um problema complementar ao problema de <a href=\"https://leetcode.com/discuss/interview-question/system-design/\" target=\"_blank\">Projeto de Sistema</a>: <a href=\"https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/\" target=\"_blank\">Projetar um Sistema de Encurtador de URL (TinyURL)</a>.</blockquote>\n\n<p>TinyURL é um serviço de encurtamento de URL em que você insere uma URL como <code>https://leetcode.com/problems/design-tinyurl</code> e ele retorna uma URL curta como <code>http://tinyurl.com/4e9iAk</code>. Projete uma classe para codificar uma URL e decodificar uma tiny URL.</p>\n\n<p>Não há restrição sobre como seu algoritmo de codificação/decodificação deve funcionar. Você só precisa garantir que uma URL possa ser codificada em uma tiny URL e que a tiny URL possa ser decodificada para a URL original.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution()</code> Inicializa o objeto do sistema.</li>\n\t<li><code>String encode(String longUrl)</code> Retorna uma tiny URL para a <code>longUrl</code> fornecida.</li>\n\t<li><code>String decode(String shortUrl)</code> Retorna a URL longa original para a <code>shortUrl</code> fornecida. É garantido que a <code>shortUrl</code> fornecida foi codificada pelo mesmo objeto.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> url = &quot;https://leetcode.com/problems/design-tinyurl&quot;\n<strong>Saída:</strong> &quot;https://leetcode.com/problems/design-tinyurl&quot;\n\n<strong>Explicação:</strong>\nSolution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after decoding it.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>url</code> é garantido ser uma URL válida.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "537",
    "paidOnly": false,
    "title": "Complex Number Multiplication",
    "titleSlug": "complex-number-multiplication",
    "url": "https://leetcode.com/problems/complex-number-multiplication",
    "description_url": "https://leetcode.com/problems/complex-number-multiplication/description/",
    "description": "<p>A <a href=\"https://en.wikipedia.org/wiki/Complex_number\" target=\"_blank\">complex number</a> can be represented as a string on the form <code>&quot;<strong>real</strong>+<strong>imaginary</strong>i&quot;</code> where:</p>\n\n<ul>\n\t<li><code>real</code> is the real part and is an integer in the range <code>[-100, 100]</code>.</li>\n\t<li><code>imaginary</code> is the imaginary part and is an integer in the range <code>[-100, 100]</code>.</li>\n\t<li><code>i<sup>2</sup> == -1</code>.</li>\n</ul>\n\n<p>Given two complex numbers <code>num1</code> and <code>num2</code> as strings, return <em>a string of the complex number that represents their multiplications</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot;\n<strong>Output:</strong> &quot;0+2i&quot;\n<strong>Explanation:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot;\n<strong>Output:</strong> &quot;0+-2i&quot;\n<strong>Explanation:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>num1</code> and <code>num2</code> are valid complex numbers.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/complex-number-multiplication/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Simple Solution[Accepted]\n\n**Algorithm**\n\nMultiplication of two complex numbers can be done as:\n\n$$\n(a+ib) \\times (x+iy)=ax+i^2by+i(bx+ay)=ax-by+i(bx+ay)\n$$\n\nWe simply split up the real and the imaginary parts of the given complex strings based on the '+' and the 'i' symbols. We store the real parts of the two strings $$a$$ and $$b$$ as $$x[0]$$ and $$y[0]$$ respectively and the imaginary parts as $$x[1]$$ and $$y[1]$$ respectively. Then, we multiply the real and the imaginary parts as required after converting the extracted parts into integers. Then, we again form the return string in the required format and return the result.\n\n<iframe src=\"https://leetcode.com/playground/jgLSUzDc/shared\" frameBorder=\"0\" name=\"jgLSUzDc\" width=\"100%\" height=\"309\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(1)$$. Here splitting takes constant time as length of the string is very small $$(<20)$$.\n\n* Space complexity : $$O(1)$$. Constant extra space is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def complexNumberMultiply(self, a: str, b: str) -> str:\n    def getRealAndImag(s: str) -> tuple:\n      return int(s[:s.index('+')]), int(s[s.index('+') + 1:-1])\n\n    A, B = getRealAndImag(a)\n    C, D = getRealAndImag(b)\n\n    return str(A * C - B * D) + '+' + str(A * D + B * C) + 'i'",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String complexNumberMultiply(String a, String b) {\n    int[] A = getRealAndImag(a);\n    int[] B = getRealAndImag(b);\n    return String.valueOf(A[0] * B[0] - A[1] * B[1]) + \"+\" +\n        String.valueOf(A[0] * B[1] + A[1] * B[0]) + \"i\";\n  }\n\n  private int[] getRealAndImag(final String s) {\n    final String real = s.substring(0, s.indexOf('+'));\n    final String imag = s.substring(s.indexOf('+') + 1, s.length() - 1);\n    return new int[] {Integer.valueOf(real), Integer.valueOf(imag)};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string complexNumberMultiply(string a, string b) {\n    const auto& [A, B] = getRealAndImag(a);\n    const auto& [C, D] = getRealAndImag(b);\n    return to_string(A * C - B * D) + \"+\" + to_string(A * D + B * C) + \"i\";\n  }\n\n private:\n  pair<int, int> getRealAndImag(const string& s) {\n    const string& real = s.substr(0, s.find_first_of('+'));\n    const string& imag = s.substr(s.find_first_of('+') + 1);\n    return {stoi(real), stoi(imag)};\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/537.html",
    "category": "Algorithms",
    "acceptance_rate": 72.33121896051532,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 731,
    "dislikes": 1252,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"103K\", \"totalSubmission\": \"142.4K\", \"totalAcceptedRaw\": 102970, \"totalSubmissionRaw\": 142359, \"acRate\": \"72.3%\"}",
    "title_pt": "Multiplicação de Números Complexos",
    "description_pt": "<p>Um <a href=\"https://en.wikipedia.org/wiki/Complex_number\" target=\"_blank\">número complexo</a> pode ser representado como uma string na forma <code>\"<strong>real</strong>+<strong>imaginary</strong>i\"</code> onde:</p>\n\n<ul>\n\t<li><code>real</code> é a parte real e é um inteiro no intervalo <code>[-100, 100]</code>.</li>\n\t<li><code>imaginary</code> é a parte imaginária e é um inteiro no intervalo <code>[-100, 100]</code>.</li>\n\t<li><code>i<sup>2</sup> == -1</code>.</li>\n</ul>\n\n<p>Dados dois números complexos <code>num1</code> e <code>num2</code> como strings, retorne <em>uma string do número complexo que representa suas multiplicações</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num1 = &quot;1+1i&quot;, num2 = &quot;1+1i&quot;\n<strong>Saída:</strong> &quot;0+2i&quot;\n<strong>Explicação:</strong> (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num1 = &quot;1+-1i&quot;, num2 = &quot;1+-1i&quot;\n<strong>Saída:</strong> &quot;0+-2i&quot;\n<strong>Explicação:</strong> (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>num1</code> and <code>num2</code> are valid complex numbers.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "538",
    "paidOnly": false,
    "title": "Convert BST to Greater Tree",
    "titleSlug": "convert-bst-to-greater-tree",
    "url": "https://leetcode.com/problems/convert-bst-to-greater-tree",
    "description_url": "https://leetcode.com/problems/convert-bst-to-greater-tree/description/",
    "description": "<p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p>\n\n<p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p>\n\n<ul>\n\t<li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node&#39;s key.</li>\n\t<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node&#39;s key.</li>\n\t<li>Both the left and right subtrees must also be binary search trees.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/05/02/tree.png\" style=\"width: 500px; height: 341px;\" />\n<pre>\n<strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\n<strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [0,null,1]\n<strong>Output:</strong> [1,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>All the values in the tree are <strong>unique</strong>.</li>\n\t<li><code>root</code> is guaranteed to be a valid binary search tree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1038: <a href=\"https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\" target=\"_blank\">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/convert-bst-to-greater-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n    prefix = 0\n\n    def reversedInorder(root: Optional[TreeNode]) -> None:\n      nonlocal prefix\n      if not root:\n        return\n\n      reversedInorder(root.right)\n      prefix += root.val\n      root.val = prefix\n      reversedInorder(root.left)\n\n    reversedInorder(root)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode convertBST(TreeNode root) {\n    reversedInorder(root);\n    return root;\n  }\n\n  private int prefix = 0;\n\n  private void reversedInorder(TreeNode root) {\n    if (root == null)\n      return;\n\n    reversedInorder(root.right);\n    prefix += root.val;\n    root.val = prefix;\n    reversedInorder(root.left);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* convertBST(TreeNode* root) {\n    int prefix = 0;\n    reversedInorder(root, prefix);\n    return root;\n  }\n\n private:\n  void reversedInorder(TreeNode* root, int& prefix) {\n    if (root == nullptr)\n      return;\n\n    reversedInorder(root->right, prefix);\n    prefix += root->val;\n    root->val = prefix;\n    reversedInorder(root->left, prefix);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/538.html",
    "category": "Algorithms",
    "acceptance_rate": 70.40074348802588,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5324,
    "dislikes": 177,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"327.2K\", \"totalSubmission\": \"464.8K\", \"totalAcceptedRaw\": 327248, \"totalSubmissionRaw\": 464836, \"acRate\": \"70.4%\"}",
    "title_pt": "Converter BST em Árvore Maior",
    "description_pt": "<p>Dada a <code>root</code> de uma Árvore Binária de Busca (BST), converta-a em uma Árvore Maior de modo que cada chave da BST original seja alterada para a chave original mais a soma de todas as chaves maiores do que a chave original na BST.</p>\n\n<p>Como lembrete, uma <em>árvore binária de busca</em> é uma árvore que satisfaz estas restrições:</p>\n\n<ul>\n\t<li>A subárvore esquerda de um nó contém apenas nós com chaves <strong>menores do que</strong> a chave do nó.</li>\n\t<li>A subárvore direita de um nó contém apenas nós com chaves <strong>maiores do que</strong> a chave do nó.</li>\n\t<li>Tanto a subárvore esquerda quanto a subárvore direita também devem ser árvores binárias de busca.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/05/02/tree.png\" style=\"width: 500px; height: 341px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\n<strong>Saída:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [0,null,1]\n<strong>Saída:</strong> [1,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>Todos os valores na árvore são <strong>únicos</strong>.</li>\n\t<li>É garantido que <code>root</code> é uma árvore binária de busca válida.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que 1038: <a href=\"https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/\" target=\"_blank\">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "539",
    "paidOnly": false,
    "title": "Minimum Time Difference",
    "titleSlug": "minimum-time-difference",
    "url": "https://leetcode.com/problems/minimum-time-difference",
    "description_url": "https://leetcode.com/problems/minimum-time-difference/description/",
    "description": "Given a list of 24-hour clock time points in <strong>&quot;HH:MM&quot;</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>.\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> timePoints = [\"23:59\",\"00:00\"]\n<strong>Output:</strong> 1\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> timePoints = [\"00:00\",\"23:59\",\"00:00\"]\n<strong>Output:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>timePoints[i]</code> is in the format <strong>&quot;HH:MM&quot;</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-time-difference/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given an array of times, where each time is given in `\"HH:MM\"` string format. We must return the minimum difference in minutes between any pair of times in the array.\n\n### Approach 1: Sort\n\n### Intuition\n\nSince the times are given in `\"HH:MM\"` string format instead of the number of minutes, we can start by parsing the string format of each time and converting it into the total number of minutes passed since `\"00:00\"`.\n\n![Input array converted to minutes](../Figures/539/Input_array_converted_to_minutes.png)\n\nIf this converted array is sorted in ascending order, then the minimum difference must be the difference in an adjacent pair of times. This is because adjacent elements in a sorted array have smaller differences than non-adjacent elements. Thus, we can sort our array and calculate the difference between each adjacent pair of elements, keeping track of the smallest difference. \n\nAn edge case we have to consider is if the smallest difference is between the last and first element, in which case the time loops back to `\"00:00\"`. For example, if the last and first time is `\"22:00\"` and `\"02:00\"`, then the time difference is 4 hours or 240 minutes.\n\nThus, checking the difference between each adjacent pair in the sorted array as well as the difference between the first and last element will give us the minimum time difference.\n\n### Algorithm\n\n1. Initialize an array `minutes` to store the given time points in units of minutes.\n2. For each time `time` in the given `timePoints` array:\n    * Parse the first two characters in `time` to get the hour `h` \n    * Parse the last two characters to get the minutes `m`\n    * Calculate the total number of minutes `h * 60 + m` and store the value in `minutes`\n3. Sort `minutes` in ascending order\n4. Initialize our answer variable `ans = Integer.MAX_VALUE`\n5. Iterate through each adjacent pair of elements `(i, i+1)` in `minutes` to find the minimum time difference:\n    * `ans = min(ans, minutes[i+1] - minutes[i])`\n6. Return the minimum of `ans` and `24 * 60 - minutes[minutes.length - 1] + minutes[0]`, the amount of time between the last and first elements. \n\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/VwArgcjG/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VwArgcjG\"></iframe>\n\n### Complexity Analysis \n\nLet $N$ be the size of the given array `timePoints`. \n\n* Time Complexity: $O(N \\cdot \\log N)$\n\n    Converting the input into minutes and traversing the sorted array to calculate the minimum difference both take $O(N)$ time. However, sorting the array takes $O(N \\cdot \\log N)$ time. Thus, the total time complexity is $O(N \\cdot \\log N)$\n\n* Space Complexity: $O(N)$\n\n    Our array `minutes` to store the converted input takes $O(N)$ space.\n\n### Approach 2: Bucket Sort \n\n### Intuition\n\nIn approach 1, our time complexity was dominated by the time needed for sorting, which was $O(N \\cdot \\log N)$. However, we notice that the values in our array `minutes` can only fall into the range $[0, 24*60 - 1]$. Because we know the range of values for the array we'd like to sort, we can instead use bucket sort, which is a sorting algorithm that can be done in linear time. \n\nBucket sort is typically completed in three steps:\n\n1. We initialize an array `buckets` whose size is equal to the total number of possible values. \n2. We process the input array so that each element `buckets[i]` contains the frequency count of the value `i` in the input array.\n3. We can finally produce the sorted array by iterating through each element/bucket `buckets[i]` in `buckets` and append the value `i` `buckets[i]` times to a new array. \n\nFor our purposes, we can use a modified bucket sort for `minutes` where `minutes[i]` will contain a boolean value for whether or not the input array has value `i`. After, we can iterate through `minutes` in a similar fashion as Approach 1, where we keep track of the difference between adjacent elements, as well as the difference between the last and first elements. \n\n### Algorithm \n\n1. Initialize array `minutes` with a size of $24 * 60$\n2. For each `time` in `timePoints`:\n    * Parse `time` and convert to the total number of minutes `min`\n    * If `minutes[min] == true`, then that means `time` appears more than once in our array, which means the minimum time difference is just $0$ so return $0$\n    * Otherwise, set `minutes[min] == true`\n3. Initialize variable `prevIndex = Integer.MAX_VALUE` to keep track of the previous time to calculate the time difference for adjacent pairs\n4. Initialize variables `firstIndex = Integer.MAX_VALUE` and `lastIndex = Integer.MAX-VALUE` to keep track of the first and last elements in our array\n5. Initialize answer variable `ans = Integer.MAX_VALUE` to maintain the minimum time difference between adjacent pairs\n6. Iterate through values `i` between $[0, 24 * 60 - 1]$:\n    * If `minutes[i]` is true, then the time `i` is present in our array:\n        * If `prevIndex` does not contain the default value `Integer.MAX_VALUE`, then we can find the difference between time `i` and the previous time `prevIndex`: `ans = min(ans, i - prevIndex)`\n        * Update `prevIndex` to `i`\n        * If `firstIndex` contains the default value, then `i` is the first element in our sorted array, so we can set `firstIndex = i`\n        * Update `lastIndex` to `i`\n7. Return the minimum between `ans` and `24 * 60 - lastIndex + firstIndex`\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/oLQPH4eP/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"oLQPH4eP\"></iframe>\n\n### Complexity Analysis\n\nLet $N$ be the size of the given array `timePoints`. \n\n* Time Complexity: $O(N)$\n\n In contrast to Approach 1, our sorting only takes $O(N)$ time.\n\n* Space Complexity: $O(1)$\n\n Our array `minutes` will always have a size of $24 * 60$, so the space complexity is constant.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMinDifference(self, timePoints: List[str]) -> int:\n    ans = 24 * 60\n    nums = sorted([int(timePoint[:2]) * 60 + int(timePoint[3:])\n                   for timePoint in timePoints])\n\n    for a, b in zip(nums, nums[1:]):\n      ans = min(ans, b - a)\n\n    return min(ans, 24 * 60 - nums[-1] + nums[0])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findMinDifference(List<String> timePoints) {\n    int ans = 24 * 60;\n    int first = 24 * 60;\n    boolean[] bucket = new boolean[24 * 60];\n\n    for (final String timePoint : timePoints) {\n      final int num =\n          Integer.valueOf(timePoint.substring(0, 2)) * 60 + Integer.valueOf(timePoint.substring(3));\n      first = Math.min(first, num);\n      if (bucket[num])\n        return 0;\n      bucket[num] = true;\n    }\n\n    int prev = first;\n\n    for (int i = first + 1; i < bucket.length; ++i)\n      if (bucket[i]) {\n        ans = Math.min(ans, i - prev);\n        prev = i;\n      }\n\n    return Math.min(ans, 24 * 60 - prev + first);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findMinDifference(vector<string>& timePoints) {\n    int ans = 24 * 60;\n    int first = 24 * 60;\n    vector<bool> bucket(24 * 60);\n\n    for (const string& time : timePoints) {\n      const int num = stoi(time.substr(0, 2)) * 60 + stoi(time.substr(3));\n      first = min(first, num);\n      if (bucket[num])\n        return 0;\n      bucket[num] = true;\n    }\n\n    int prev = first;\n\n    for (int i = first + 1; i < bucket.size(); ++i)\n      if (bucket[i]) {\n        ans = min(ans, i - prev);\n        prev = i;\n      }\n\n    return min(ans, 24 * 60 - prev + first);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/539.html",
    "category": "Algorithms",
    "acceptance_rate": 62.32663695098466,
    "topics": [
      "Array",
      "Math",
      "String",
      "Sorting"
    ],
    "hints": [],
    "likes": 2551,
    "dislikes": 316,
    "similar_questions": "[{\"title\": \"Minimum Cost to Set Cooking Time\", \"titleSlug\": \"minimum-cost-to-set-cooking-time\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"321K\", \"totalSubmission\": \"515.1K\", \"totalAcceptedRaw\": 321046, \"totalSubmissionRaw\": 515103, \"acRate\": \"62.3%\"}",
    "title_pt": "Diferença Mínima de Tempo",
    "description_pt": "Dada uma lista de pontos de tempo de um relógio de 24 horas no formato <strong>&quot;HH:MM&quot;</strong>, retorne <em>a diferença mínima em <b>minutos</b> entre quaisquer dois pontos de tempo na lista</em>.\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> timePoints = [\"23:59\",\"00:00\"]\n<strong>Saída:</strong> 1\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> timePoints = [\"00:00\",\"23:59\",\"00:00\"]\n<strong>Saída:</strong> 0\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>timePoints[i]</code> está no formato <strong>&quot;HH:MM&quot;</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "540",
    "paidOnly": false,
    "title": "Single Element in a Sorted Array",
    "titleSlug": "single-element-in-a-sorted-array",
    "url": "https://leetcode.com/problems/single-element-in-a-sorted-array",
    "description_url": "https://leetcode.com/problems/single-element-in-a-sorted-array/description/",
    "description": "<p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p>\n\n<p>Return <em>the single element that appears only once</em>.</p>\n\n<p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8]\n<strong>Output:</strong> 2\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11]\n<strong>Output:</strong> 10\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/single-element-in-a-sorted-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def singleNonDuplicate(self, nums: List[int]) -> int:\n    l = 0\n    r = len(nums) - 1\n\n    while l < r:\n      m = (l + r) // 2\n      if m % 2 == 1:\n        m -= 1\n      if nums[m] == nums[m + 1]:\n        l = m + 2\n      else:\n        r = m\n\n    return nums[l]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int singleNonDuplicate(int[] nums) {\n    int l = 0;\n    int r = nums.length - 1;\n\n    while (l < r) {\n      int m = (l + r) / 2;\n      if (m % 2 == 1)\n        --m;\n      if (nums[m] == nums[m + 1])\n        l = m + 2;\n      else\n        r = m;\n    }\n\n    return nums[l];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int singleNonDuplicate(vector<int>& nums) {\n    int l = 0;\n    int r = nums.size() - 1;\n\n    while (l < r) {\n      int m = (l + r) / 2;\n      if (m & 1)\n        --m;\n      if (nums[m] == nums[m + 1])\n        l = m + 2;\n      else\n        r = m;\n    }\n\n    return nums[l];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/540.html",
    "category": "Algorithms",
    "acceptance_rate": 59.19269128702663,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 12006,
    "dislikes": 216,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"902.5K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 902469, \"totalSubmissionRaw\": 1524631, \"acRate\": \"59.2%\"}",
    "title_pt": "Elemento Único em um Array Ordenado",
    "description_pt": "<p>Você recebe um array ordenado composto apenas por inteiros, no qual cada elemento aparece exatamente duas vezes, exceto por um elemento, que aparece exatamente uma vez.</p>\n\n<p>Retorne <em>o elemento único que aparece apenas uma vez</em>.</p>\n\n<p>Sua solução deve executar em tempo <code>O(log n)</code> e usar <code>O(1)</code> de espaço.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1,2,3,3,4,4,8,8]\n<strong>Saída:</strong> 2\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [3,3,7,7,10,11,11]\n<strong>Saída:</strong> 10\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "541",
    "paidOnly": false,
    "title": "Reverse String II",
    "titleSlug": "reverse-string-ii",
    "url": "https://leetcode.com/problems/reverse-string-ii",
    "description_url": "https://leetcode.com/problems/reverse-string-ii/description/",
    "description": "<p>Given a string <code>s</code> and an integer <code>k</code>, reverse the first <code>k</code> characters for every <code>2k</code> characters counting from the start of the string.</p>\n\n<p>If there are fewer than <code>k</code> characters left, reverse all of them. If there are less than <code>2k</code> but greater than or equal to <code>k</code> characters, then reverse the first <code>k</code> characters and leave the other as original.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"abcdefg\", k = 2\n<strong>Output:</strong> \"bacdfeg\"\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"abcd\", k = 2\n<strong>Output:</strong> \"bacd\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consists of only lowercase English letters.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-string-ii/solutions/",
    "solution": "[TOC]\n\n---\n### Approach #1: Direct [Accepted]\n\n**Intuition and Algorithm**\n\nWe will reverse each block of `2k` characters directly.\n\nEach block starts at a multiple of `2k`: for example, `0, 2k, 4k, 6k, ...`. One thing to be careful about is we may not reverse each block if there aren't enough characters.\n\nTo reverse a block of characters from `i` to `j`, we can swap characters in positions `i++` and `j--`.\n\n<iframe src=\"https://leetcode.com/playground/ke3DMSV2/shared\" frameBorder=\"0\" width=\"100%\" height=\"293\" name=\"ke3DMSV2\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the size of `s`. We build a helper array, plus reverse about half the characters in `s`.\n\n* Space Complexity: $$O(N)$$, the size of `a`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def reverseStr(self, s: str, k: int) -> str:\n    return s[:k][::-1] + s[k:2 * k] + self.reverseStr(s[2 * k:], k) if s else \"\"",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String reverseStr(String s, int k) {\n    StringBuilder sb = new StringBuilder(s);\n\n    for (int i = 0; i < sb.length(); i += 2 * k) {\n      int l = i;\n      int r = Math.min(i + k - 1, sb.length() - 1);\n      while (l < r) {\n        sb.setCharAt(l, s.charAt(r));\n        sb.setCharAt(r, s.charAt(l));\n        ++l;\n        --r;\n      }\n    }\n\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string reverseStr(string s, int k) {\n    for (size_t i = 0; i < s.length(); i += 2 * k) {\n      int l = i;\n      int r = min(i + k - 1, s.length() - 1);\n      while (l < r)\n        swap(s[l++], s[r--]);\n    }\n\n    return s;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/541.html",
    "category": "Algorithms",
    "acceptance_rate": 51.98058262373626,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 2130,
    "dislikes": 4101,
    "similar_questions": "[{\"title\": \"Reverse String\", \"titleSlug\": \"reverse-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse Words in a String III\", \"titleSlug\": \"reverse-words-in-a-string-iii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Faulty Keyboard\", \"titleSlug\": \"faulty-keyboard\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"304.4K\", \"totalSubmission\": \"585.7K\", \"totalAcceptedRaw\": 304427, \"totalSubmissionRaw\": 585656, \"acRate\": \"52.0%\"}",
    "title_pt": "Reverter String II",
    "description_pt": "<p>Dada uma string <code>s</code> e um inteiro <code>k</code>, reverta os primeiros <code>k</code> caracteres para cada <code>2k</code> caracteres contando a partir do início da string.</p>\n\n<p>Se restarem menos de <code>k</code> caracteres, reverta todos eles. Se restarem menos de <code>2k</code>, mas mais ou igual a <code>k</code> caracteres, então reverta os primeiros <code>k</code> caracteres e deixe os demais como estão originalmente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"abcdefg\", k = 2\n<strong>Saída:</strong> \"bacdfeg\"\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"abcd\", k = 2\n<strong>Saída:</strong> \"bacd\"\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s</code> consiste apenas de letras minúsculas do alfabeto inglês.</li>\n\t<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "542",
    "paidOnly": false,
    "title": "01 Matrix",
    "titleSlug": "01-matrix",
    "url": "https://leetcode.com/problems/01-matrix",
    "description_url": "https://leetcode.com/problems/01-matrix/description/",
    "description": "<p>Given an <code>m x n</code> binary matrix <code>mat</code>, return <em>the distance of the nearest </em><code>0</code><em> for each cell</em>.</p>\n\n<p>The distance between two cells sharing a common edge is <code>1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]]\n<strong>Output:</strong> [[0,0,0],[0,1,0],[0,0,0]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]]\n<strong>Output:</strong> [[0,0,0],[0,1,0],[1,2,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>mat[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n\t<li>There is at least one <code>0</code> in <code>mat</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as 1765: <a href=\"https://leetcode.com/problems/map-of-highest-peak/description/\" target=\"_blank\">https://leetcode.com/problems/map-of-highest-peak/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/01-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n    m = len(mat)\n    n = len(mat[0])\n    dirs = [0, 1, 0, -1, 0]\n    q = deque()\n    seen = [[False] * n for _ in range(m)]\n\n    for i in range(m):\n      for j in range(n):\n        if mat[i][j] == 0:\n          q.append((i, j))\n          seen[i][j] = True\n\n    while q:\n      i, j = q.popleft()\n      for k in range(4):\n        x = i + dirs[k]\n        y = j + dirs[k + 1]\n        if x < 0 or x == m or y < 0 or y == n:\n          continue\n        if seen[x][y]:\n          continue\n        mat[x][y] = mat[i][j] + 1\n        q.append((x, y))\n        seen[x][y] = True\n\n    return mat",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] updateMatrix(int[][] mat) {\n    final int m = mat.length;\n    final int n = mat[0].length;\n    final int[] dirs = new int[] {0, 1, 0, -1, 0};\n    Queue<int[]> q = new ArrayDeque<>();\n    boolean[][] seen = new boolean[m][n];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (mat[i][j] == 0) {\n          q.offer(new int[] {i, j});\n          seen[i][j] = true;\n        }\n\n    while (!q.isEmpty()) {\n      final int i = q.peek()[0];\n      final int j = q.poll()[1];\n      for (int k = 0; k < 4; ++k) {\n        final int x = i + dirs[k];\n        final int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (seen[x][y])\n          continue;\n        mat[x][y] = mat[i][j] + 1;\n        q.offer(new int[] {x, y});\n        seen[x][y] = true;\n      }\n    }\n\n    return mat;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {\n    const int m = mat.size();\n    const int n = mat[0].size();\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    queue<pair<int, int>> q;\n    vector<vector<bool>> seen(m, vector<bool>(n));\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j)\n        if (mat[i][j] == 0) {\n          q.emplace(i, j);\n          seen[i][j] = true;\n        }\n\n    while (!q.empty()) {\n      const auto [i, j] = q.front();\n      q.pop();\n      for (int k = 0; k < 4; ++k) {\n        const int x = i + dirs[k];\n        const int y = j + dirs[k + 1];\n        if (x < 0 || x == m || y < 0 || y == n)\n          continue;\n        if (seen[x][y])\n          continue;\n        mat[x][y] = mat[i][j] + 1;\n        q.emplace(x, y);\n        seen[x][y] = true;\n      }\n    }\n\n    return mat;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/542.html",
    "category": "Algorithms",
    "acceptance_rate": 51.160685965617134,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Breadth-First Search",
      "Matrix"
    ],
    "hints": [],
    "likes": 10089,
    "dislikes": 438,
    "similar_questions": "[{\"title\": \"Shortest Path to Get Food\", \"titleSlug\": \"shortest-path-to-get-food\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Remove Adjacent Ones in Matrix\", \"titleSlug\": \"minimum-operations-to-remove-adjacent-ones-in-matrix\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Difference Between Ones and Zeros in Row and Column\", \"titleSlug\": \"difference-between-ones-and-zeros-in-row-and-column\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"725.8K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 725832, \"totalSubmissionRaw\": 1418730, \"acRate\": \"51.2%\"}",
    "title_pt": "Matriz 01",
    "description_pt": "<p>Dada uma matriz binária <code>m x n</code> <code>mat</code>, retorne <em>a distância até o </em><code>0</code><em> mais próximo para cada célula</em>.</p>\n<p>A distância entre duas células que compartilham uma aresta comum é <code>1</code>.</p>\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/01-1-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> mat = [[0,0,0],[0,1,0],[0,0,0]]\n<strong>Saída:</strong> [[0,0,0],[0,1,0],[0,0,0]]\n</pre>\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/01-2-grid.jpg\" style=\"width: 253px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]]\n<strong>Saída:</strong> [[0,0,0],[0,1,0],[1,2,1]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= m * n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>mat[i][j]</code> é ou <code>0</code> ou <code>1</code>.</li>\n\t<li>Há pelo menos um <code>0</code> em <code>mat</code>.</li>\n</ul>\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que 1765: <a href=\"https://leetcode.com/problems/map-of-highest-peak/description/\" target=\"_blank\">https://leetcode.com/problems/map-of-highest-peak/</a></p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "543",
    "paidOnly": false,
    "title": "Diameter of Binary Tree",
    "titleSlug": "diameter-of-binary-tree",
    "url": "https://leetcode.com/problems/diameter-of-binary-tree",
    "description_url": "https://leetcode.com/problems/diameter-of-binary-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the length of the <strong>diameter</strong> of the tree</em>.</p>\n\n<p>The <strong>diameter</strong> of a binary tree is the <strong>length</strong> of the longest path between any two nodes in a tree. This path may or may not pass through the <code>root</code>.</p>\n\n<p>The <strong>length</strong> of a path between two nodes is represented by the number of edges between them.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,5]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [1,2]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/diameter-of-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n    ans = 0\n\n    def maxDepth(root: Optional[TreeNode]) -> int:\n      nonlocal ans\n      if not root:\n        return 0\n\n      l = maxDepth(root.left)\n      r = maxDepth(root.right)\n      ans = max(ans, l + r)\n      return 1 + max(l, r)\n\n    maxDepth(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int diameterOfBinaryTree(TreeNode root) {\n    maxDepth(root);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  int maxDepth(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    final int l = maxDepth(root.left);\n    final int r = maxDepth(root.right);\n    ans = Math.max(ans, l + r);\n    return 1 + Math.max(l, r);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int diameterOfBinaryTree(TreeNode* root) {\n    int ans = 0;\n    maxDepth(root, ans);\n    return ans;\n  }\n\n private:\n  int maxDepth(TreeNode* root, int& ans) {\n    if (root == nullptr)\n      return 0;\n\n    const int l = maxDepth(root->left, ans);\n    const int r = maxDepth(root->right, ans);\n    ans = max(ans, l + r);\n    return 1 + max(l, r);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/543.html",
    "category": "Algorithms",
    "acceptance_rate": 63.32769474858965,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 14693,
    "dislikes": 1160,
    "similar_questions": "[{\"title\": \"Diameter of N-Ary Tree\", \"titleSlug\": \"diameter-of-n-ary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Path With Different Adjacent Characters\", \"titleSlug\": \"longest-path-with-different-adjacent-characters\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"3.2M\", \"totalAcceptedRaw\": 2002498, \"totalSubmissionRaw\": 3162122, \"acRate\": \"63.3%\"}",
    "title_pt": "Diâmetro de uma Árvore Binária",
    "description_pt": "<p>Dado o <code>root</code> de uma árvore binária, retorne <em>o comprimento do <strong>diâmetro</strong> da árvore</em>.</p>\n\n<p>O <strong>diâmetro</strong> de uma árvore binária é o <strong>comprimento</strong> do maior caminho entre quaisquer dois nós em uma árvore. Esse caminho pode ou não passar pela <code>root</code>.</p>\n\n<p>O <strong>comprimento</strong> de um caminho entre dois nós é representado pelo número de arestas entre eles.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/06/diamtree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,5]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> 3 é o comprimento do caminho [4,2,1,3] ou [5,2,1,3].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,2]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "546",
    "paidOnly": false,
    "title": "Remove Boxes",
    "titleSlug": "remove-boxes",
    "url": "https://leetcode.com/problems/remove-boxes",
    "description_url": "https://leetcode.com/problems/remove-boxes/description/",
    "description": "<p>You are given several <code>boxes</code> with different colors represented by different positive numbers.</p>\n\n<p>You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of <code>k</code> boxes, <code>k &gt;= 1</code>), remove them and get <code>k * k</code> points.</p>\n\n<p>Return <em>the maximum points you can get</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> boxes = [1,3,2,2,2,3,4,3,1]\n<strong>Output:</strong> 23\n<strong>Explanation:</strong>\n[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----&gt; [1, 3, 3, 3, 1] (1*1=1 points) \n----&gt; [1, 1] (3*3=9 points) \n----&gt; [] (2*2=4 points)\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> boxes = [1,1,1]\n<strong>Output:</strong> 9\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> boxes = [1]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= boxes.length &lt;= 100</code></li>\n\t<li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-boxes/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeBoxes(self, boxes: List[int]) -> int:\n    # Dp(i, j, k) := max score of boxes[i..j] if k boxes equal to boxes[j]\n    @functools.lru_cache(None)\n    def dp(i: int, j: int, k: int) -> int:\n      if i > j:\n        return 0\n\n      r = j\n      sameBoxes = k + 1\n      while r > 0 and boxes[r - 1] == boxes[r]:\n        r -= 1\n        sameBoxes += 1\n      ans = dp(i, r - 1, 0) + sameBoxes * sameBoxes\n\n      for p in range(i, r):\n        if boxes[p] == boxes[r]:\n          ans = max(ans, dp(i, p, sameBoxes) + dp(p + 1, r - 1, 0))\n\n      return ans\n\n    return dp(0, len(boxes) - 1, 0)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int removeBoxes(int[] boxes) {\n    final int n = boxes.length;\n    // dp[i][j][k] := max score of boxes[i..j] if k boxes eqaul to boxes[j]\n    dp = new int[n][n][n];\n    return removeBoxes(boxes, 0, n - 1, 0);\n  }\n\n  private int[][][] dp;\n\n  private int removeBoxes(int[] boxes, int i, int j, int k) {\n    if (i > j)\n      return 0;\n    if (dp[i][j][k] > 0)\n      return dp[i][j][k];\n\n    int r = j;\n    int sameBoxes = k + 1;\n    while (r > 0 && boxes[r - 1] == boxes[r]) {\n      --r;\n      ++sameBoxes;\n    }\n    dp[i][j][k] = removeBoxes(boxes, i, r - 1, 0) + sameBoxes * sameBoxes;\n\n    for (int p = i; p < r; ++p)\n      if (boxes[p] == boxes[r])\n        dp[i][j][k] = Math.max(dp[i][j][k], removeBoxes(boxes, i, p, sameBoxes) +\n                                                removeBoxes(boxes, p + 1, r - 1, 0));\n\n    return dp[i][j][k];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int removeBoxes(vector<int>& boxes) {\n    const int n = boxes.size();\n    // dp[i][j][k] := max score of boxes[i..j] if k boxes eqaul to boxes[j]\n    dp.resize(n, vector<vector<int>>(n, vector<int>(n)));\n    return removeBoxes(boxes, 0, n - 1, 0);\n  }\n\n private:\n  vector<vector<vector<int>>> dp;\n\n  int removeBoxes(const vector<int>& boxes, int i, int j, int k) {\n    if (i > j)\n      return 0;\n    if (dp[i][j][k])\n      return dp[i][j][k];\n\n    int r = j;\n    int sameBoxes = k + 1;\n    while (r > 0 && boxes[r - 1] == boxes[r]) {\n      --r;\n      ++sameBoxes;\n    }\n    dp[i][j][k] = removeBoxes(boxes, i, r - 1, 0) + sameBoxes * sameBoxes;\n\n    for (int p = i; p < r; ++p)\n      if (boxes[p] == boxes[r])\n        dp[i][j][k] = max(dp[i][j][k], removeBoxes(boxes, i, p, sameBoxes) +\n                                           removeBoxes(boxes, p + 1, r - 1, 0));\n\n    return dp[i][j][k];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/546.html",
    "category": "Algorithms",
    "acceptance_rate": 48.2503930673882,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Memoization"
    ],
    "hints": [],
    "likes": 2362,
    "dislikes": 129,
    "similar_questions": "[{\"title\": \"Strange Printer\", \"titleSlug\": \"strange-printer\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Unique Flavors After Sharing K Candies\", \"titleSlug\": \"number-of-unique-flavors-after-sharing-k-candies\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"52.8K\", \"totalSubmission\": \"109.4K\", \"totalAcceptedRaw\": 52783, \"totalSubmissionRaw\": 109395, \"acRate\": \"48.2%\"}",
    "title_pt": "Remover Caixas",
    "description_pt": "<p>Você recebe várias <code>boxes</code> com cores diferentes representadas por números positivos distintos.</p>\n\n<p>Você pode passar por várias rodadas para remover caixas até que não reste nenhuma caixa. Cada vez, você pode escolher algumas caixas contíguas com a mesma cor (isto é, compostas por <code>k</code> caixas, <code>k &gt;= 1</code>), removê-las e મેળવtrar <code>k * k</code> pontos.</p>\n\n<p>Retorne <em>a quantidade máxima de pontos que você pode obter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> boxes = [1,3,2,2,2,3,4,3,1]\n<strong>Saída:</strong> 23\n<strong>Explicação:</strong>\n[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----&gt; [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----&gt; [1, 3, 3, 3, 1] (1*1=1 points) \n----&gt; [1, 1] (3*3=9 points) \n----&gt; [] (2*2=4 points)\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> boxes = [1,1,1]\n<strong>Saída:</strong> 9\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> boxes = [1]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= boxes.length &lt;= 100</code></li>\n\t<li><code>1 &lt;= boxes[i]&nbsp;&lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "547",
    "paidOnly": false,
    "title": "Number of Provinces",
    "titleSlug": "number-of-provinces",
    "url": "https://leetcode.com/problems/number-of-provinces",
    "description_url": "https://leetcode.com/problems/number-of-provinces/description/",
    "description": "<p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p>\n\n<p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p>\n\n<p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p>\n\n<p>Return <em>the total number of <strong>provinces</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg\" style=\"width: 222px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg\" style=\"width: 222px; height: 142px;\" />\n<pre>\n<strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n\t<li><code>n == isConnected.length</code></li>\n\t<li><code>n == isConnected[i].length</code></li>\n\t<li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li>\n\t<li><code>isConnected[i][i] == 1</code></li>\n\t<li><code>isConnected[i][j] == isConnected[j][i]</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-provinces/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given `n` cities, some of which are connected to other cities given by an `n x n` matrix `isConnected`. The connectivity is transitive, which means that if city `a` is directly connected with city `b` and city `b` is directly connected with city `c`, then city `a` is indirectly connected with city `c`.\n\nA province is defined as a group of directly or indirectly connected cities with no other cities outside of the group.\n\nOur task is to return the total number of provinces.\n\n---\n\n### Approach 1: Depth First Search\n\n#### Intuition\n\nWe can see that two cities `x` and `y` belong to the same province if there is a **path** from city `x` to city `y` using the cities that are directly connected.\n\nThis leads us to consider the problem in terms of graphs.\n\nEach city can be thought of as a node in a graph. The roads that directly connect the cities are the edges. If there is a path in this graph connecting cities `x` and `y`, then `x` and `y` are in the same province. Because the graph is undirected, `x` and `y` belong to the same province if and only if they are part of the same graph component.\n\n**The number of required provinces is the number of connected components formed in such a graph.**\n\nTo check the number of connected components in a graph, we can use a graph traversal algorithm like depth first search (DFS).\n\nIn DFS, we use a recursive function to explore nodes as far as possible along each branch. Upon reaching the end of a branch, we backtrack to the next branch and continue exploring.\n\nOnce we encounter an unvisited node, we will take one of its neighbor nodes (if exists) as the next node on this branch. Recursively call the function to take the next node as the 'starting node' and solve the subproblem.\n\n![img](../Figures/547/547-dfs.png)\n\nIf you are new to Depth First Search, please see our [LeetCode Explore Card](https://leetcode.com/explore/featured/card/graph/619/depth-first-search-in-graph/3882/) for more information on it!\n\nTo figure out how many connected components there are in the graph, we first mark all nodes as unvisited.\n\nWe iterate through all the nodes from `0` to `n - 1`, checking whether each `node` has been visited or not. As the graph is undirected, a DFS traversal from `node` would visit all of the nodes in the component to which `node` belongs. Whenever we see an unvisited node while looping through all the nodes, it means we have found a new component. We run the DFS traversal from the unvisited node to traverse over all the nodes in the new component, marking all these nodes as visited to avoid counting a component more than once.\n\nThe number of connected components in the graph is equal to the number of unvisited nodes we encounter (the number of times we start a DFS traversal) in this process.\n\n#### Algorithm\n\n1. Create an integer variable `n` which stores the number of cities.\n2. Create a `visit` array of length `n` to keep track of nodes that have been visited.\n3. Create an integer `numberOfComponents` which stores the number of connected components in the graph. Initialize it to `0`.\n4. Iterate through all of the nodes, and for each node `i` check if it has been visited or not. If node `i` is not visited, we increment `numberOfComponents` by `1` and start a DFS traversal:\n    - We use the `dfs` function to perform the traversal. For each call, pass `node`, `isConnected`, and `visit` as the parameters. We start with node `i`.\n    - We mark `node` as visited.\n    - We iterate over all the values in `isConnected[node]` to get the neighbors of `node`. If `isConnected[node][i] == 1`, one neighbor of `node` is `i` (as we have a direct edge between `node` and `i`). For each neighbor `i` that has not yet been visited, we recursively call `dfs` with `i` as the node.\n5. Return `numberOfComponents`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Z8EQGch8/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"Z8EQGch8\"></iframe>\n\n#### Complexity Analysis\n\nHere $n$ is the number of cities.\n\n* Time complexity: $O(n^2)$.\n    - Initializing the `visit` array takes $O(n)$ time.\n    - The `dfs` function visits each node once, which takes $O(n)$ time because there are $n$ nodes in total. From each `node`, we iterate over all possible edges using `isConnected[node]` which takes $O(n)$ time for each visited node. As a result, it takes a total of $O(n^2)$ time to visit all the nodes and iterate over its edges.\n\n* Space complexity: $O(n)$.\n    - The `visit` array takes $O(n)$ space.\n    - The recursion call stack used by `dfs` can have no more than $n$ elements in the worst-case scenario. It would take up $O(n)$ space in that case. \n\n---\n\n### Approach 2: Breadth First Search\n\n#### Intuition\n\nAs we just have to find the number of connected components in the graph, another method is to use a breadth-first search (BFS).\n\nBFS is an algorithm for traversing or searching a graph. It traverses in a level-wise manner, i.e., all the nodes at the present level (say `l`) are explored before moving on to the nodes at the next level (`l + 1`), where a level's number is the distance from a starting node. BFS is implemented with a queue.\n\nHere is an example with the steps:\n\n![img](../Figures/547/547-bfs.png)\n\nIf you are not familiar with BFS traversal, we suggest you read our [LeetCode Explore Card](https://leetcode.com/explore/featured/card/graph/620/breadth-first-search-in-graph/).\n\n#### Algorithm\n\n1. Create an integer variable `n` which stores the number of cities.\n2. Create a `visit` array of length `n` to keep track of nodes that have been visited.\n3. Create an integer `numberOfComponents` which stores the number of connected components in the graph. Initialize it to `0`.\n4. Iterate through all of the nodes, and for each node `i` check if it has been visited or not. If node `i` is not visited, we increment `numberOfComponents` by `1` and start a BFS traversal:\n    - We use the `bfs` function to perform the traversal. For each call, pass `node`, `isConnected`, and `visit` as the parameters. We start with node `i`.\n    - We create an integer queue `q` and push `node` into it. We also mark `node` as visited.\n    - We now loop until the queue is empty. The queue's first element, `node`, is popped out. We iterate over all the neighbors of `node` where the neighboring nodes are found using `isConnected[node]`. If any `neighbor` has not yet been visited, we mark it as visited and push it into the queue.\n5. Return `numberOfComponents`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/i3nKSSz5/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"i3nKSSz5\"></iframe>\n\n#### Complexity Analysis\n\nHere $n$ is the number of cities.\n\n* Time complexity: $O(n^2)$.\n    - Initializing the `visit` array takes $O(n)$ time.\n    - Each queue operation in the BFS algorithm takes $O(1)$ time, and a single node can only be pushed once, leading to $O(n)$ operations for $n$ nodes. As discussed above, we iterate over all possible edges using `isConnected[node]` which takes $O(n)$ time for each visited node, resulting in $O(n^2)$ operations in total in the worst-case scenario while visiting all nodes.\n\n* Space complexity: $O(n)$.\n    - The BFS queue takes $O(n)$ because each node is added, and in the worst-case scenario you could have a linear amount of nodes in the queue at once.\n    - The `visit` array takes $O(n)$ space as well.\n\n---\n\n### Approach 3: Union-find\n\n#### Intuition\n\nAnother approach to solving questions based on graph connectivity is the union-find data structure.\n\nA disjoint-set data structure also called a union–find data structure or merge–find set, is a data structure that stores a collection of disjoint (non-overlapping) sets. Equivalently, it stores a partition of a set into disjoint subsets. It provides operations for adding new sets, merging sets (replacing them by their union), and finding a representative member of a set. It implements two useful operations:\n\n1. `Find`: Determine which subset a particular element is in. This can be used to determine if two elements are in the same subset.\n2. `Union`: Join two subsets into a single subset.\n\nIf you are new to Union-Find, we suggest you read our [LeetCode Explore Card](https://leetcode.com/explore/learn/card/graph/618/disjoint-set/3881/). We will not talk about implementation details in this article, but only about the interface to the data structure.\n\nOur task, as with the previous approaches, is to count the number of connected components formed in the graph with cities acting as nodes and an edge between directly connected cities.\n\nWe initialize all nodes as separate components in the union-find data structure. We create a variable called `numberOfComponents` to count the number of connected components in the graph and initialize it to the number to the nodes.\n\nWe iterate over all the edges, decrementing `numberOfComponents` by `1` for each edge whenever two different components are merged into a single one using that edge.\n\n#### Algorithm\n\n1. Create an integer variable `n` which stores the number of cities.\n2. Create an instance of `UnionFind` of size `n`.\n3. Create an integer variable `numberOfComponents` to count the number of connected components in the graph. We initialize it to `n` as each node initially behaves as a separate component.\n4. We iterate over `isConnected` using two loops, outer loop running from `i = 0` to `n - 1` and an inner loop running from `j = i + 1` to `n - 1`. For each pair of directly connected cities `i` and `j`, i.e., `isConnected[i][j] == 1`, we use the `find` operation to determine which components both of them belong to. If they belong to different components, i.e., `find(i)!= find(j)`, we perform a `union` operation on both nodes, combining the two different connected components into a single connected component. We also reduce `numberOfComponents` by one as we just merged two different components. We don't do anything if `i` and `j` already belong to the same component.\n5. Return `numberOfComponents`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/bLutVW9r/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"bLutVW9r\"></iframe>\n\n#### Complexity Analysis\n\nHere $n$ is the number of cities.\n\n* Time complexity: $O(n^2)$.\n    - We need $O(n^2)$ time to iterate over all the values in `isConnected`.\n    - For $T$ operations, the amortized time complexity of the union-find algorithm (using path compression with union by rank) is $O(alpha(T))$. Here, $\\alpha(T)$ is the inverse Ackermann function that grows so slowly, that it doesn't exceed $4$ for all reasonable $T$ (approximately $ T < 10^{600}$). You can read more about the complexity of union-find [here](https://en.wikipedia.org/wiki/Disjoint-set_data_structure#Time_complexity).  Because the function grows so slowly, we consider it to be $O(1)$.\n    - Initializing `UnionFind` takes $O(n)$ time beacuse we are initializing the `parent` and `rank` arrays of size `n` each.\n    - We iterate through every edge and use the `find` operation to find the component of nodes connected by each edge. It takes $O(1)$ per operation and takes $O(e)$ time for all the $e$ edges. We can have a maximum of $O(n^2)$ edges in between $n$ nodes (each node is connected to other), so it would take $O(n^2)$ time. If nodes from different components are connected by an edge, we also perform `union` of the nodes, which takes $O(1)$ time per operation. In the worst-case scenario, it may be called $O(n)$ times to connect all the components to form a connected graph with only one component.\n\n* Space complexity: $O(n)$.\n    - We are using the `parent` and `rank` arrays, both of which require $O(n)$ space each.",
    "solution_code_python": "\t\t\t\n\nclass UnionFind:\n  def __init__(self, n: int):\n    self.count = n\n    self.id = list(range(n))\n\n  def union(self, u: int, v: int) -> None:\n    i = self.find(u)\n    j = self.find(v)\n    if i == j:\n      return\n    self.id[i] = j\n    self.count -= 1\n\n  def find(self, u: int) -> int:\n    if self.id[u] != u:\n      self.id[u] = self.find(self.id[u])\n    return self.id[u]\n\n\nclass Solution:\n  def findCircleNum(self, M: List[List[int]]) -> int:\n    n = len(M)\n    uf = UnionFind(n)\n\n    for i in range(n):\n      for j in range(i, n):\n        if M[i][j] == 1:\n          uf.union(i, j)\n\n    return uf.count",
    "solution_code_java": "\t\t\t\n\nclass UnionFind {\n  public UnionFind(int n) {\n    count = n;\n    id = new int[n];\n    for (int i = 0; i < n; ++i)\n      id[i] = i;\n  }\n\n  public void union(int u, int v) {\n    final int i = find(u);\n    final int j = find(v);\n    if (i == j)\n      return;\n    id[i] = j;\n    --count;\n  }\n\n  public int getCount() {\n    return count;\n  }\n\n  private int count;\n  private int[] id;\n\n  private int find(int u) {\n    return id[u] == u ? u : (id[u] = find(id[u]));\n  }\n}\n\nclass Solution {\n  public int findCircleNum(int[][] M) {\n    final int n = M.length;\n    UnionFind uf = new UnionFind(n);\n\n    for (int i = 0; i < n; ++i)\n      for (int j = i; j < n; ++j)\n        if (M[i][j] == 1)\n          uf.union(i, j);\n\n    return uf.getCount();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass UnionFind {\n public:\n  UnionFind(int n) : count(n), id(n) {\n    iota(begin(id), end(id), 0);\n  }\n\n  void union_(int u, int v) {\n    const int i = find(u);\n    const int j = find(v);\n    if (i == j)\n      return;\n    id[i] = j;\n    --count;\n  }\n\n  int getCount() const {\n    return count;\n  }\n\n private:\n  int count;\n  vector<int> id;\n\n  int find(int u) {\n    return id[u] == u ? u : id[u] = find(id[u]);\n  }\n};\n\nclass Solution {\n public:\n  int findCircleNum(vector<vector<int>>& M) {\n    const int n = M.size();\n    UnionFind uf(n);\n\n    for (int i = 0; i < n; ++i)\n      for (int j = i; j < n; ++j)\n        if (M[i][j] == 1)\n          uf.union_(i, j);\n\n    return uf.getCount();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/547.html",
    "category": "Algorithms",
    "acceptance_rate": 68.40079132607761,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Graph"
    ],
    "hints": [],
    "likes": 10377,
    "dislikes": 388,
    "similar_questions": "[{\"title\": \"Number of Connected Components in an Undirected Graph\", \"titleSlug\": \"number-of-connected-components-in-an-undirected-graph\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Robot Return to Origin\", \"titleSlug\": \"robot-return-to-origin\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sentence Similarity\", \"titleSlug\": \"sentence-similarity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sentence Similarity II\", \"titleSlug\": \"sentence-similarity-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Earliest Moment When Everyone Become Friends\", \"titleSlug\": \"the-earliest-moment-when-everyone-become-friends\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Detonate the Maximum Bombs\", \"titleSlug\": \"detonate-the-maximum-bombs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1195611, \"totalSubmissionRaw\": 1747947, \"acRate\": \"68.4%\"}",
    "title_pt": "Número de Províncias",
    "description_pt": "<p>Há <code>n</code> cidades. Algumas delas estão conectadas, enquanto outras não. Se a cidade <code>a</code> está conectada diretamente com a cidade <code>b</code>, e a cidade <code>b</code> está conectada diretamente com a cidade <code>c</code>, então a cidade <code>a</code> está conectada indiretamente com a cidade <code>c</code>.</p>\n\n<p>Uma <strong>província</strong> é um grupo de cidades conectadas direta ou indiretamente e sem nenhuma outra cidade fora do grupo.</p>\n\n<p>Você recebe uma matriz <code>n x n</code> <code>isConnected</code> em que <code>isConnected[i][j] = 1</code> se a <code>i<sup>th</sup></code> cidade e a <code>j<sup>th</sup></code> cidade estão diretamente conectadas, e <code>isConnected[i][j] = 0</code> caso contrário.</p>\n\n<p>Retorne <em>o número total de <strong>províncias</strong></em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg\" style=\"width: 222px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg\" style=\"width: 222px; height: 142px;\" />\n<pre>\n<strong>Entrada:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 200</code></li>\n\t<li><code>n == isConnected.length</code></li>\n\t<li><code>n == isConnected[i].length</code></li>\n\t<li><code>isConnected[i][j]</code> é <code>1</code> ou <code>0</code>.</li>\n\t<li><code>isConnected[i][i] == 1</code></li>\n\t<li><code>isConnected[i][j] == isConnected[j][i]</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "550",
    "paidOnly": false,
    "title": "Game Play Analysis IV",
    "titleSlug": "game-play-analysis-iv",
    "url": "https://leetcode.com/problems/game-play-analysis-iv",
    "description_url": "https://leetcode.com/problems/game-play-analysis-iv/description/",
    "description": "<p>Table: <code>Activity</code></p>\n\n<pre>\n+--------------+---------+\n| Column Name  | Type    |\n+--------------+---------+\n| player_id    | int     |\n| device_id    | int     |\n| event_date   | date    |\n| games_played | int     |\n+--------------+---------+\n(player_id, event_date) is the primary key (combination of columns with unique values) of this table.\nThis table shows the activity of players of some games.\nEach row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a&nbsp;solution&nbsp;to report the <strong>fraction</strong> of players that logged in again on the day after the day they first logged in, <strong>rounded to 2 decimal places</strong>. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1         | 2         | 2016-03-01 | 5            |\n| 1         | 2         | 2016-03-02 | 6            |\n| 2         | 3         | 2017-06-25 | 1            |\n| 3         | 1         | 2016-03-02 | 0            |\n| 3         | 4         | 2018-07-03 | 5            |\n+-----------+-----------+------------+--------------+\n<strong>Output:</strong> \n+-----------+\n| fraction  |\n+-----------+\n| 0.33      |\n+-----------+\n<strong>Explanation:</strong> \nOnly the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/game-play-analysis-iv/solutions/",
    "solution": "[TOC]\n\n# Solution\n---\n\n### Overview\n\n> **Problem reference:** Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.\n\nThis problem is a natural extension or follow-up to [part\nII](https://leetcode.com/problems/game-play-analysis-ii/) of the five-part Game Play Analysis problem series. Why? Because counting the number of players who logged in for at least two consecutive days starting from their first login date naturally involves starting the problem-solving process by finding out the first login date for each player (which, we should note, actually *is* the solution to [part I](https://leetcode.com/problems/game-play-analysis-i/) in this problem series).\n\n\nBut finding each player's first login date is only a start to solving this\nproblem. We need to somehow use this information to determine whether or not\neach player under consideration logged in the day after their first log in\ndate. How we go about making this determination is the crux of this problem.\n\n---\n\n## pandas\n\n### Approach 1: Date Manipulation and Conditional Aggregation\n\n**Visualization of approach 1**\n\n![fig](../Figures/550/550-1.png)\n\n#### Intuition\n\nLet's breakdown the steps involved in this approach given the followin input DataFrame:\n\n<table>\n<tr><th>player_id</th><th>device_id</th><th>event_date</th><th>games_played</th></tr>\n<tr><td>1</td><td>2</td><td>2016-03-01</td><td>5</td></tr>\n<tr><td>1</td><td>2</td><td>2016-03-02</td><td>6</td></tr>\n<tr><td>2</td><td>3</td><td>2017-06-25</td><td>1</td></tr>\n<tr><td>3</td><td>1</td><td>2016-03-02</td><td>0</td></tr>\n<tr><td>3</td><td>4</td><td>2018-07-03</td><td>5</td></tr>\n</table>\n<br>\n\n**Step 1: Identifying the First Login Date**\n   - **Objective**: To determine the first date each player logged in.\n   - **Intuition**: By grouping the data by `player_id` and getting the minimum `event_date`, we pinpoint the initial login date for each individual player. This forms our baseline for tracking each player's login activity over time.\n```python\nfirst_login = activity.groupby('player_id')['event_date'].min().reset_index()\n```\n<table>\n<tr><th>player_id</th><th>event_date</th></tr>\n<tr><td>1</td><td>2016-03-01</td></tr>\n<tr><td>2</td><td>2017-06-25</td></tr>\n<tr><td>3</td><td>2016-03-02</td></tr>\n</table>\n<br>\n\n**Step 2: Calculating the Day Before Each Event Date**\n   - **Objective**: To facilitate identifying consecutive logins.\n   - **Intuition**: Note that in the question, consecutive dates actually represent two adjacent dates with a one-day difference. Therefore, we create a column that represents the day before each `event_date` to help us identify consecutive logins in the subsequent steps. This column will essentially allow us to match it with the first login date to see if a player logged in consecutively. For instance, if a player first logged in on `2016-03-02` and had consecutive logins on `2016-03-03`, we would add a value of `day_before_event = 2016-03-02` to the second record, which matches the first login date.\n\n```python\nactivity['day_before_event'] = activity['event_date'] - pd.to_timedelta(1, unit='D')\n```\n\n<table>\n<tr><th>player_id</th><th>device_id</th><th>event_date</th><th>games_played</th><th>day_before_event</th></tr>\n<tr><td>1</td><td>2</td><td>2016-03-01</td><td>5</td><td>2016-02-29</td></tr>\n<tr><td>1</td><td>2</td><td>2016-03-02</td><td>6</td><td>2016-03-01</td></tr>\n<tr><td>2</td><td>3</td><td>2017-06-25</td><td>1</td><td>2017-06-24</td></tr>\n<tr><td>3</td><td>1</td><td>2016-03-02</td><td>0</td><td>2016-03-01</td></tr>\n<tr><td>3</td><td>4</td><td>2018-07-03</td><td>5</td><td>2018-07-02</td></tr>\n</table>\n<br>\n\n**Step 3: Merging DataFrames to Identify Potential Consecutive Logins**\n   - **Objective**: To align actual login dates with the first login dates of each player.\n   - **Intuition**: We merge the data on 'player_id' to get a combined dataset where we have details of each player’s first login day along with all other days they logged in. This prepares us to directly compare whether any of the actual login dates align with a day after the first login date, highlighting consecutive logins.\n\n```python\nmerged_df = activity.merge(first_login, on='player_id', suffixes=('_actual', '_first'))\n```\n\n<table>\n<tr><th>player_id</th><th>device_id</th><th>event_date_actual</th><th>games_played</th><th>day_before_event</th><th>event_date_first</th></tr>\n<tr><td>1</td><td>2</td><td>2016-03-01</td><td>5</td><td>2016-02-29</td><td>2016-03-01</td></tr>\n<tr><td>1</td><td>2</td><td>2016-03-02</td><td>6</td><td>2016-03-01</td><td>2016-03-01</td></tr>\n<tr><td>2</td><td>3</td><td>2017-06-25</td><td>1</td><td>2017-06-24</td><td>2017-06-25</td></tr>\n<tr><td>3</td><td>1</td><td>2016-03-02</td><td>0</td><td>2016-03-01</td><td>2016-03-02</td></tr>\n<tr><td>3</td><td>4</td><td>2018-07-03</td><td>5</td><td>2018-07-02</td><td>2016-03-02</td></tr>\n</table>\n<br>\n\n**Step 4: Identifying Consecutive Logins**\n   - **Objective**: To pinpoint the exact instances of consecutive logins occurring a day after the first login.\n   - **Intuition**: By filtering the merged dataset for rows where the 'day_before_event' equals the 'event_date_first', we identify the precise moments where a login took place a day after the first login, effectively highlighting consecutive logins.\n\n```python\nconsecutive_login = merged_df[merged_df['day_before_event'] == merged_df['event_date_first']]\n```\n\n<table>\n<tr><th>player_id</th><th>device_id</th><th>event_date_actual</th><th>games_played</th><th>day_before_event</th><th>event_date_first</th></tr>\n<tr><td>1</td><td>2</td><td>2016-03-02</td><td>6</td><td>2016-03-01</td><td>2016-03-01</td></tr>\n</table>\n<br>\n\n**Step 5: Computing the Fraction of Consecutive Logins**\n   - **Objective**: To find the fraction representing players who logged back in the day following their first login.\n   - **Intuition**: Here we find the unique count of players who logged in consecutively and divide it by the total unique count of players in the dataset. This yields the proportion of players who exhibited this behavior, giving us a sense of player retention after the first login.\n\n```python\nfraction = round(consecutive_login['player_id'].nunique() / activity['player_id'].nunique(), 2)\n```\nReturns: `0.33`\n\n**Step 6: Formatting the Output**\n   - **Objective**: To prepare the final output.\n   - **Intuition**: Creating a new DataFrame to hold the calculated fraction ensures that we can return the results in a structured and readable format, fulfilling the requirements of our function's return type.\n\n```python\noutput_df = pd.DataFrame({'fraction': [fraction]})\n```\n\n<table>\n<tr><th>fraction</th></tr>\n<tr><td>0.33</td></tr>\n</table>\n<br>\n\n#### Implementation\n\n```python\nimport pandas as pd\n\ndef gameplay_analysis(activity: pd.DataFrame) -> pd.DataFrame:\n    # Step 1: Find the first login date for each player\n    first_login = activity.groupby('player_id')['event_date'].min().reset_index()\n    \n    # Step 2: Create a new column for the day before each event_date in the original DataFrame\n    activity['day_before_event'] = activity['event_date'] - pd.to_timedelta(1, unit='D')\n    \n    # Step 3: Merge the dataframes to find rows where player logged in a day after their first login\n    merged_df = activity.merge(first_login, on='player_id', suffixes=('_actual', '_first'))\n    \n    # Step 4: Find the rows where the actual event date matches the day after the first login date\n    consecutive_login = merged_df[merged_df['day_before_event'] == merged_df['event_date_first']]\n    \n    # Step 5: Calculate the fraction of players that logged in again on the day after their first login\n    fraction = round(consecutive_login['player_id'].nunique() / activity['player_id'].nunique(), 2)\n    \n    # Step 6: Create a dataframe to hold the output\n    output_df = pd.DataFrame({'fraction': [fraction]})\n    \n    return output_df\n```\n\n\n---\n\n## Database\n\n### Approach 1: Subqueries and multi-value use of the `IN` comparison operator\n\n#### Intuition\n\nThe preferred solution approach to [part\nII](https://leetcode.com/problems/game-play-analysis-ii/) in this problem\nseries involved using the `IN` comparison operator in a rather creative or\nnuanced way, namely *using more than a single value* for comparison:\n\n```sql\nSELECT\n  A1.player_id,\n  A1.device_id\nFROM\n  Activity A1\nWHERE\n  (A1.player_id, A1.event_date) IN (\n    SELECT\n      A2.player_id,\n      MIN(A2.event_date)\n    FROM\n      Activity A2\n    GROUP BY\n      A2.player_id\n  );\n```\n\nWe can use a similar idea for this problem, where, again, we rely on our\nability to access the tuples `(player_id, first_login)` in some manner:\n\n```sql\n(val1, val2) IN (\n  SELECT\n    A.player_id,\n    MIN(A.event_date) AS first_login\n  FROM\n    Activity A\n  GROUP BY\n    A.player_id\n)\n```\n\nBut what should `val1` and `val2` be? We must have `player_id` as `val1`, but the choice for `val2` is less apparent. We need, in some form or fashion, to be able to relate `val2` to the first login date corresponding to the `player_id` represented by `val1`; specifically, `val2` needs to be a date that is one day *after* the first login date being referenced. How can we achieve this?\n\n#### Algorithm\n\n1. Find the first login date for each player: `(player_id, first_login)`.\n2. Determine which tuples, if any, exist such that\n\n    ```\n    (player_id, day_after_first_login) = (player_id, first_login)\n    ```\n\n    The existence of such a tuple will confirm that whichever `player_id` is\n    being considered logged in the day after their first login date (i.e.,\n    `day_after_first_login`).\n\n3. Divide the total number of `player_id` values obtained from the process\n   described above by the *total number* of distinct `player_id` values from\n   the entire `Activity` table and round the result to two decimal places.\n\n#### Implementation\n\n##### MySQL\n\n```sql\nSELECT\n  ROUND(\n    COUNT(A1.player_id)\n    / (SELECT COUNT(DISTINCT A3.player_id) FROM Activity A3)\n  , 2) AS fraction\nFROM\n  Activity A1\nWHERE\n  (A1.player_id, DATE_SUB(A1.event_date, INTERVAL 1 DAY)) IN (\n    SELECT\n      A2.player_id,\n      MIN(A2.event_date)\n    FROM\n      Activity A2\n    GROUP BY\n      A2.player_id\n  );\n```\n\n**Note:** We only need to use `COUNT(A1.player_id)` in the `ROUND()` function above as opposed to `COUNT(DISTINCT A1.player_id)` since `(player_id, event_date)` is the primary key of the `Activity` table (i.e., it is not possible for the same player to have duplicated `event_date` entries for the date after the player's initial login date).\n\n---\n\n### Approach 2: CTEs and `INNER JOIN`\n\n#### Intuition\n\nCommon table expressions (CTEs) are powerful not only because of what they\nallow us to *do* but also because of how they allow us to *think*. We can use CTEs to our advantage here so as to approach the problem-solving process in a more or less \"linear\" fashion:\n\n1. Identify the first login date for each player.\n2. Identify the number of players who logged in the day after their first login date.\n3. Divide the number of players identified in step 2 by the number of players identified in step 1 and round the result to two decimal places.\n\n#### Algorithm\n\nSee above.\n\n#### Implementation\n\n##### MySQL\n\n```sql\nWITH first_logins AS (\n  SELECT\n    A.player_id,\n    MIN(A.event_date) AS first_login\n  FROM\n    Activity A\n  GROUP BY\n    A.player_id\n), consec_logins AS (\n  SELECT\n    COUNT(A.player_id) AS num_logins\n  FROM\n    first_logins F\n    INNER JOIN Activity A ON F.player_id = A.player_id\n    AND F.first_login = DATE_SUB(A.event_date, INTERVAL 1 DAY)\n)\nSELECT\n  ROUND(\n    (SELECT C.num_logins FROM consec_logins C)\n    / (SELECT COUNT(F.player_id) FROM first_logins F)\n  , 2) AS fraction;\n```\n\n**Note:** As with Approach 1, observe that `COUNT(A.player_id)` is sufficient in the `consec_logins` CTE since `(player_id, event_date)` is the primary key of the `Activity` table.\n\n---\n\n### Database Conclusion\n\nApproach 1 is beautiful in its own right. It is elegant and builds on work done previously throughout this problem series. But we prefer Approach 2 due to its relative simplicity, performance, and rather principled approach. Specifically, you may be hard-pressed to come up with Approach 1 on the spot in an interview. It should be much more manageable to reproduce a solution akin to Approach 2 in an interview setting.",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/550.html",
    "category": "Database",
    "acceptance_rate": 39.29748671218671,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1197,
    "dislikes": 228,
    "similar_questions": "[{\"title\": \"Game Play Analysis III\", \"titleSlug\": \"game-play-analysis-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Game Play Analysis V\", \"titleSlug\": \"game-play-analysis-v\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"313.8K\", \"totalSubmission\": \"798.5K\", \"totalAcceptedRaw\": 313781, \"totalSubmissionRaw\": 798476, \"acRate\": \"39.3%\"}",
    "title_pt": "Análise de Jogadas IV",
    "description_pt": "<p>Tabela: <code>Activity</code></p>\n\n<pre>\n+--------------+---------+\n| Nome da Coluna | Tipo  |\n+--------------+---------+\n| player_id    | int     |\n| device_id    | int     |\n| event_date   | date    |\n| games_played | int     |\n+--------------+---------+\n(player_id, event_date) é a chave primária (combinação de colunas com valores únicos) desta tabela.\nEsta tabela mostra a atividade de jogadores de alguns jogos.\nCada linha é um registro de um jogador que fez login e jogou um número de partidas (possivelmente 0) antes de sair em algum dia usando algum dispositivo.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma&nbsp;solução&nbsp;para reportar a <strong>fração</strong> de jogadores que fizeram login novamente no dia seguinte ao dia em que fizeram login pela primeira vez, <strong>arredondada para 2 casas decimais</strong>. Em outras palavras, você precisa contar o número de jogadores que fizeram login por pelo menos dois dias consecutivos começando a partir da data de seu primeiro login e, então, dividir esse número pelo total de jogadores.</p>\n\n<p>O formato da&nbsp;saída&nbsp;está no seguinte exemplo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1         | 2         | 2016-03-01 | 5            |\n| 1         | 2         | 2016-03-02 | 6            |\n| 2         | 3         | 2017-06-25 | 1            |\n| 3         | 1         | 2016-03-02 | 0            |\n| 3         | 4         | 2018-07-03 | 5            |\n+-----------+-----------+------------+--------------+\n<strong>Saída:</strong> \n+-----------+\n| fraction  |\n+-----------+\n| 0.33      |\n+-----------+\n<strong>Explicação:</strong> \nSomente o jogador com id 1 fez login novamente após o primeiro dia em que havia feito login, então a resposta é 1/3 = 0.33\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "551",
    "paidOnly": false,
    "title": "Student Attendance Record I",
    "titleSlug": "student-attendance-record-i",
    "url": "https://leetcode.com/problems/student-attendance-record-i",
    "description_url": "https://leetcode.com/problems/student-attendance-record-i/description/",
    "description": "<p>You are given a string <code>s</code> representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p>\n\n<ul>\n\t<li><code>&#39;A&#39;</code>: Absent.</li>\n\t<li><code>&#39;L&#39;</code>: Late.</li>\n\t<li><code>&#39;P&#39;</code>: Present.</li>\n</ul>\n\n<p>The student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p>\n\n<ul>\n\t<li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li>\n\t<li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li>\n</ul>\n\n<p>Return <code>true</code><em> if the student is eligible for an attendance award, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;PPALLP&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The student has fewer than 2 absences and was never late 3 or more consecutive days.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;PPALLL&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s[i]</code> is either <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code>, or <code>&#39;P&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/student-attendance-record-i/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkRecord(self, s: str) -> bool:\n    return s.count('A') <= 1 and 'LLL' not in s",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkRecord(String s) {\n    return s.indexOf(\"A\") == s.lastIndexOf(\"A\") && !s.contains(\"LLL\");\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkRecord(string s) {\n    int countA = 0;\n    int countL = 0;\n\n    for (const char c : s) {\n      if (c == 'A' && ++countA > 1)\n        return false;\n      if (c != 'L')\n        countL = 0;\n      else if (++countL > 2)\n        return false;\n    }\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/551.html",
    "category": "Algorithms",
    "acceptance_rate": 49.583533557584495,
    "topics": [
      "String"
    ],
    "hints": [],
    "likes": 812,
    "dislikes": 55,
    "similar_questions": "[{\"title\": \"Student Attendance Record II\", \"titleSlug\": \"student-attendance-record-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"253.8K\", \"totalSubmission\": \"511.9K\", \"totalAcceptedRaw\": 253831, \"totalSubmissionRaw\": 511926, \"acRate\": \"49.6%\"}",
    "title_pt": "Registro de Frequência do Estudante I",
    "description_pt": "<p>Você recebe uma string <code>s</code> representando um registro de frequência de um estudante, em que cada caractere indica se o estudante esteve ausente, atrasado ou presente naquele dia. O registro contém apenas os três caracteres a seguir:</p>\n\n<ul>\n\t<li><code>&#39;A&#39;</code>: Ausente.</li>\n\t<li><code>&#39;L&#39;</code>: Atrasado.</li>\n\t<li><code>&#39;P&#39;</code>: Presente.</li>\n</ul>\n\n<p>O estudante é elegível para um prêmio de frequência se atender a <strong>ambos</strong> os seguintes critérios:</p>\n\n<ul>\n\t<li>O estudante esteve ausente (<code>&#39;A&#39;</code>) por <strong>estritamente</strong> menos de 2 dias no <strong>total</strong>.</li>\n\t<li>O estudante <strong>nunca</strong> esteve atrasado (<code>&#39;L&#39;</code>) por 3 ou mais dias <strong>consecutivos</strong>.</li>\n</ul>\n\n<p>Retorne <code>true</code><em> se o estudante for elegível para um prêmio de frequência, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;PPALLP&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> O estudante tem menos de 2 ausências e nunca esteve atrasado por 3 ou mais dias consecutivos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;PPALLL&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> O estudante esteve atrasado por 3 dias consecutivos nos últimos 3 dias, portanto não é elegível para o prêmio.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s[i]</code> é <code>&#39;A&#39;</code>, <code>&#39;L&#39;</code> ou <code>&#39;P&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "552",
    "paidOnly": false,
    "title": "Student Attendance Record II",
    "titleSlug": "student-attendance-record-ii",
    "url": "https://leetcode.com/problems/student-attendance-record-ii",
    "description_url": "https://leetcode.com/problems/student-attendance-record-ii/description/",
    "description": "<p>An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:</p>\n\n<ul>\n\t<li><code>&#39;A&#39;</code>: Absent.</li>\n\t<li><code>&#39;L&#39;</code>: Late.</li>\n\t<li><code>&#39;P&#39;</code>: Present.</li>\n</ul>\n\n<p>Any student is eligible for an attendance award if they meet <strong>both</strong> of the following criteria:</p>\n\n<ul>\n\t<li>The student was absent (<code>&#39;A&#39;</code>) for <strong>strictly</strong> fewer than 2 days <strong>total</strong>.</li>\n\t<li>The student was <strong>never</strong> late (<code>&#39;L&#39;</code>) for 3 or more <strong>consecutive</strong> days.</li>\n</ul>\n\n<p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of possible attendance records of length</em> <code>n</code><em> that make a student eligible for an attendance award. The answer may be very large, so return it <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> There are 8 records with length 2 that are eligible for an award:\n&quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot;\nOnly &quot;AA&quot; is not eligible because there are 2 absences (there need to be fewer than 2).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 10101\n<strong>Output:</strong> 183236316\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/student-attendance-record-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Top-Down Dynamic Programming with Memoization\n\n#### Intuition  \n\nA trivial way to approach this problem would be to generate all possible combinations of `'P'`, `'A'`, and `'L'` of length `n`, and then check whether the currently generated combination is eligible for an attendance award (for convenience, let's call the combination eligible for an attendance award a **valid combination**, and its opposite an **invalid combination**). \n\n![all_combinations](../Figures/552/Slide1.jpg)\n\n> **Note:** This approach will generate all possible combinations, so it is a sub-optimal approach and will result in a TLE. However, understanding this approach is a stepping stone to further optimization.\n\n<br /> \n\n\nTo generate all combinations of length `n`, we will choose a character from `'P'`, `'A'`, and `'L'` for all `n` positions one by one. \n\nWhen we choose a character for the first position, we will be left with `n - 1` positions, so now we have to make a combination of length `n - 1`. We can use a recursive approach here as our bigger problem reduces to a smaller similar sub-problem with each step.    \nWe choose any character from `'P'`, `'A'`, and `'L'` for the current position and then recursively generate the remaining combination of length `n - 1`.\n\n**Note:** This article uses recursion techniques; if you are not familiar with recursion, check out our [recursion explore card](https://leetcode.com/explore/learn/card/recursion-i/250/principle-of-recursion/1439/).\n\n\n\n**Determining the recurrence relation:**\n\nWe define a recursive function `generate_combination(n)` that generates combinations of length `n`.   \nFirst, we choose a character for the current position (choose, `'P'`, `'A'`, and `'L'` one by one), and then we recursively get the combinations of length `n - 1` using the function `generate_combination(n - 1)` to make combinations of length `n`. \n\n```python3\ncurrent_subproblem_combinations  = 'P' + generate_combination(n - 1) \ncurrent_subproblem_combinations += 'A' + generate_combination(n - 1) \ncurrent_subproblem_combinations += 'L' + generate_combination(n - 1) \n```\n\n\nInstead of getting combinations of length `n - 1`  three times, we will get those combinations once and store and use them three times. Thus, saving us some runtime.\n\n```python3\nsmaller_subproblem_combinations = generate_combination(n - 1)\n\ncurrent_subproblem_combinations  = 'P' + smaller_subproblem_combinations \ncurrent_subproblem_combinations += 'A' + smaller_subproblem_combinations \ncurrent_subproblem_combinations += 'L' + smaller_subproblem_combinations \n```\n\n<br />\n\n**Determining the base case:**\n\nIf `n` is `0`, it means we have to generate a combination of length `0`, thus, we can return an empty string from here.\n\n<br />\n\n```python\ndef generate_combination(n) -> List:\n    # Base case.\n    if n == 0:\n        return ['']\n\n    # Get all combinations of length 'n - 1'.\n    smaller_subproblem_combinations = generate_combination(n - 1)\n\n    # Generate and return all combinations of length 'n' using combinations of length 'n - 1'.\n    current_subproblem_combinations  = 'P' + smaller_subproblem_combinations \n    current_subproblem_combinations += 'A' + smaller_subproblem_combinations \n    current_subproblem_combinations += 'L' + smaller_subproblem_combinations\n    return current_subproblem_combinations\n\n# Get all combinations.\nall_combinations = generate_combination(n)\n# Then check all combinations eligible for the award.\n```\n\n![recursion_image](../Figures/552/Slide2.jpg)\n\n\nIn this approach, we can see a problem: if the combination becomes invalid at the beginning, then there is no benefit in generating all the combinations of suffixes that follow it.\n\n![early_exit](../Figures/552/Slide3.jpg)\n\n<br />\n\n**Optimizing the recursion:**\n\nIf the current combination so far is invalid, it is best to stop the recursive call early to save some time. Remember that the problem states that we can have at most `1` `'A'` and `2` consecutive `'L'`, so these conditions can be used to perform the early exit.   \n\nTo do this, while generating combinations we need to keep track of the total number of `'A'` (absences) so far and the number of consecutive `'L'` (lates) at the end of our combination so far.     \nWhen we choose a character for the current position, we change the respective counts and then make the next recursive call so that our combination doesn't exceed the maximum allowed counts.\n\n\nWhen `n` becomes `0`, it will be guaranteed that the combination is eligible for the award, otherwise, we would have already exited from the function. Previously, we were returning the whole combination string as we were required to verify if that particular combination would be eligible for the award or not, but this is not required now, so we can return `1` to indicate that we will count this combination.     \nSimilarly, we will return `0` whenever we exit from the function and do not need to count the combinations.\n\n```python\n# Exit condition / Base case.\nif total_absences >= 2 or consecutive_lates >= 3: return 0\nif n == 0: return 1\n```\n\n<br />\n\nSo, our function will now return the number of combinations of length `n` eligible for the award, `eligible_combinations(n, total_absences, consecutive_lates) -> int`. \n\n\nWhenever we choose an option either `'P'`, `'A'`, or `'L'`, we increment their counts in subsequent recursive calls to keep track of the number of absences and consecutive lates.\n\n1. If we choose `'P'`, it will not change the total number of absences, but it will reset the number of consecutive lates to zero in our combination.\n2. If we choose `'A'`, it will increase the total number of absences in our combination by one and reset the number of consecutive lates to zero.\n3. If we choose `'L'`, it will not change the total number of absences, but it will increase the number of consecutive lates by one in our combination.\n\n\n```python\ndef eligible_combinations(n, total_absences, consecutive_lates) -> int:\n    # Do not generate further combinations if the combination is not eligible for the award.\n    if total_absences >= 2 or consecutive_lates >= 3: return 0\n    # We have created a combination of length 'n' which is eligible for the award, thus, include it in the count.\n    if n == 0: return 1\n\n    # Choose a character for the current position and make further recursive calls.\n    counts = eligible_combinations(n - 1, total_absences, 0) # Choose 'P'.\n    counts += eligible_combinations(n - 1, total_absences + 1, 0) # Choose 'A'.\n    counts += eligible_combinations(n - 1, total_absences, consecutive_lates + 1) # Choose 'L'.\n    return counts \n```\n\n<br />\n\n**Memoization:**\n\nWe can also see that some of the sub-problems recur; this can be better understood if we draw the recursive call tree; for example, in the image below we would have to compute `eligible_combinations(2, 0, 1)` and `eligible_combinations(2, 0, 0)` many times.\n\n![recursive_tree](../Figures/552/Slide4.jpg)\n\nBy caching the result of each subproblem, we can avoid recalculating previously seen sub-problems, thus improving the time complexity.\n\n> This optimization technique of storing the results of the expensive function calls and returning the cached result when the input occurs again is called memoization.\n\nEach subproblem is defined by three variables `n`, `total_absences`, and `consecutive_lates`.                  \nSo, we will store the subproblem results in a three-dimensional array `memo[n][total_absences][consecutive_lates]`.\n\n\n\n#### Algorithm\n\n1. Initialization:\n    - Create a constant `MOD` equal to `1000000007`.\n    - Create the cache `memo` as a 3D vector.\n2. Define a function `eligible_combinations(n, total_absences, consecutive_lates)`:\n    - If the combination is not eligible for the award (`total_absences>= 2` or `consecutive_lates >= 3`), return `0`.\n    - If we created a combination eligible for award (`n == 0`), return `1`.\n    - If the sub-problem has been solved earlier, then, return the stored result from the cache.\n    - Initialize a variable `count` to `0`.\n    - Recursively call the function for three choices and perform the modular addition of the respective recursive call result with `count`:\n        - Choose `'P'` for the current position: `count = eligible_combinations(n - 1, total_absences, 0)`.\n        - Choose `'A'` for the current position: `count = (count + eligible_combinations(n - 1, total_absences + 1, 0)) % MOD`.\n        - Choose `'L'` for the current position: `count = (count + eligible_combinations(n - 1, total_absences, consecutive_lates + 1)) % MOD`.\n    - Store the result in the cache and return `count`.\n3. In `checkRecord(n)` function:\n    - Initialize an empty cache `memo` with dimensions `(n + 1) x 2 x 3` and fill it with `-1` indicating we have not stored the result of sub-problems (as counts will always be `0` or more).\n    - Return the result given by `eligible_combinations` function with initial parameters `(n, 0, 0)` indicating no absence and no consecutive late count in the initial combination.\n\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/kqRsRkfg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"kqRsRkfg\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n)$  \n    - Our recursive function will only evaluate $n \\times 2 \\times 3$ unique sub-problems due to memoization. \n    - So, this approach will take $O(6 \\cdot n) = O(n)$ time.\n* Space complexity: $O(n)$\n    - We initialized an additional array `memo` of size $n \\times 2 \\times 3$ that takes $O(n)$ space.\n    - The recursive call stack will also take $O(n)$ space in the worst-case.\n    - So, this approach will take $O(6 \\cdot n + n) = O(n)$ space.\n\n\n<br />\n\n---\n\n\n### Approach 2: Bottom-Up Dynamic Programming\n\n#### Intuition  \n\nThe previous recursive dynamic programming approach can also be converted to an iterative dynamic programming approach.                \nIn the iterative dynamic programming (tabulation), we create a dp table, fill in the results of the smaller sub-problems, and solve the larger sub-problems iteratively. \n\nFrom the previous approach, we know that the state of each sub-problem depends on three variables `n`, `total_absences`, and `consecutive_lates`.                  \nTherefore, we will store the results of the sub-problem in a three-dimensional array `dp`, where `dp[len][total_absences][consecutive_lates]` stores the number of combinations of length `len` eligible for the award having `total_absences` `'A'` and `consecutive_lates` `'L'` at the end of the combination.\n\n<br />\n\n**Determining the base case:**\n\nThe simplest case to fill in the table is to store the sub-problem results when the combination length is `0`.\n- `dp[0][0][0] = 1`, as there is only one combination of length `0` with zero `'A'` and zero consecutive `'L'`.\n- All other cases like `dp[0][x][y]` will store `0`, because it's not possible to make a combination of length `0` with any number of `'A'` or `'L'` in it.\n\n<br />\n\n**Generating bigger sub-problem result using a smaller sub-problem:**\n\nWe will iterate on all sub-problems using nested for loops (combination length `len` will go from `0` to `n - 1`, `total_absences` from `0` to `1`, and `consecutive_lates` from `0` to `2`) and try to generate the bigger sub-problem result using the current smaller sub-problem result.\n\nSay we are at the current sub-problem `dp[len][total_absences][consecutive_lates]`, using this sub-problem we will generate results for a bigger sub-problem when we append `'P'`, `'A'`, or `'L'` at the end.\n\n1. If we choose `'P'`:    \n    - We can append `'P'` to all combinations of the current sub-problem, `bigger_subproblem_result = dp[len][total_absences][consecutive_lates]`\n    - Appending `'P'` will increase `len` by `1`, keep the `total_absences` same, and reset `consecutive_lates` to `0`, so we store the result at `dp[len + 1][total_absences][0]`, i.e. `dp[len + 1][total_absences][0] += bigger_subproblem_result` in the table. \n2. If we choose `'A'`:    \n    - We can append `'A'` to all combinations of the current sub-problem if it has `total_absences = 0`, `bigger_subproblem_result = dp[len][total_absences][consecutive_lates]` \n    - If the combinations of the current sub-problem have `total_absences > 0`, then adding one more `'A'` will increase the count of absences to `2` or more and will make the combination invalid, so, there is no need to count these combinations.\n    - Appending `'A'` will increase the `len` and `total_absences` by `1` and reset `consecutive_lates` to `0`, so we store the result at `dp[len + 1][total_absences+ 1][0]`, i.e. `dp[len + 1][total_absences+ 1][0] += bigger_subproblem_result` in the table. \n3. If we choose `'L'`:    \n    - We can append `'L'` to all combinations of the current sub-problem if it has `consecutive_lates = 0 or 1`, `bigger_subproblem_result = dp[len][total_absences][consecutive_lates]`\n    - If the combinations of the current sub-problem have `consecutive_lates > 1`, then adding one more `'L'` will increase the count of consecutive lates to `3` or more and will make the combination invalid, so, there is no need to count these combinations.\n    - Appending `'L'` will increase the `len` and `consecutive_lates` by `1` but keep the `total_absences` same, so we store the result at `dp[len + 1][total_absences][consecutive_lates + 1]`, i.e. `dp[len + 1][total_absences][consecutive_lates + 1] += bigger_subproblem_result` in the table. \n\n<br />\n \n\n**Calculating required result:**\n\nIn the end, to calculate the final result (count of all eligible combinations of length `n`) we will need to sum all the valid combinations of length `n`, thus, counting all the results stored in `dp[n][0 to 1][0 to 2]`.\n\n<br />\n\n#### Algorithm\n\n1. Initialization:\n    - Create a constant `MOD` equal to `1000000007`.\n    - Create the cache `dp` as a 3D vector with dimensions `(n + 1) x 2 x 3` and fill it with `0`.\n2. Set `dp[0][0][0] = 1`.\n3. Iterate over the sub-problems using three nested loops for `len`, `total_absences`, and `consecutive_lates`.\n    - If we choose `'P'`: `dp[len + 1][total_absences][0] = (dp[len + 1][total_absences][0] + dp[len][total_absences][consecutive_lates]) % MOD`\n    - If we choose `'A'` and `total_absences < 1`: `dp[len + 1][total_absences + 1][0] = (dp[len + 1][total_absences + 1][0] + dp[len][total_absences][consecutive_lates]) % MOD`\n    - If we choose `'L'` and `consecutive_lates < 2`: `dp[len + 1][total_absences][consecutive_lates + 1] = (dp[len + 1][total_absences][consecutive_lates + 1] + dp[len][total_absences][consecutive_lates]) % MOD;`\n4. Sum up the `counts` for all combinations of length `n` with different `total_absences` and `consecutive_lates` counts using modular addition with `MOD`.\n5. Return the final `count`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/LJjsiYFN/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"LJjsiYFN\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n)$  \n    - We iterate over $n \\times 2 \\times 3$ sub-problems using nested for loops.\n    - Thus, this approach will take $O(6 \\cdot n) = O(n)$ time.\n* Space complexity: $O(n)$\n    - We initialized an additional array of size $n \\cdot 2 \\cdot 3$.\n    - Thus, this approach will take $O(6 \\cdot n) = O(n)$ space.\n\n\n<br />\n\n---\n\n\n### Approach 3: Bottom-Up Dynamic Programming, Space Optimized\n\n#### Intuition  \n\n> **Note:** The previous approaches will be sufficient during the limited time availability of a real interview setting. Here we offer a more optimized approach based on it, which will also likely appear as a follow-up question.\n\nIn the previous approach, when computing the numbers of combinations of length `len `, we only need the numbers of combinations of length `len - 1`. The shorter combinations of length `len - 2`, `len - 3`, etc. are no longer needed.    \nIt means all other length sub-problem results are kept unnecessarily in the `dp` table.    \n\n\n![dp](../Figures/552/Slide5.jpg)\n\n<br />\n\nThus, instead of keeping one 3-dimensional `dp` array, we can keep two 2-dimensional arrays `dp_curr_state`, and `dp_next_state`.\n\n`dp_curr_state[total_absences][consecutive_lates]` and `dp_next_state[total_absences][consecutive_lates]` will store the number of valid combinations of current length `len` and next length `len + 1`, respectively with `total_absences` `'A'` and `consecutive_lates` `'L'`. The values eligible for the award are `0, 1` for `total_absences` and `0, 1, 2`, for `consecutive_lates`; thus, these 2-dimensional arrays will have size `2 x 3` each.    \n\nUsing the current length `len` combination counts stored in `dp_curr_state` we will compute the next length `len + 1` combination counts and store them in `dp_next_state`. Then, length `len + 1` will become our current length, `dp_next_state` will become `dp_curr_state` and similarly, we will compute the next length `len + 2`  combination counts and continue.\n\n<br />\n\n#### Algorithm\n\n1. Initialization:\n    - Create a constant `MOD` equal to `1000000007`.\n    - Create the two 2-dimensional arrays `dp_curr_state` and `dp_next_state` with dimensions `2 x 3` and fill it with `0`.\n2. Set `dp_curr_state[0][0] = 1`.\n3. Iterate over the sub-problems using a for loop for `len`:\n    - Iterate over the combinations of `total_absences`, and `consecutive_lates` using nested for loops:\n        - If we choose `'P'`: `dp_next_state[total_absences][0] = (dp_next_state[total_absences][0] + dp_curr_state[total_absences][consecutive_lates]) % MOD`\n        - If we choose `'A'` and `total_absences < 1`: `dp_next_state[total_absences + 1][0] = (dp_next_state[total_absences + 1][0] + dpCurrState[total_absences][consecutive_lates]) % MOD;`\n        - If we choose `'L'` and `consecutive_lates < 2`: `dp_next_state[total_absences][consecutive_lates + 1] = (dp_next_state[total_absences][consecutive_lates + 1] + dp_curr_state[total_absences][consecutive_lates]) % MOD`\n    - Set the `dp_curr_state` to `dp_next_state` and reset `dp_next_state` to `0`.\n4. Sum up the `counts` for all combinations of length `n` (`dp_curr_state`) with different `total_absences` and `consecutive_lates` counts using modular addition with `MOD`.\n5. Return the final `count`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/FYFbUVMn/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"FYFbUVMn\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(n)$  \n    - We iterate over $2 \\times 3 \\times n$ states once using the nested for-loops.\n    - Thus, this approach will take $O(6 \\cdot n) = O(n)$ time.\n* Space complexity: $O(1)$\n    - We use two $2 \\times 3$ arrays and a handful of variables. Since the space used is not affected by the size of $n$, we only use constant space in this approach.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkRecord(self, n: int) -> int:\n    kMod = 1_000_000_007\n    # dp[i][j] := length so far w/ i A's and the latest chars are j L's\n    dp = [[0] * 3 for _ in range(2)]\n    dp[0][0] = 1\n\n    for _ in range(n):\n      prev = [A[:] for A in dp]\n\n      # Append P\n      dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod\n\n      # Append L\n      dp[0][1] = prev[0][0]\n\n      # Append L\n      dp[0][2] = prev[0][1]\n\n      # Append A or append P\n      dp[1][0] = (prev[0][0] + prev[0][1] + prev[0][2] +\n                  prev[1][0] + prev[1][1] + prev[1][2]) % kMod\n\n      # Append L\n      dp[1][1] = prev[1][0]\n\n      # Append L\n      dp[1][2] = prev[1][1]\n\n    return (sum(dp[0]) + sum(dp[1])) % kMod",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int checkRecord(int n) {\n    final int kMod = 1_000_000_007;\n    // dp[i][j] := length so far w/ i A's and the latest chars are j L's\n    long[][] dp = new long[2][3];\n    dp[0][0] = 1;\n\n    while (n-- > 0) {\n      long[][] prev = Arrays.stream(dp)\n                          .map((long[] A) -> A.clone())\n                          .toArray((int length) -> new long[length][]);\n\n      // Append P\n      dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod;\n\n      // Append L\n      dp[0][1] = prev[0][0];\n\n      // Append L\n      dp[0][2] = prev[0][1];\n\n      // Append A or append P\n      dp[1][0] =\n          (prev[0][0] + prev[0][1] + prev[0][2] + prev[1][0] + prev[1][1] + prev[1][2]) % kMod;\n\n      // Append L\n      dp[1][1] = prev[1][0];\n\n      // Append L\n      dp[1][2] = prev[1][1];\n    }\n\n    return (int) ((dp[0][0] + dp[0][1] + dp[0][2] + dp[1][0] + dp[1][1] + dp[1][2]) % kMod);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int checkRecord(int n) {\n    constexpr int kMod = 1'000'000'007;\n    // dp[i][j] := length so far w/ i A's and the latest chars are j L's\n    vector<vector<long>> dp(2, vector<long>(3));\n    dp[0][0] = 1;\n\n    while (n--) {\n      const auto prev(dp);\n\n      // Append P\n      dp[0][0] = (prev[0][0] + prev[0][1] + prev[0][2]) % kMod;\n\n      // Append L\n      dp[0][1] = prev[0][0];\n\n      // Append L\n      dp[0][2] = prev[0][1];\n\n      // Append A or append P\n      dp[1][0] = (prev[0][0] + prev[0][1] + prev[0][2] +\n                  prev[1][0] + prev[1][1] + prev[1][2]) % kMod;\n\n      // Append L\n      dp[1][1] = prev[1][0];\n\n      // Append L\n      dp[1][2] = prev[1][1];\n    }\n\n    return accumulate(begin(dp), end(dp), 0, [](int s, vector<long>& row) {\n      return (s + accumulate(begin(row), end(row), 0L)) % kMod;\n    });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/552.html",
    "category": "Algorithms",
    "acceptance_rate": 55.73679793147834,
    "topics": [
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 2326,
    "dislikes": 289,
    "similar_questions": "[{\"title\": \"Student Attendance Record I\", \"titleSlug\": \"student-attendance-record-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"148.1K\", \"totalSubmission\": \"265.7K\", \"totalAcceptedRaw\": 148091, \"totalSubmissionRaw\": 265697, \"acRate\": \"55.7%\"}",
    "title_pt": "Registro de Frequência de Estudante II",
    "description_pt": "<p>Um registro de frequência de um estudante pode ser representado como uma string em que cada caractere significa se o estudante esteve ausente, atrasado ou presente naquele dia. O registro contém apenas os seguintes três caracteres:</p>\n\n<ul>\n\t<li><code>&#39;A&#39;</code>: Ausente.</li>\n\t<li><code>&#39;L&#39;</code>: Atrasado.</li>\n\t<li><code>&#39;P&#39;</code>: Presente.</li>\n</ul>\n\n<p>Qualquer estudante é elegível para um prêmio de frequência se atender <strong>ambos</strong> os seguintes critérios:</p>\n\n<ul>\n\t<li>O estudante esteve ausente (<code>&#39;A&#39;</code>) por <strong>estritamente</strong> menos de 2 dias <strong>no total</strong>.</li>\n\t<li>O estudante <strong>nunca</strong> esteve atrasado (<code>&#39;L&#39;</code>) por 3 ou mais dias <strong>consecutivos</strong>.</li>\n</ul>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>o <strong>número</strong> de possíveis registros de frequência de comprimento</em> <code>n</code><em> que tornam um estudante elegível para um prêmio de frequência. A resposta pode ser muito grande, então retorne-a <strong>modulo</strong> </em><code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 8\n<strong>Explicação:</strong> Há 8 registros com comprimento 2 que são elegíveis para um prêmio:\n&quot;PP&quot;, &quot;AP&quot;, &quot;PA&quot;, &quot;LP&quot;, &quot;PL&quot;, &quot;AL&quot;, &quot;LA&quot;, &quot;LL&quot;\nApenas &quot;AA&quot; não é elegível porque há 2 ausências (precisa haver menos de 2).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 10101\n<strong>Saída:</strong> 183236316\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "553",
    "paidOnly": false,
    "title": "Optimal Division",
    "titleSlug": "optimal-division",
    "url": "https://leetcode.com/problems/optimal-division",
    "description_url": "https://leetcode.com/problems/optimal-division/description/",
    "description": "<p>You are given an integer array <code>nums</code>. The adjacent integers in <code>nums</code> will perform the float division.</p>\n\n<ul>\n\t<li>For example, for <code>nums = [2,3,4]</code>, we will evaluate the expression <code>&quot;2/3/4&quot;</code>.</li>\n</ul>\n\n<p>However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.</p>\n\n<p>Return <em>the corresponding expression that has the maximum value in string format</em>.</p>\n\n<p><strong>Note:</strong> your expression should not contain redundant parenthesis.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1000,100,10,2]\n<strong>Output:</strong> &quot;1000/(100/10/2)&quot;\n<strong>Explanation:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; are redundant since they do not influence the operation priority.\nSo you should return &quot;1000/(100/10/2)&quot;.\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,3,4]\n<strong>Output:</strong> &quot;2/(3/4)&quot;\n<strong>Explanation:</strong> (2/(3/4)) = 8/3 = 2.667\nIt can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>2 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>There is only one optimal division for the given input.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/optimal-division/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Accepted]\n\n**Algorithm**\n\nBrute force of this problem is to divide the list into two parts $$left$$ and $$right$$ and call function for these two parts. We will iterate $$i$$ from $$start$$ to $$end$$ so that $$left=(start,i)$$ and $$right=(i+1,end)$$.\n\n$$left$$ and $$right$$ parts return their maximum and minimum value and corresponding strings.\n\nMinimum value can be found by dividing minimum of left by maximum of right i.e. $$minVal=left.min/right.max$$.\n\nSimilarly,Maximum value can be found by dividing maximum of left value by minimum of right value. i.e. $$maxVal=left.max/right.min$$.\n\nNow, how to add parenthesis? As associativity of division operator is from left to right i.e. by default left most divide should be done first, we need not have to add paranthesis to the left part, but we must add parenthesis to the right part.\n\neg- \"2/(3/4)\" will be formed as leftPart+\"/\"+\"(\"+rightPart+\")\", assuming leftPart is \"2\" and rightPart is\"3/4\".\n\nOne more point, we also don't require parenthesis to right part when it contains single digit.\n\neg- \"2/3\", here left part is \"2\" and right part is \"3\" (contains single digit) . 2/(3) is not valid.\n\n\n<iframe src=\"https://leetcode.com/playground/CAbJyzm4/shared\" frameBorder=\"0\" name=\"CAbJyzm4\" width=\"100%\" height=\"515\"></iframe>\n\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n!)$$. Number of permutations of expression after applying brackets will be in $$O(n!)$$ where $$n$$ is the number of items in the list.\n\n* Space complexity: $$O(n^2)$$. Depth of recursion tree will be $$O(n)$$ and each node contains string of maximum length $$O(n)$$.\n\n---\n### Approach #2 Using Memorization [Accepted]\n\n**Algorithm**\n\nIn the above approach we called optimal function recursively for ever $$start$$ and $$end$$. We can notice that there are many redundant calls in the above approach, we can reduce these calls by using memorization to store the result of different function calls. Here, $$memo$$ array is used for this purpose.\n\n<iframe src=\"https://leetcode.com/playground/xFgr7Cpd/shared\" frameBorder=\"0\" name=\"xFgr7Cpd\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. $$memo$$ array of size $$n^2$$ is filled and filling of each cell of the $$memo$$ array takes $$O(n)$$ time.\n\n* Space complexity : $$O(n^3)$$. $$memo$$ array of size $$n^2$$ where each cell of array contains string of length $$O(n)$$.\n\n---\n### Approach #3 Using some Math [Accepted]\n\n**Algorithm**\n\nUsing some simple math we can find the easy solution of this problem. Consider the input in the form of [a,b,c,d], now we have to set priority of\noperations to maximize a/b/c/d. We know that to maximize fraction $$p/q$$, $$q$$(denominator) should be minimized. So, to maximize $$a/b/c/d$$  we have to first minimize b/c/d. Now our objective turns to minimize the expression b/c/d.\n\nThere are two possible combinations of this expression, b/(c/d) and (b/c)/d.\n```\nb/(c/d)        (b/c)/d = b/c/d\n(b*d)/c        b/(d*c)\nd/c            1/(d*c)\n```\n\nObviously, $$d/c > 1/(d*c)$$ for $$d>1$$.\n\nYou can see that second combination will always be less than first one for numbers greater than $$1$$. So, the answer will be a/(b/c/d).\nSimilarly for expression like a/b/c/d/e/f... answer will be a/(b/c/d/e/f...).\n\n\n\n<iframe src=\"https://leetcode.com/playground/wUbJEUre/shared\" frameBorder=\"0\" name=\"wUbJEUre\" width=\"100%\" height=\"309\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Single loop to traverse $$nums$$ array.\n\n* Space complexity : $$O(n)$$. $$res$$ variable is used to store the result.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def optimalDivision(self, nums: List[int]) -> str:\n    ans = str(nums[0])\n\n    if len(nums) == 1:\n      return ans\n    if len(nums) == 2:\n      return ans + '/' + str(nums[1])\n\n    ans += '/(' + str(nums[1])\n    for i in range(2, len(nums)):\n      ans += '/' + str(nums[i])\n    ans += ')'\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String optimalDivision(int[] nums) {\n    StringBuilder sb = new StringBuilder(String.valueOf(nums[0]));\n\n    if (nums.length == 1)\n      return sb.toString();\n    if (nums.length == 2)\n      return sb.append('/').append(nums[1]).toString();\n\n    sb.append(\"/(\").append(nums[1]);\n    for (int i = 2; i < nums.length; ++i)\n      sb.append('/').append(nums[i]);\n    sb.append(')');\n    return sb.toString();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string optimalDivision(vector<int>& nums) {\n    string ans = to_string(nums[0]);\n\n    if (nums.size() == 1)\n      return ans;\n    if (nums.size() == 2)\n      return ans + \"/\" + to_string(nums[1]);\n\n    ans += \"/(\" + to_string(nums[1]);\n    for (int i = 2; i < nums.size(); ++i)\n      ans += \"/\" + to_string(nums[i]);\n    ans += \")\";\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/553.html",
    "category": "Algorithms",
    "acceptance_rate": 61.624805361857696,
    "topics": [
      "Array",
      "Math",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 393,
    "dislikes": 1620,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"45.5K\", \"totalSubmission\": \"73.9K\", \"totalAcceptedRaw\": 45513, \"totalSubmissionRaw\": 73855, \"acRate\": \"61.6%\"}",
    "title_pt": "Divisão Ótima",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code>. Os inteiros adjacentes em <code>nums</code> realizarão a divisão de ponto flutuante.</p>\n\n<ul>\n\t<li>Por exemplo, para <code>nums = [2,3,4]</code>, avaliaremos a expressão <code>&quot;2/3/4&quot;</code>.</li>\n</ul>\n\n<p>No entanto, você pode adicionar qualquer número de parênteses em qualquer posição para alterar a prioridade das operações. Você quer adicionar esses parênteses de forma que o valor da expressão após a avaliação seja máximo.</p>\n\n<p>Retorne <em>a expressão correspondente que tem o valor máximo no formato de string</em>.</p>\n\n<p><strong>Nota:</strong> sua expressão não deve conter parênteses redundantes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1000,100,10,2]\n<strong>Saída:</strong> &quot;1000/(100/10/2)&quot;\n<strong>Explicação:</strong> 1000/(100/10/2) = 1000/((100/10)/2) = 200\nNo entanto, os parênteses em negrito em &quot;1000/(<strong>(</strong>100/10<strong>)</strong>/2)&quot; são redundantes, pois não influenciam a prioridade da operação.\nPortanto, você deve retornar &quot;1000/(100/10/2)&quot;.\nOutros casos:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,3,4]\n<strong>Saída:</strong> &quot;2/(3/4)&quot;\n<strong>Explicação:</strong> (2/(3/4)) = 8/3 = 2.667\nPode-se mostrar que, após tentar todas as possibilidades, não podemos obter uma expressão com avaliação maior que 2.667\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10</code></li>\n\t<li><code>2 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>Há apenas uma divisão ótima para a entrada dada.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "554",
    "paidOnly": false,
    "title": "Brick Wall",
    "titleSlug": "brick-wall",
    "url": "https://leetcode.com/problems/brick-wall",
    "description_url": "https://leetcode.com/problems/brick-wall/description/",
    "description": "<p>There is a rectangular brick wall in front of you with <code>n</code> rows of bricks. The <code>i<sup>th</sup></code> row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.</p>\n\n<p>Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</p>\n\n<p>Given the 2D array <code>wall</code> that contains the information about the wall, return <em>the minimum number of crossed bricks after drawing such a vertical line</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2025/01/17/a.png\" style=\"width: 400px; height: 384px;\" />\n<pre>\n<strong>Input:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> wall = [[1],[1],[1]]\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == wall.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>sum(wall[i])</code> is the same for each row <code>i</code>.</li>\n\t<li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/brick-wall/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def leastBricks(self, wall: List[List[int]]) -> int:\n    maxFreq = 0\n    count = defaultdict(int)\n\n    for row in wall:\n      prefix = 0\n      for i in range(len(row) - 1):\n        prefix += row[i]\n        count[prefix] += 1\n        maxFreq = max(maxFreq, count[prefix])\n\n    return len(wall) - maxFreq",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int leastBricks(List<List<Integer>> wall) {\n    int maxFreq = 0;\n    Map<Integer, Integer> count = new HashMap<>();\n\n    for (List<Integer> row : wall) {\n      int prefix = 0;\n      for (int i = 0; i < row.size() - 1; ++i) {\n        prefix += row.get(i);\n        count.put(prefix, count.getOrDefault(prefix, 0) + 1);\n        maxFreq = Math.max(maxFreq, count.get(prefix));\n      }\n    }\n\n    return wall.size() - maxFreq;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int leastBricks(vector<vector<int>>& wall) {\n    int maxCount = 0;\n    unordered_map<int, int> count;\n\n    for (const vector<int>& row : wall) {\n      int prefix = 0;\n      for (int i = 0; i < row.size() - 1; ++i) {\n        prefix += row[i];\n        maxCount = max(maxCount, ++count[prefix]);\n      }\n    }\n\n    return wall.size() - maxCount;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/554.html",
    "category": "Algorithms",
    "acceptance_rate": 55.825798877014265,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [],
    "likes": 2603,
    "dislikes": 181,
    "similar_questions": "[{\"title\": \"Number of Ways to Build Sturdy Brick Wall\", \"titleSlug\": \"number-of-ways-to-build-sturdy-brick-wall\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"157.4K\", \"totalSubmission\": \"281.9K\", \"totalAcceptedRaw\": 157388, \"totalSubmissionRaw\": 281926, \"acRate\": \"55.8%\"}",
    "title_pt": "Parede de Tijolos",
    "description_pt": "<p>Há uma parede retangular de tijolos à sua frente com <code>n</code> linhas de tijolos. A <code>i<sup>th</sup></code> linha tem algum número de tijolos, todos com a mesma altura (isto é, uma unidade), mas eles podem ter larguras diferentes. A largura total de cada linha é a mesma.</p>\n\n<p>Desenhe uma linha vertical do topo até a base e cruze o menor número de tijolos. Se sua linha passar pela borda de um tijolo, então o tijolo não é considerado como cruzado. Você não pode desenhar uma linha exatamente ao longo de uma das duas bordas verticais da parede, caso em que a linha obviamente não cruzaria nenhum tijolo.</p>\n\n<p>Dado o array bidimensional <code>wall</code> que contém as informações sobre a parede, retorne <em>o número mínimo de tijolos cruzados após desenhar essa linha vertical</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2025/01/17/a.png\" style=\"width: 400px; height: 384px;\" />\n<pre>\n<strong>Entrada:</strong> wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> wall = [[1],[1],[1]]\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == wall.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= wall[i].length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= sum(wall[i].length) &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>sum(wall[i])</code> é o mesmo para cada linha <code>i</code>.</li>\n\t<li><code>1 &lt;= wall[i][j] &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "556",
    "paidOnly": false,
    "title": "Next Greater Element III",
    "titleSlug": "next-greater-element-iii",
    "url": "https://leetcode.com/problems/next-greater-element-iii",
    "description_url": "https://leetcode.com/problems/next-greater-element-iii/description/",
    "description": "<p>Given a positive integer <code>n</code>, find <em>the smallest integer which has exactly the same digits existing in the integer</em> <code>n</code> <em>and is greater in value than</em> <code>n</code>. If no such positive integer exists, return <code>-1</code>.</p>\n\n<p><strong>Note</strong> that the returned integer should fit in <strong>32-bit integer</strong>, if there is a valid answer but it does not fit in <strong>32-bit integer</strong>, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> n = 12\n<strong>Output:</strong> 21\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> n = 21\n<strong>Output:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/next-greater-element-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nextGreaterElement(self, n: int) -> int:\n    def nextPermutation(s: List[chr]) -> str:\n      i = len(s) - 2\n      while i >= 0:\n        if s[i] < s[i + 1]:\n          break\n        i -= 1\n\n      if i >= 0:\n        for j in range(len(s) - 1, i, -1):\n          if s[j] > s[i]:\n            break\n        s[i], s[j] = s[j], s[i]\n\n      reverse(s, i + 1, len(s) - 1)\n      return ''.join(s)\n\n    def reverse(s: List[chr], l: int, r: int):\n      while l < r:\n        s[l], s[r] = s[r], s[l]\n        l += 1\n        r -= 1\n\n    s = nextPermutation(list(str(n)))\n    ans = int(s)\n    return -1 if ans > 2**31 - 1 or ans <= n else ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int nextGreaterElement(int n) {\n    final String s = nextPermutation(String.valueOf(n).toCharArray());\n    final long ans = Long.parseLong(s);\n    return ans > Integer.MAX_VALUE || ans <= (long) n ? -1 : (int) ans;\n  }\n\n  // Very simliar to 31. Next Permutation\n  private String nextPermutation(char[] s) {\n    final int n = s.length;\n\n    int i;\n    for (i = n - 2; i >= 0; --i)\n      if (s[i] < s[i + 1])\n        break;\n\n    if (i >= 0) {\n      for (int j = n - 1; j > i; --j)\n        if (s[j] > s[i]) {\n          swap(s, i, j);\n          break;\n        }\n    }\n\n    reverse(s, i + 1, n - 1);\n    return new String(s);\n  }\n\n  private void reverse(char[] s, int l, int r) {\n    while (l < r)\n      swap(s, l++, r--);\n  }\n\n  private void swap(char[] s, int i, int j) {\n    final char temp = s[i];\n    s[i] = s[j];\n    s[j] = temp;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int nextGreaterElement(int n) {\n    const string& s = nextPermutation(to_string(n));\n    const long ans = stol(s);\n    return ans > INT_MAX || ans <= n ? -1 : ans;\n  }\n\n private:\n  // Very simliar to 31. Next Permutation\n  string nextPermutation(string s) {\n    const int n = s.length();\n\n    int i;\n    for (i = n - 2; i >= 0; --i)\n      if (s[i] < s[i + 1])\n        break;\n\n    if (i >= 0) {\n      for (int j = n - 1; j > i; --j)\n        if (s[j] > s[i]) {\n          swap(s[i], s[j]);\n          break;\n        }\n    }\n\n    reverse(s, i + 1, n - 1);\n    return s;\n  }\n\n  void reverse(string& s, int l, int r) {\n    while (l < r)\n      swap(s[l++], s[r--]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/556.html",
    "category": "Algorithms",
    "acceptance_rate": 34.51875310836844,
    "topics": [
      "Math",
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 3812,
    "dislikes": 485,
    "similar_questions": "[{\"title\": \"Next Greater Element I\", \"titleSlug\": \"next-greater-element-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element II\", \"titleSlug\": \"next-greater-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Next Palindrome Using Same Digits\", \"titleSlug\": \"next-palindrome-using-same-digits\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"181.2K\", \"totalSubmission\": \"524.8K\", \"totalAcceptedRaw\": 181152, \"totalSubmissionRaw\": 524788, \"acRate\": \"34.5%\"}",
    "title_pt": "Próximo Elemento Maior III",
    "description_pt": "<p>Dado um inteiro positivo <code>n</code>, encontre <em>o menor inteiro que possui exatamente os mesmos dígitos existentes no inteiro</em> <code>n</code> <em>e é maior em valor que</em> <code>n</code>. Se nenhum inteiro positivo כזה existir, retorne <code>-1</code>.</p>\n\n<p><strong>Nota</strong> que o inteiro retornado deve caber em um <strong>inteiro de 32 bits</strong>; se houver uma resposta válida, mas ela não couber em um <strong>inteiro de 32 bits</strong>, retorne <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> n = 12\n<strong>Saída:</strong> 21\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> n = 21\n<strong>Saída:</strong> -1\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "557",
    "paidOnly": false,
    "title": "Reverse Words in a String III",
    "titleSlug": "reverse-words-in-a-string-iii",
    "url": "https://leetcode.com/problems/reverse-words-in-a-string-iii",
    "description_url": "https://leetcode.com/problems/reverse-words-in-a-string-iii/description/",
    "description": "<p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Let&#39;s take LeetCode contest&quot;\n<strong>Output:</strong> &quot;s&#39;teL ekat edoCteeL tsetnoc&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Mr Ding&quot;\n<strong>Output:</strong> &quot;rM gniD&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>\n\t<li><code>s</code> does not contain any leading or trailing spaces.</li>\n\t<li>There is <strong>at least one</strong> word in <code>s</code>.</li>\n\t<li>All the words in <code>s</code> are separated by a single space.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reverse-words-in-a-string-iii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Overview\n\nThe problem is a variation of similar reverse string problems, [Reverse Words In a String](https://leetcode.com/problems/reverse-words-in-a-string/) and [Reverse Words In String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/).\n\nIn the first one, we had to reverse all characters, and in the second variation, we had to reverse the order of words. In this problem, we have to reverse the characters of each word in the sentences.\n\n---\n### Approach 1: Traverse and Reverse each character one by one\n\n**Intuition**\n\nTo solve the problem let's look at the example carefully,\n```\nInput: \"Let's take LeetCode contest\"`\n\nOutput: \"s'teL ekat edoCteeL tsetnoc\"\n```\nThere are a few observations here,\n- The characters of each word in the string are reversed, but the order of words remains the same.\n\n   For example, in the input, the word `Let's` is the first word in the string. In the output, the characters in the word `Let's` are reversed to `s'teL`. But it is still at the first position in the string.\nSimilarly the second word `take` is reversed as `ekat` and placed at the same second position in the output string.\n\n\n- The words in the string are separated by a space character. So we can say that to build the output string, we must extract and reverse the substring between 2 consecutive space characters.\n\n  ![Second Observation Illustration](../Figures/557/second_observation.png)\n\nUsing this intuition, let's understand how to implement this problem.\n\n**Algorithm**\n\nBy analyzing the above two key observations, we can derive the following algorithm,\n-  Find the starting and ending position of each word in the string.\n\n   As a space character is a separator for each word, we are finding the substrings having a space character before its first character and after its last character.\n   > Note: Take care of 2 edge cases here, the first word does not have a space before its first character. Similarly, the last word does not have a space after its last character.\n\n- For each identified word, reverse the characters of the word one by one.\n\n*Steps*\n\n Traverse the string from left to right, starting from $$0^{th}$$ to $$n^{th}$$ index. As we traverse, the pointer `strIndex` tracks each character.\nThe implementation can be divided into 2 steps,\n\n1. Find the start and end index of every word\n\n    - Traverse over the string until the current pointer `strIndex` points to a space character.\n\n    - As `strIndex` points to the space character, the index `strIndex - 1` points to the last character of the current word.\n\n      ![Current Pointer Traversal](../Figures/557/current_pointer_traversal.png)\n\n   - Let's understand how to find the first character of the word,\n     - For the first word, its first character is always the first character of the string.\n     - For the remaining words, the first character would be the character after the last space character.\n\n        Thus, to mark the start of the current character, we must keep track of the last found space character. Let's use a variable `lastSpaceIndex`. The variable will be initialized to `-1`  and updated every time we find the next space character.\n\n       ![Mark Start And End Index](../Figures/557/start_and_end_index.png)\n\n        The first character of the current word is thus `lastSpaceIndex + 1`.\n\n2. Reverse the characters within the word\n\n   -  Now that we have the first and last index of the current word, we have to reverse the current word and append it to the result string.\n\n   -  To reverse the current word, we can traverse it in reverse order i.e start from the end index `strIndex - 1` to the first index i.e `lastSpaceIndex + 1`, appending each character one by one to the result string.\n\n   - To separate the current word from the next, append a space character (\" \") at the end after the reverse operation. However, for the last word, this step is skipped.\n\nRepeat 1 and 2 for all the words in the string.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/WEGNG2Mq/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"WEGNG2Mq\"></iframe>\n\n**Complexity Analysis**\n\nLet $$N$$ be the length of input string `s`.\n\nTime Complexity: $$\\mathcal{O}(N)$$ Every character in the string is traversed twice. First, to find the end of the current word, and second to reverse the word and append it to the result. Thus the time complexity is, $$\\mathcal{O}(N + N) = \\mathcal{O}(N)$$.\n\nSpace Complexity: $$\\mathcal{O}(1)$$ We use constant extra space to track the last space index. You could also argue that we are using $$O(n)$$ space to build the output string (we normally don't count the output as part of the space complexity, but in this case we are temporarily using some space to build it).\n\n---\n### Approach 2: Using Two Pointers\n\n**Intuition**\n\nIn the previous approach, the words were reversed by copying every character into another string one by one in reverse order. This operation takes $$\\mathcal{O}(N)$$ time, where `N` is the length of the word.\n\nHowever, there is another optimal approach to reverse the string in $$\\mathcal{O}(N/2)$$ time in place using two pointer approach.  \n\nIn this solution, we will traverse the string and find every word's start and end index. Then, we will reverse each word using the two-pointer approach.\n\n*Approach to reverse a string using a two-pointer approach*\n\n1. Find the start and end index of every word given by `startIndex` and `endIndex`.\n2. Swap the characters in the word pointed by `startIndex` and `endIndex`.\n3. Increment `startIndex` by 1 and decrement `endIndex` by 1.\n4. While `startIndex < endIndex`, repeat steps 2 and 3.\n\n     ![Two Pointer Approach To Reverse String](../Figures/557/2_pointer_approach.png)\n\nHere's the code snippet for reversing the string stored in character array `chArray` using two pointer approach.\n\n```java\nwhile (startIndex < endIndex) {\n        char temp = chArray[startIndex];\n        chArray[startIndex] = chArray[endIndex];\n        chArray[endIndex] = temp;\n        startIndex++;\n        endIndex--;\n}\n```\n\n**Algorithm**\n\n- The variable `lastSpaceIndex` stores the index of space character last found. Initialize its value to `-1`.\n\n- Traverse over each character of the string from $$0^{th}$$ index to $$n^{th}$$ index using pointer `strIndex`.\n- As `strIndex` points to a space character, mark the start and end index of the current word in the variables `startIndex` and `endIndex` as,\n\n  - The `startIndex` of the current word is the value of `lastSpaceIndex + 1`.\n  - The `endIndex` of the current word is the value of `strIndex - 1`.\n\n- Reverse the characters in the current word using two pointer approach.\n\n- Update the `lastSpaceIndex` to the value of `strIndex` i.e the index of current space character. The next iteration will refer to this variable to identify the start position of the next word.\n\n-  Repeat the process for all the words in the string.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/Lue6Jm4Q/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"Lue6Jm4Q\"></iframe>\n\n**Complexity Analysis**\n\nLet $$N$$ be the length of string `s`.\n* Time Complexity: $$\\mathcal{O}(N)$$ The outer loop iterates over $$\\text{N}$$ characters to find the `start` and `end` index of every word. The algorithm to reverse the word also iterates $$\\text{N}$$ times to perform $$\\text{N/2}$$ swaps. Thus, the time complexity is $$\\mathcal{O}(N + N) = {O}(N)$$.\n\n* Space Complexity: $$\\mathcal{O}(1)$$ We use constant extra space to track the last space index. You could also argue that we are using $$O(n)$$ space to build the output string (we normally don't count the output as part of the space complexity, but in this case we are temporarily using some space to build it).",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String reverseWords(String s) {\n    StringBuilder sb = new StringBuilder(s);\n    int i = 0;\n    int j = 0;\n\n    while (i < sb.length()) {\n      while (i < j || i < sb.length() && sb.charAt(i) == ' ')\n        ++i;\n      while (j < i || j < sb.length() && sb.charAt(j) != ' ')\n        ++j;\n      reverse(sb, i, j - 1);\n    }\n\n    return sb.toString();\n  }\n\n  private void reverse(StringBuilder sb, int l, int r) {\n    while (l < r) {\n      final char temp = sb.charAt(l);\n      sb.setCharAt(l++, sb.charAt(r));\n      sb.setCharAt(r--, temp);\n    }\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string reverseWords(string s) {\n    int i = 0;\n    int j = 0;\n\n    while (i < s.length()) {\n      while (i < j || i < s.length() && s[i] == ' ')\n        ++i;\n      while (j < i || j < s.length() && s[j] != ' ')\n        ++j;\n      reverse(begin(s) + i, begin(s) + j);\n    }\n\n    return s;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/557.html",
    "category": "Algorithms",
    "acceptance_rate": 83.62189730709439,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [],
    "likes": 6054,
    "dislikes": 252,
    "similar_questions": "[{\"title\": \"Reverse String II\", \"titleSlug\": \"reverse-string-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 1011789, \"totalSubmissionRaw\": 1209957, \"acRate\": \"83.6%\"}",
    "title_pt": "Inverter as Palavras em uma String III",
    "description_pt": "<p>Dada uma string <code>s</code>, inverta a ordem dos caracteres em cada palavra dentro de uma frase, preservando ainda assim os espaços em branco e a ordem inicial das palavras.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Let&#39;s take LeetCode contest&quot;\n<strong>Saída:</strong> &quot;s&#39;teL ekat edoCteeL tsetnoc&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Mr Ding&quot;\n<strong>Saída:</strong> &quot;rM gniD&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>s</code> contém caracteres ASCII <strong>imprimíveis</strong>.</li>\n\t<li><code>s</code> não contém espaços no início nem no fim.</li>\n\t<li>Há <strong>pelo menos uma</strong> palavra em <code>s</code>.</li>\n\t<li>Todas as palavras em <code>s</code> são separadas por um único espaço.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "558",
    "paidOnly": false,
    "title": "Logical OR of Two Binary Grids Represented as Quad-Trees",
    "titleSlug": "logical-or-of-two-binary-grids-represented-as-quad-trees",
    "url": "https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees",
    "description_url": "https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/description/",
    "description": "<p>A Binary Matrix is a matrix in which all the elements are either <strong>0</strong> or <strong>1</strong>.</p>\n\n<p>Given <code>quadTree1</code> and <code>quadTree2</code>. <code>quadTree1</code> represents a <code>n * n</code> binary matrix and <code>quadTree2</code> represents another <code>n * n</code> binary matrix.</p>\n\n<p>Return <em>a Quad-Tree</em> representing the <code>n * n</code> binary matrix which is the result of <strong>logical bitwise OR</strong> of the two binary matrixes represented by <code>quadTree1</code> and <code>quadTree2</code>.</p>\n\n<p>Notice that you can assign the value of a node to <strong>True</strong> or <strong>False</strong> when <code>isLeaf</code> is <strong>False</strong>, and both are <strong>accepted</strong> in the answer.</p>\n\n<p>A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:</p>\n\n<ul>\n\t<li><code>val</code>: True if the node represents a grid of 1&#39;s or False if the node represents a grid of 0&#39;s.</li>\n\t<li><code>isLeaf</code>: True if the node is leaf node on the tree or False if the node has the four children.</li>\n</ul>\n\n<pre>\nclass Node {\n    public boolean val;\n    public boolean isLeaf;\n    public Node topLeft;\n    public Node topRight;\n    public Node bottomLeft;\n    public Node bottomRight;\n}</pre>\n\n<p>We can construct a Quad-Tree from a two-dimensional area using the following steps:</p>\n\n<ol>\n\t<li>If the current grid has the same value (i.e all <code>1&#39;s</code> or all <code>0&#39;s</code>) set <code>isLeaf</code> True and set <code>val</code> to the value of the grid and set the four children to Null and stop.</li>\n\t<li>If the current grid has different values, set <code>isLeaf</code> to False and set <code>val</code> to any value and divide the current grid into four sub-grids as shown in the photo.</li>\n\t<li>Recurse for each of the children with the proper sub-grid.</li>\n</ol>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/new_top.png\" style=\"width: 777px; height: 181px;\" />\n<p>If you want to know more about the Quad-Tree, you can refer to the <a href=\"https://en.wikipedia.org/wiki/Quadtree\">wiki</a>.</p>\n\n<p><strong>Quad-Tree format:</strong></p>\n\n<p>The input/output represents the serialized format of a Quad-Tree using level order traversal, where <code>null</code> signifies a path terminator where no node exists below.</p>\n\n<p>It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list <code>[isLeaf, val]</code>.</p>\n\n<p>If the value of <code>isLeaf</code> or <code>val</code> is True we represent it as <strong>1</strong> in the list <code>[isLeaf, val]</code> and if the value of <code>isLeaf</code> or <code>val</code> is False we represent it as <strong>0</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qt1.png\" style=\"width: 550px; height: 196px;\" /> <img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qt2.png\" style=\"width: 550px; height: 278px;\" />\n<pre>\n<strong>Input:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]\n, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\n<strong>Output:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]\n<strong>Explanation:</strong> quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.\nIf we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.\nNotice that the binary matrices shown are only for illustration, you don&#39;t have to construct the binary matrix to get the result tree.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qtr.png\" style=\"width: 777px; height: 222px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]\n<strong>Output:</strong> [[1,0]]\n<strong>Explanation:</strong> Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.\nThe resulting matrix is of size 1*1 with also zero.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>quadTree1</code> and <code>quadTree2</code> are both <strong>valid</strong> Quad-Trees each representing a <code>n * n</code> grid.</li>\n\t<li><code>n == 2<sup>x</sup></code> where <code>0 &lt;= x &lt;= 9</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Node intersect(Node quadTree1, Node quadTree2) {\n    if (quadTree1.isLeaf)\n      return quadTree1.val ? quadTree1 : quadTree2;\n    if (quadTree2.isLeaf)\n      return quadTree2.val ? quadTree2 : quadTree1;\n\n    Node topLeft = intersect(quadTree1.topLeft, quadTree2.topLeft);\n    Node topRight = intersect(quadTree1.topRight, quadTree2.topRight);\n    Node bottomLeft = intersect(quadTree1.bottomLeft, quadTree2.bottomLeft);\n    Node bottomRight = intersect(quadTree1.bottomRight, quadTree2.bottomRight);\n\n    if (topLeft.val == topRight.val &&\n        topLeft.val == bottomLeft.val &&\n        topLeft.val == bottomRight.val &&\n        topLeft.isLeaf && topRight.isLeaf &&\n        bottomLeft.isLeaf && bottomRight.isLeaf)\n      return new Node(topLeft.val, true);\n    return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Node* intersect(Node* quadTree1, Node* quadTree2) {\n    if (quadTree1->isLeaf)\n      return quadTree1->val ? quadTree1 : quadTree2;\n    if (quadTree2->isLeaf)\n      return quadTree2->val ? quadTree2 : quadTree1;\n\n    Node* topLeft = intersect(quadTree1->topLeft, quadTree2->topLeft);\n    Node* topRight = intersect(quadTree1->topRight, quadTree2->topRight);\n    Node* bottomLeft = intersect(quadTree1->bottomLeft, quadTree2->bottomLeft);\n    Node* bottomRight = intersect(quadTree1->bottomRight, quadTree2->bottomRight);\n\n    if (topLeft->val == topRight->val &&\n        topLeft->val == bottomLeft->val &&\n        topLeft->val == bottomRight->val &&\n        topLeft->isLeaf && topRight->isLeaf &&\n        bottomLeft->isLeaf && bottomRight->isLeaf)\n      return new Node(topLeft->val, true);\n    return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/558.html",
    "category": "Algorithms",
    "acceptance_rate": 50.42221693625118,
    "topics": [
      "Divide and Conquer",
      "Tree"
    ],
    "hints": [],
    "likes": 197,
    "dislikes": 475,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"17K\", \"totalSubmission\": \"33.6K\", \"totalAcceptedRaw\": 16958, \"totalSubmissionRaw\": 33632, \"acRate\": \"50.4%\"}",
    "title_pt": "OU Lógico de Dois Grids Binários Representados como Quad-Trees",
    "description_pt": "<p>Uma Matriz Binária é uma matriz na qual todos os elementos são ou <strong>0</strong> ou <strong>1</strong>.</p>\n\n<p>Dadas <code>quadTree1</code> e <code>quadTree2</code>. <code>quadTree1</code> representa uma matriz binária de <code>n * n</code> e <code>quadTree2</code> representa outra matriz binária de <code>n * n</code>.</p>\n\n<p>Retorne <em>uma Quad-Tree</em> que represente a matriz binária de <code>n * n</code> que é o resultado do <strong>OU bit a bit lógico</strong> das duas matrizes binárias representadas por <code>quadTree1</code> e <code>quadTree2</code>.</p>\n\n<p>Observe que você pode atribuir o valor de um nó para <strong>True</strong> ou <strong>False</strong> quando <code>isLeaf</code> for <strong>False</strong>, e ambos são <strong>aceitos</strong> na resposta.</p>\n\n<p>Uma Quad-Tree é uma estrutura de dados em árvore na qual cada nó interno tem exatamente quatro filhos. Além disso, cada nó tem dois atributos:</p>\n\n<ul>\n\t<li><code>val</code>: True se o nó representa um grid de 1&#39;s ou False se o nó representa um grid de 0&#39;s.</li>\n\t<li><code>isLeaf</code>: True se o nó for um nó folha na árvore ou False se o nó tiver os quatro filhos.</li>\n</ul>\n\n<pre>\nclass Node {\n    public boolean val;\n    public boolean isLeaf;\n    public Node topLeft;\n    public Node topRight;\n    public Node bottomLeft;\n    public Node bottomRight;\n}</pre>\n\n<p>Podemos construir uma Quad-Tree a partir de uma área bidimensional usando os seguintes passos:</p>\n\n<ol>\n\t<li>Se o grid atual tiver o mesmo valor (ou seja, todos <code>1&#39;s</code> ou todos <code>0&#39;s</code>) defina <code>isLeaf</code> como True e defina <code>val</code> para o valor do grid e defina os quatro filhos como Null e pare.</li>\n\t<li>Se o grid atual tiver valores diferentes, defina <code>isLeaf</code> como False e defina <code>val</code> para qualquer valor e divida o grid atual em quatro subgrids, como mostrado na figura.</li>\n\t<li>Recursione para cada um dos filhos com o subgrid apropriado.</li>\n</ol>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/new_top.png\" style=\"width: 777px; height: 181px;\" />\n<p>Se você quiser saber mais sobre a Quad-Tree, pode consultar a <a href=\"https://en.wikipedia.org/wiki/Quadtree\">wiki</a>.</p>\n\n<p><strong>Formato da Quad-Tree:</strong></p>\n\n<p>A entrada/saída representa o formato serializado de uma Quad-Tree usando travessia em ordem de nível, onde <code>null</code> significa um terminador de caminho onde nenhum nó existe abaixo.</p>\n\n<p>Ela é muito semelhante à serialização da árvore binária. A única diferença é que o nó é representado como uma lista <code>[isLeaf, val]</code>.</p>\n\n<p>Se o valor de <code>isLeaf</code> ou <code>val</code> for True, nós o representamos como <strong>1</strong> na lista <code>[isLeaf, val]</code> e se o valor de <code>isLeaf</code> ou <code>val</code> for False, nós o representamos como <strong>0</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qt1.png\" style=\"width: 550px; height: 196px;\" /> <img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qt2.png\" style=\"width: 550px; height: 278px;\" />\n<pre>\n<strong>Entrada:</strong> quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]\n, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\n<strong>Saída:</strong> [[0,0],[1,1],[1,1],[1,1],[1,0]]\n<strong>Explicação:</strong> quadTree1 e quadTree2 são mostradas acima. Você pode ver a matriz binária que é representada por cada Quad-Tree.\nSe aplicarmos o OU bit a bit lógico sobre as duas matrizes binárias, obtemos a matriz binária abaixo, que é representada pela Quad-Tree resultante.\nObserve que as matrizes binárias mostradas são apenas para ilustração, você não precisa construir a matriz binária para obter a árvore resultante.\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/02/11/qtr.png\" style=\"width: 777px; height: 222px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> quadTree1 = [[1,0]], quadTree2 = [[1,0]]\n<strong>Saída:</strong> [[1,0]]\n<strong>Explicação:</strong> Cada árvore representa uma matriz binária de tamanho 1*1. Cada matriz contém apenas zero.\nA matriz resultante tem tamanho 1*1 e também contém zero.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>quadTree1</code> e <code>quadTree2</code> são ambas Quad-Trees <strong>válidas</strong>, cada uma representando um grid de <code>n * n</code>.</li>\n\t<li><code>n == 2<sup>x</sup></code> onde <code>0 &lt;= x &lt;= 9</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "559",
    "paidOnly": false,
    "title": "Maximum Depth of N-ary Tree",
    "titleSlug": "maximum-depth-of-n-ary-tree",
    "url": "https://leetcode.com/problems/maximum-depth-of-n-ary-tree",
    "description_url": "https://leetcode.com/problems/maximum-depth-of-n-ary-tree/description/",
    "description": "<p>Given a n-ary tree, find its maximum depth.</p>\n\n<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>\n\n<p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Output:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Output:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-depth-of-n-ary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxDepth(self, root: 'Node') -> int:\n    if not root:\n      return 0\n    if not root.children:\n      return 1\n    return 1 + max(self.maxDepth(child) for child in root.children)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxDepth(Node root) {\n    if (root == null)\n      return 0;\n\n    int ans = 0;\n\n    for (Node child : root.children)\n      ans = Math.max(ans, maxDepth(child));\n\n    return 1 + ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxDepth(Node* root) {\n    if (root == nullptr)\n      return 0;\n\n    int ans = 0;\n\n    for (Node* child : root->children)\n      ans = max(ans, maxDepth(child));\n\n    return 1 + ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/559.html",
    "category": "Algorithms",
    "acceptance_rate": 72.86206386921477,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 2823,
    "dislikes": 91,
    "similar_questions": "[{\"title\": \"Maximum Depth of Binary Tree\", \"titleSlug\": \"maximum-depth-of-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"The Time When the Network Becomes Idle\", \"titleSlug\": \"the-time-when-the-network-becomes-idle\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Good Nodes\", \"titleSlug\": \"count-the-number-of-good-nodes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"320.4K\", \"totalSubmission\": \"439.8K\", \"totalAcceptedRaw\": 320449, \"totalSubmissionRaw\": 439803, \"acRate\": \"72.9%\"}",
    "title_pt": "Profundidade Máxima de uma Árvore N-ária",
    "description_pt": "<p>Dada uma árvore n-ária, encontre sua profundidade máxima.</p>\n\n<p>A profundidade máxima é o número de nós ao longo do caminho mais longo da raiz até o nó folha mais distante.</p>\n\n<p><em>A serialização de entrada da Nary-Tree é representada em sua travessia em ordem de nível, e cada grupo de filhos é separado pelo valor null (Veja os exemplos).</em></p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Saída:</strong> 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Saída:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número total de nós está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li>A profundidade da árvore n-ária é menor ou igual a <code>1000</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "560",
    "paidOnly": false,
    "title": "Subarray Sum Equals K",
    "titleSlug": "subarray-sum-equals-k",
    "url": "https://leetcode.com/problems/subarray-sum-equals-k",
    "description_url": "https://leetcode.com/problems/subarray-sum-equals-k/description/",
    "description": "<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>\n\n<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1,1], k = 2\n<strong>Output:</strong> 2\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,3], k = 3\n<strong>Output:</strong> 2\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>-10<sup>7</sup> &lt;= k &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/subarray-sum-equals-k/solutions/",
    "solution": "[TOC]\n\n## Video Solution\n\n---\n\n<div class='video-preview'></div>\n\n<div>&nbsp;\n</div>\n\n## Solution Article\n\n---\n\n### Approach 1: Brute Force\n\n**Algorithm**\n\nThe simplest method is to consider every possible subarray of the given $$nums$$ array, find the sum of the elements of each of those subarrays and check for the equality of the sum obtained with the given $$k$$. Whenever the sum equals $$k$$, we can increment the $$count$$ used to store the required result.\n\n<iframe src=\"https://leetcode.com/playground/uzdLhWrz/shared\" frameBorder=\"0\" name=\"uzdLhWrz\" width=\"100%\" height=\"309\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. Considering every possible subarray takes $$O(n^2)$$ time. For each of the subarray we calculate the sum taking $$O(n)$$ time in the worst case, taking a total of $$O(n^3)$$ time.\n\n* Space complexity : $$O(1)$$. Constant space is used.\n\n<br/>\n\n---\n\n### Approach 2: Using Cumulative Sum\n\n**Algorithm**\n\nInstead of determining the sum of elements every time for every new subarray considered, we can make use of a cumulative sum array , $$sum$$. Then, in order to calculate the sum of elements lying between two indices, we can subtract the cumulative sum corresponding to the two indices to obtain the sum directly, instead of iterating over the subarray to obtain the sum.\n\nIn this implementation, we make use of a cumulative sum array, $$sum$$, such that $$sum[i]$$ is used to store the cumulative sum of $$nums$$ array up to the element corresponding to the $$(i-1)^{th}$$ index. Thus, to determine the sum of elements for the subarray $$nums[i:j]$$, we can directly use $$sum[j+1] - sum[i]$$.\n\n<iframe src=\"https://leetcode.com/playground/YnknRnC6/shared\" frameBorder=\"0\" name=\"YnknRnC6\" width=\"100%\" height=\"326\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. Considering every possible subarray takes $$O(n^2)$$ time. Finding out the sum of any subarray takes $$O(1)$$ time after the initial processing of $$O(n)$$ for creating the cumulative sum array.\n\n* Space complexity : $$O(n)$$. Cumulative sum array $$sum$$ of size $$n+1$$ is used.\n\n<br/>\n\n---\n\n### Approach 3: Without Space\n\n**Algorithm**\n\nInstead of considering all the $$start$$ and $$end$$ points and then finding the sum for each subarray corresponding to those points, we can directly find the sum on the go while considering different $$end$$ points. i.e. We can choose a particular $$start$$ point and while iterating over the $$end$$ points, we can add the element corresponding to the $$end$$ point to the sum formed till now. Whenever the $$sum$$ equals the required $$k$$ value, we can update the $$count$$ value. We do so while iterating over all the $$end$$ indices possible for every $$start$$ index. Whenever, we update the $$start$$ index, we need to reset the $$sum$$ value to 0.\n\n<iframe src=\"https://leetcode.com/playground/MGuUEEUy/shared\" frameBorder=\"0\" name=\"MGuUEEUy\" width=\"100%\" height=\"292\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. We need to consider every subarray possible.\n\n* Space complexity : $$O(1)$$. Constant space is used.\n\n<br/>\n\n---\n\n### Approach 4: Using Hashmap\n\n**Algorithm**\n\nThe idea behind this approach is as follows: If the cumulative sum(represented by $$sum[i]$$ for sum up to $$i^{th}$$ index) up to two indices is the same, the sum of the elements lying in between those indices is zero. Extending the same thought further, if the cumulative sum up to two indices, say $$i$$ and $$j$$ is at a difference of $$k$$ i.e. if $$sum[i] - sum[j] = k$$, the sum of elements lying between indices $$i$$ and $$j$$ is $$k$$.\n\nBased on these thoughts, we make use of a hashmap $$map$$ which is used to store the cumulative sum up to all the indices possible along with the number of times the same sum occurs. We store the data in the form: $$(sum_i, no. of occurrences of sum_i)$$. We traverse over the array $$nums$$ and keep on finding the cumulative sum. Every time we encounter a new sum, we make a new entry in the hashmap corresponding to that sum. If the same sum occurs again, we increment the count corresponding to that sum in the hashmap. Further, for every sum encountered, we also determine the number of times the sum $$sum-k$$ has occurred already, since it will determine the number of times a subarray with sum $$k$$ has occurred up to the current index. We increment the $$count$$ by the same amount. \n\nAfter the complete array has been traversed, the $$count$$ gives the required result.\n\nThe animation below depicts the process.\n\n!?!../Documents/560_Subarray.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/S6xciAtN/shared\" frameBorder=\"0\" name=\"S6xciAtN\" width=\"100%\" height=\"292\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. The entire $$nums$$ array is traversed only once.\n\n* Space complexity : $$O(n)$$. Hashmap $$map$$ can contain up to $$n$$ distinct entries in the worst case.\n\n<br/>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def subarraySum(self, nums: List[int], k: int) -> int:\n    ans = 0\n    prefix = 0\n    count = Counter({0: 1})\n\n    for num in nums:\n      prefix += num\n      ans += count[prefix - k]\n      count[prefix] += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int subarraySum(int[] nums, int k) {\n    int ans = 0;\n    int prefix = 0;\n    Map<Integer, Integer> count = new HashMap<>();\n    count.put(0, 1);\n\n    for (final int num : nums) {\n      prefix += num;\n      ans += count.getOrDefault(prefix - k, 0);\n      count.put(prefix, count.getOrDefault(prefix, 0) + 1);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int subarraySum(vector<int>& nums, int k) {\n    int ans = 0;\n    int prefix = 0;\n    unordered_map<int, int> count{{0, 1}};  // {prefix sum: count}\n\n    for (const int num : nums) {\n      prefix += num;\n      const int target = prefix - k;\n      if (count.count(target))\n        ans += count[target];\n      ++count[prefix];\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/560.html",
    "category": "Algorithms",
    "acceptance_rate": 45.300853758409346,
    "topics": [
      "Array",
      "Hash Table",
      "Prefix Sum"
    ],
    "hints": [
      "Will Brute force work here? Try to optimize it.",
      "Can we optimize it by using some extra space?",
      "What about storing sum frequencies in a hash table? Will it be useful?",
      "sum(i,j)=sum(0,j)-sum(0,i), where sum(i,j) represents the sum of all the elements from index i to j-1.\r\n\r\nCan we use this property to optimize it."
    ],
    "likes": 23092,
    "dislikes": 749,
    "similar_questions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Continuous Subarray Sum\", \"titleSlug\": \"continuous-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subarray Product Less Than K\", \"titleSlug\": \"subarray-product-less-than-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Pivot Index\", \"titleSlug\": \"find-pivot-index\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Subarray Sums Divisible by K\", \"titleSlug\": \"subarray-sums-divisible-by-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Reduce X to Zero\", \"titleSlug\": \"minimum-operations-to-reduce-x-to-zero\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Radius Subarray Averages\", \"titleSlug\": \"k-radius-subarray-averages\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Sum Score of Array\", \"titleSlug\": \"maximum-sum-score-of-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"3.9M\", \"totalAcceptedRaw\": 1746836, \"totalSubmissionRaw\": 3856091, \"acRate\": \"45.3%\"}",
    "title_pt": "Subarray com Soma Igual a K",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>o número total de subarrays cuja soma seja igual a</em> <code>k</code>.</p>\n\n<p>Uma subarray é uma sequência contígua <strong>não vazia</strong> de elementos dentro de um array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1,1], k = 2\n<strong>Saída:</strong> 2\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,3], k = 3\n<strong>Saída:</strong> 2\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>-10<sup>7</sup> &lt;= k &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: A força bruta funcionará aqui? Tente otimizá-la.",
      "- Dica 2: Podemos otimizá-lo usando algum espaço extra?",
      "- Dica 3: E se armazenarmos as frequências das somas em uma tabela hash? Isso seria útil?",
      "- Dica 4: sum(i,j)=sum(0,j)-sum(0,i), onde sum(i,j) representa a soma de todos os elementos do índice i até j-1.\n\nPodemos usar essa propriedade para otimizar?"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "561",
    "paidOnly": false,
    "title": "Array Partition",
    "titleSlug": "array-partition",
    "url": "https://leetcode.com/problems/array-partition",
    "description_url": "https://leetcode.com/problems/array-partition/description/",
    "description": "<p>Given an integer array <code>nums</code> of <code>2n</code> integers, group these integers into <code>n</code> pairs <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> such that the sum of <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> for all <code>i</code> is <strong>maximized</strong>. Return<em> the maximized sum</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,4,3,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -&gt; min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -&gt; min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -&gt; min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [6,2,6,5,1,2]\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums.length == 2 * n</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/array-partition/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def arrayPairSum(self, nums: List[int]) -> int:\n    return sum(sorted(nums)[::2])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int arrayPairSum(int[] nums) {\n    int ans = 0;\n\n    Arrays.sort(nums);\n\n    for (int i = 0; i < nums.length; i += 2)\n      ans += nums[i];\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int arrayPairSum(vector<int>& nums) {\n    int ans = 0;\n\n    sort(begin(nums), end(nums));\n\n    for (int i = 0; i < nums.size(); i += 2)\n      ans += nums[i];\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/561.html",
    "category": "Algorithms",
    "acceptance_rate": 80.31842358399818,
    "topics": [
      "Array",
      "Greedy",
      "Sorting",
      "Counting Sort"
    ],
    "hints": [
      "Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4.",
      "How will you make pairs to get the result? There must be some pattern.",
      "Did you observe that- Minimum element gets add into the result in sacrifice of maximum element.",
      "Still won't able to find pairs? Sort the array and try to find the pattern."
    ],
    "likes": 2192,
    "dislikes": 282,
    "similar_questions": "[{\"title\": \"Minimum Difference Between Highest and Lowest of K Scores\", \"titleSlug\": \"minimum-difference-between-highest-and-lowest-of-k-scores\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost of Buying Candies With Discount\", \"titleSlug\": \"minimum-cost-of-buying-candies-with-discount\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"All Divisions With the Highest Score of a Binary Array\", \"titleSlug\": \"all-divisions-with-the-highest-score-of-a-binary-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"567.8K\", \"totalSubmission\": \"706.9K\", \"totalAcceptedRaw\": 567785, \"totalSubmissionRaw\": 706918, \"acRate\": \"80.3%\"}",
    "title_pt": "Particionamento de Array",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> com <code>2n</code> inteiros, agrupe esses inteiros em <code>n</code> pares <code>(a<sub>1</sub>, b<sub>1</sub>), (a<sub>2</sub>, b<sub>2</sub>), ..., (a<sub>n</sub>, b<sub>n</sub>)</code> de modo que a soma de <code>min(a<sub>i</sub>, b<sub>i</sub>)</code> para todos os <code>i</code> seja <strong>maximizada</strong>. Retorne<em> a soma maximizada</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,4,3,2]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Todos os pareamentos possíveis (ignorando a ordem dos elementos) são:\n1. (1, 4), (2, 3) -&gt; min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -&gt; min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -&gt; min(1, 2) + min(3, 4) = 1 + 3 = 4\nPortanto, a soma máxima possível é 4.</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [6,2,6,5,1,2]\n<strong>Saída:</strong> 9\n<strong>Explicação:</strong> O pareamento ótimo é (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>nums.length == 2 * n</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Obviamente, força bruta não vai ajudar aqui. Pense em outra coisa, pegue um exemplo como 1,2,3,4.",
      "Dica 2: Como você fará os pares para obter o resultado? Deve haver algum padrão.",
      "Dica 3: Você observou que o elemento mínimo é somado ao resultado em sacrifício do elemento máximo.",
      "Dica 4: Ainda não conseguiu encontrar os pares? Ordene o array e tente encontrar o padrão."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "563",
    "paidOnly": false,
    "title": "Binary Tree Tilt",
    "titleSlug": "binary-tree-tilt",
    "url": "https://leetcode.com/problems/binary-tree-tilt",
    "description_url": "https://leetcode.com/problems/binary-tree-tilt/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the sum of every tree node&#39;s <strong>tilt</strong>.</em></p>\n\n<p>The <strong>tilt</strong> of a tree node is the <strong>absolute difference</strong> between the sum of all left subtree node <strong>values</strong> and all right subtree node <strong>values</strong>. If a node does not have a left child, then the sum of the left subtree node <strong>values</strong> is treated as <code>0</code>. The rule is similar if the node does not have a right child.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg\" style=\"width: 712px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> \nTilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg\" style=\"width: 800px; height: 203px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,9,3,5,null,7]\n<strong>Output:</strong> 15\n<strong>Explanation:</strong> \nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg\" style=\"width: 800px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> root = [21,7,14,1,1,2,2,3,3]\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-tree-tilt/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Overview\n\nFirst of all, let us clarify the concept of __*tilt*__ for a given node in a tree.\n\nIn order to calculate the tilt value for a node, we need to know the sum of nodes in its left and right subtrees respectively.\n\nAssume that we have a function `valueSum(node)` which gives the sum of all nodes, starting from the input node, then the sum of the node's left subtree would be `valueSum(node.left)`.\nSimilarly, the sum of its right subtree would be `valueSum(node.right)`.\n\nWith the above functions, we can then define the tilt value of a node as follows:\n$$\n    \\text{tilt(node)} = |\\text{valueSum(node.left)} - \\text{valueSum(node.right)}|\n$$\n\nGiven the above formula, we show an example on how the tilt value of each node looks like, in the following graph:\n\n![tilt example](../Figures/563/563_tilt_example.png)\n\n_Note: when a subtree is empty, its value sum is zero._\nAs a result, the tilt value for a leaf node would be zero, since both the left and right subtree of a leaf node are empty.\n\n\n---\n### Approach 1: Post-Order DFS Traversal\n\n**Intuition**\n\n>The overall idea is that we _traverse_ each node, and calculate the _tilt_ value for each node. At the end, we sum up all the tilt values, which is the desired result of the problem.\n\nThere are in general two strategies to traverse a tree data structure, namely [Breadth-First Search](https://leetcode.com/explore/learn/card/queue-stack/231/practical-application-queue/) (**_BFS_**) and [Depth-First Search](https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/) (**_DFS_**).\n\nConcerning the DFS strategy, it can further be divided into three categories: _Pre-Order_, _In-Order_ and _Post-Order_, depending on the relative order of visit among the node and its children nodes.\n\nSometimes, both strategies could work for a specific problem. In other cases, one of them might be more adapted to the problem.\nIn our case here, the _DFS_ is a more optimized choice, as one will see later.\nMore specifically, we could apply the **_Post-Order DFS_** traversal here.\n\n**Algorithm**\n\nAs we discussed before, in order to calculate the tilt value for a node, we need to calculate the sum of its left and right subtrees respectively.\n\nLet us first implement the function `valueSum(node)` which returns the sum of values for all nodes starting from the given `node`, which can be summarized with the following recursive formula:\n\n$$\n    \\text{valueSum(node)} = \\text{node.val} + \\text{valueSum(node.left)} + \\text{valueSum(node.right)}\n$$\n\nFurthermore, the tilt value of a node also depends on the value sum of its left and right subtrees, as follows:\n\n$$\n    \\text{tilt(node)} = |\\text{valueSum(node.left)} - \\text{valueSum(node.right)}|\n$$\n\nIntuitively, we could combine the above calculations within a single recursive function.\nIn this way, we only need to traverse each node once and only once.\n\n>More specifically, we will traverse the tree in the **post-order DFS**, _i.e._ we visit a node's left and right subtrees before processing the value of the current node.\n\nHere are some sample implementations.\n\n<iframe src=\"https://leetcode.com/playground/iY8eedsa/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"iY8eedsa\"></iframe>\n\n\n**Complexity Analysis**\n\nLet $$N$$ be the number of nodes in the input tree.\n\n- Time Complexity: $$\\mathcal{O}(N)$$ \n\n    - We traverse each node once and only once. During the traversal, we calculate the tilt value for each node.\n\n- Space Complexity: $$\\mathcal{O}(N)$$\n\n    - Although the variables that we used in the algorithm are of constant-size, we applied recursion in the algorithm which incurs additional memory consumption in function call stack.\n\n    - In the worst case where the tree is not well balanced, the recursion could pile up $$N$$ times. As a result, the space complexity of the algorithm is $$\\mathcal{O}(N)$$.\n\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findTilt(self, root: Optional[TreeNode]) -> int:\n    ans = 0\n\n    def summ(root: Optional[TreeNode]) -> None:\n      nonlocal ans\n      if not root:\n        return 0\n\n      l = summ(root.left)\n      r = summ(root.right)\n      ans += abs(l - r)\n      return root.val + l + r\n\n    summ(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findTilt(TreeNode root) {\n    sum(root);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  private int sum(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    final int l = sum(root.left);\n    final int r = sum(root.right);\n    ans += Math.abs(l - r);\n    return root.val + l + r;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findTilt(TreeNode* root) {\n    int ans = 0;\n    sum(root, ans);\n    return ans;\n  }\n\n private:\n  int sum(TreeNode* root, int& ans) {\n    if (root == nullptr)\n      return 0;\n\n    const int l = sum(root->left, ans);\n    const int r = sum(root->right, ans);\n    ans += abs(l - r);\n    return root->val + l + r;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/563.html",
    "category": "Algorithms",
    "acceptance_rate": 63.87354490740864,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [
      "Don't think too much, this is an easy problem. Take some small tree as an example.",
      "Can a parent node use the values of its child nodes? How will you implement it?",
      "May be recursion and tree traversal can help you in implementing.",
      "What about postorder traversal, using values of left and right childs?"
    ],
    "likes": 2309,
    "dislikes": 2225,
    "similar_questions": "[{\"title\": \"Find All The Lonely Nodes\", \"titleSlug\": \"find-all-the-lonely-nodes\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"240.2K\", \"totalSubmission\": \"376K\", \"totalAcceptedRaw\": 240168, \"totalSubmissionRaw\": 376006, \"acRate\": \"63.9%\"}",
    "title_pt": "Inclinação de Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a soma da <strong>inclinação</strong> de cada nó da árvore.</em></p>\n\n<p>A <strong>inclinação</strong> de um nó da árvore é a <strong>diferença absoluta</strong> entre a soma de todos os <strong>valores</strong> da subárvore esquerda e todos os <strong>valores</strong> da subárvore direita. Se um nó não tiver um filho esquerdo, então a soma dos <strong>valores</strong> dos nós da subárvore esquerda é tratada como <code>0</code>. A regra é semelhante se o nó não tiver um filho direito.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt1.jpg\" style=\"width: 712px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> \nInclinação do nó 2 : |0-0| = 0 (sem filhos)\nInclinação do nó 3 : |0-0| = 0 (sem filhos)\nInclinação do nó 1 : |2-3| = 1 (a subárvore esquerda é apenas o filho esquerdo, então a soma é 2; a subárvore direita é apenas o filho direito, então a soma é 3)\nSoma de cada inclinação : 0 + 0 + 1 = 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt2.jpg\" style=\"width: 800px; height: 203px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,9,3,5,null,7]\n<strong>Saída:</strong> 15\n<strong>Explicação:</strong> \nInclinação do nó 3 : |0-0| = 0 (sem filhos)\nInclinação do nó 5 : |0-0| = 0 (sem filhos)\nInclinação do nó 7 : |0-0| = 0 (sem filhos)\nInclinação do nó 2 : |3-5| = 2 (a subárvore esquerda é apenas o filho esquerdo, então a soma é 3; a subárvore direita é apenas o filho direito, então a soma é 5)\nInclinação do nó 9 : |0-7| = 7 (sem filho esquerdo, então a soma é 0; a subárvore direita é apenas o filho direito, então a soma é 7)\nInclinação do nó 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (os valores da subárvore esquerda são 3, 5 e 2, cuja soma é 10; os valores da subárvore direita são 9 e 7, cuja soma é 16)\nSoma de cada inclinação : 0 + 0 + 0 + 2 + 7 + 6 = 15\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/20/tilt3.jpg\" style=\"width: 800px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> root = [21,7,14,1,1,2,2,3,3]\n<strong>Saída:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Não pense demais, este é um problema fácil. Pegue uma árvore pequena como exemplo.",
      "- Dica 2: Um nó pai pode usar os valores de seus nós filhos? Como você implementará isso?",
      "- Dica 3: Talvez recursão e travessia de árvore possam ajudar na sua implementação.",
      "- Dica 4: E quanto à travessia em pós-ordem, usando os valores dos filhos esquerdo e direito?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "564",
    "paidOnly": false,
    "title": "Find the Closest Palindrome",
    "titleSlug": "find-the-closest-palindrome",
    "url": "https://leetcode.com/problems/find-the-closest-palindrome",
    "description_url": "https://leetcode.com/problems/find-the-closest-palindrome/description/",
    "description": "<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>\n\n<p>The closest is defined as the absolute difference minimized between two integers.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = &quot;123&quot;\n<strong>Output:</strong> &quot;121&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = &quot;1&quot;\n<strong>Output:</strong> &quot;0&quot;\n<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n.length &lt;= 18</code></li>\n\t<li><code>n</code> consists of only digits.</li>\n\t<li><code>n</code> does not have leading zeros.</li>\n\t<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-the-closest-palindrome/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Find Previous and Next Palindromes\n\n#### Intuition\n\nThe problem asks us to find the closest palindrome to a given integer `n` represented as a string. The string length is at most 18, meaning `n` can be as large as 999,999,999,999,999,999. The goal is to return the nearest palindrome to `n` that is not equal to `n` itself, minimizing the absolute difference.\n\nTo solve this, we can think of a palindrome as a number where the first half is mirrored to create the second half. For example, the palindrome for `12321` is formed by reversing the first half (`12`) and appending it to itself (`12` -> `12321`). This observation is key to finding the closest palindrome.\n\nIf we consider changing the second half of `n` to match the reverse of the first half, we might obtain a palindrome close to `n`. However, there are cases where this method might not give us the optimal answer, particularly for odd-length strings or when small adjustments to the first half could yield a closer palindrome.\n\nFor instance, consider `n = 139`. If we mirror the first half (`13`), we get `131`, but a closer palindrome is `141`. Therefore, it's important to also check palindromes formed by slightly adjusting the first half of `n`:\n\n1. Same Half: Create a palindrome by mirroring the first half.\n2. Decremented Half: Create a palindrome by decrementing the first half by 1 and mirroring it.\n3. Incremented Half: Create a palindrome by incrementing the first half by 1 and mirroring it.\n\n> Note: Adding +1 or subtracting -1 to/from the first half ensures that we stay as close as possible to the original number while creating new potential palindromes. If we were to add or subtract a larger value, such as +2 or -2, the resulting palindrome would be farther away from the original number, potentially missing a closer palindrome, and it's given that we need to find the closest palindrome.\n\n\nIn addition to these cases, we must handle edge cases where `n` is close to numbers like `1000`, `10000`, etc., or very small numbers like `11` or `9`. These can produce palindromes like `99`, `999`, or `101`, `1001`, which might be closer to `n`.\n\nTo summarize, we need to check the following five candidates:\n- Palindrome formed from the first half of `n`.\n- Palindrome formed from the first half decremented by 1.\n- Palindrome formed from the first half incremented by 1.\n- Nearest palindrome of the form `99`, `999`, etc.\n- Nearest palindrome of the form `101`, `1001`, etc.\n\nAfter generating these candidates, we compare them to `n` and choose the one with the smallest absolute difference.\n\n#### Algorithm\n\nMain Function - `nearestPalindromic(n)`\n\n1. Calculate the length of `n` and determine the midpoint.\n2. Extract the first half of the number.\n3. Generate possible palindromic candidates and append them to `possibilities` list:\n    - Mirror the first half and append it to the string.\n    - Mirror the first half incremented by 1 and append it to the string.\n    - Mirror the first half decremented by 1 and append it to the string.\n    - Add the form 999....\n    - Add the form 100...001.\n4. Find the nearest palindromic number by comparing absolute differences.\n5. Return the closest palindrome.\n\nHelper Function - `halfToPalindrome(left, even)`\n\n1. Initialize `res` with `left`.\n2. If the length is odd, divide `left` by 10.\n3. Mirror the digits of `left` to form a palindrome.\n4. Return the palindrome `res`.\n\n![approach1](../Figures/564/approach1.png)\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/NDKjtFUm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"NDKjtFUm\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of digits in the input number.\n\n- Time complexity: $O(n)$\n    \n    We perform operations on exactly 5 strings. The palindrome construction for each string takes $O(n)$ time. Therefore, total time complexity is given by $O(n)$.\n\n- Space complexity: $O(n)$\n    \n    We store the 5 possible candidates in the `possibilities` array. Apart from this, the built-in functions used to make the `firstHalf` can potentially lead to $O(n)$ space complexity, as they copy the characters into a new String. Therefore, the total space complexity is $O(n)$.\n\n---\n\n### Approach 2: Binary Search\n\n#### Intuition\n\nAnother way to solve the problem is by using binary search. The task is to find the smallest palindrome greater than `n` and the largest palindrome smaller than `n`, then return the one with the smallest absolute difference. Since this is a minimization/maximization, we can try to use binary search to solve this problem. But, our search space should be sorted to apply binary search. Observe that when you construct the palindromes using the first half for two integers, then the greater integer would always have it's constructed palindrome greater. Therefore, our search space is sorted in a non-decreasing order.\n\nGiven that palindromes are symmetric numbers, we can search within a specific range by leveraging binary search. The key is to first determine potential palindromes by constructing them based on the first half of `n`.\n\nFinding the Next Palindrome:\n- Start with the left boundary as `n + 1` and the right boundary as an infinitely large value.\n- Perform binary search within this range. For each midpoint value, construct the palindrome by mirroring its first half.\n- If the constructed palindrome is greater than `n`, shift the search to the left (smaller values). Otherwise, move to the right.\n\nFinding the Previous Palindrome:\n- Start with the left boundary as `0` and the right boundary as `n - 1`.\n- Perform binary search, constructing palindromes as above.\n- If the constructed palindrome is smaller than `n`, shift the search to the right (larger values). Otherwise, move to the left.\n\nBinary search efficiently narrows down the range of possible palindromes, finding the closest one that is greater and the closest one that is smaller. Once we have these two candidates, we simply compare their differences with `n` to determine the closest palindrome.\n\nThis approach is particularly useful when `n` is large, as it reduces the search space compared to checking all potential candidates directly.\n\n#### Algorithm\n\n`convert(num)`\n\n1. Convert the number `num` to a string `s`.\n2. Identify the midpoint indices `l (left)` and `r (right)`.\n3. Mirror the left half of the string s onto the right half to create a palindrome.\n4. Return the palindrome as a long integer.\n\n`nextPalindrome(num)`\n\n1. Initialize `left` to 0 and `right` to `num`.\n2. Use binary search to find the next palindrome greater than `num`:\n    - Calculate `mid` as the midpoint between `left` and `right`.\n    - Convert `mid` to a palindrome using `convert(mid)`.\n    - If the palindrome is less than `num`, update `ans` to the palindrome and set `left` to `mid + 1`.\n    - Otherwise, set `right` to `mid - 1`.\n3. Return the result `ans`.\n\n`previousPalindrome(num)`\n\n1. Initialize `left` to `num` and `right` to a large value `(1e18)`.\n2. Use binary search to find the previous palindrome smaller than `num`:\n    - Calculate `mid` as the midpoint between `left` and `right`.\n    - Convert `mid` to a palindrome using `convert(mid)`.\n    - If the palindrome is greater than `num`, update `ans` to the palindrome and set `right` to `mid - 1`.\n    - Otherwise, set `left` to `mid + 1`.\n3. Return the result `ans`.\n\nMain Function - `nearestPalindromic(n)`\n\n1. Convert the input string `n` to a long integer `num`.\n2. Call `nextPalindrome(num)` to find the next palindrome greater than `num`.\n3. Call `previousPalindrome(num)` to find the previous palindrome smaller than `num`.\n4. Compare the differences between `num` and the two palindromes found:\n    - If the difference with the next palindrome is less than or equal to the difference with the previous palindrome, return the next palindrome. Otherwise, return the previous palindrome as a string.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/bVnnvn8k/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"bVnnvn8k\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the input number and $n$ be the number of digits in it.\n\n- Time complexity: $O(n \\cdot log(m))$\n    \n    We perform two binary search operations on a search space of size `m`, and in each operation iterate through all the digits. Therefore, the total time complexity is given by $O(n \\cdot log(m))$.\n\n- Space complexity: $O(n)$\n\n    The space complexity is primarily determined by the storage needed for the string representation of the number and the intermediate list or character array used for manipulation. Since these data structures are proportional to the number of digits in $O(n)$, the total space complexity is $O(n)$.\n\n    For C++: `to_string(num)` - Converts the number to a string, which requires space proportional to the number of digits in $O(n)$, i.e., $O(n)$.\n    For Java: `Long.toString(num)` - Converts the number to a string, requiring $O(n)$ space.\n    For Python: `''.join(s_list)` - Creates a new string from the list, requiring $O(n)$ space.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def nearestPalindromic(self, n: str) -> str:\n    def getPalindromes(s: str) -> tuple:\n      num = int(s)\n      k = len(s)\n      palindromes = []\n      half = s[0:(k + 1) // 2]\n      reversedHalf = half[:k // 2][::-1]\n      candidate = int(half + reversedHalf)\n\n      if candidate < num:\n        palindromes.append(candidate)\n      else:\n        prevHalf = str(int(half) - 1)\n        reversedPrevHalf = prevHalf[:k // 2][::-1]\n        if k % 2 == 0 and int(prevHalf) == 0:\n          palindromes.append(9)\n        elif k % 2 == 0 and (int(prevHalf) + 1) % 10 == 0:\n          palindromes.append(int(prevHalf + '9' + reversedPrevHalf))\n        else:\n          palindromes.append(int(prevHalf + reversedPrevHalf))\n\n      if candidate > num:\n        palindromes.append(candidate)\n      else:\n        nextHalf = str(int(half) + 1)\n        reversedNextHalf = nextHalf[:k // 2][::-1]\n        palindromes.append(int(nextHalf + reversedNextHalf))\n\n      return palindromes\n\n    prevPalindrome, nextPalindrome = getPalindromes(n)\n    return str(prevPalindrome) if abs(prevPalindrome - int(n)) <= abs(nextPalindrome - int(n)) else str(nextPalindrome)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String nearestPalindromic(String n) {\n    final long[] palindromes = getPalindromes(n);\n    return Math.abs(palindromes[0] - Long.parseLong(n)) <=\n            Math.abs(palindromes[1] - Long.parseLong(n))\n        ? String.valueOf(palindromes[0])\n        : String.valueOf(palindromes[1]);\n  }\n\n  private long[] getPalindromes(final String s) {\n    final long num = Long.parseLong(s);\n    final int n = s.length();\n    long[] palindromes = new long[2];\n    final String half = s.substring(0, (n + 1) / 2);\n    final String reversedHalf = new StringBuilder(half.substring(0, n / 2)).reverse().toString();\n    final long candidate = Long.parseLong(half + reversedHalf);\n\n    if (candidate < num)\n      palindromes[0] = candidate;\n    else {\n      final String prevHalf = String.valueOf(Long.parseLong(half) - 1);\n      final String reversedPrevHalf =\n          new StringBuilder(prevHalf.substring(0, Math.min(prevHalf.length(), n / 2)))\n              .reverse()\n              .toString();\n      if (n % 2 == 0 && Long.parseLong(prevHalf) == 0)\n        palindromes[0] = 9;\n      else if (n % 2 == 0 && (Long.parseLong(prevHalf) + 1) % 10 == 0)\n        palindromes[0] = Long.parseLong(prevHalf + '9' + reversedPrevHalf);\n      else\n        palindromes[0] = Long.parseLong(prevHalf + reversedPrevHalf);\n    }\n\n    if (candidate > num)\n      palindromes[1] = candidate;\n    else {\n      final String nextHalf = String.valueOf(Long.parseLong(half) + 1);\n      final String reversedNextHalf =\n          new StringBuilder(nextHalf.substring(0, n / 2)).reverse().toString();\n      palindromes[1] = Long.parseLong(nextHalf + reversedNextHalf);\n    }\n\n    return palindromes;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string nearestPalindromic(string n) {\n    const auto& [prevPalindrome, nextPalindrome] = getPalindromes(n);\n    return abs(prevPalindrome - stol(n)) <= abs(nextPalindrome - stol(n))\n               ? to_string(prevPalindrome)\n               : to_string(nextPalindrome);\n  }\n\n private:\n  pair<long, long> getPalindromes(const string& s) {\n    const long num = stol(s);\n    const int n = s.length();\n    pair<long, long> palindromes;\n    const string& half = s.substr(0, (n + 1) / 2);\n    const string& reversedHalf = reversed(half.substr(0, n / 2));\n    const long candidate = stol(half + reversedHalf);\n\n    if (candidate < num)\n      palindromes.first = candidate;\n    else {\n      const string& prevHalf = to_string(stol(half) - 1);\n      const string& reversedPrevHalf = reversed(prevHalf.substr(0, n / 2));\n      if (n % 2 == 0 && stol(prevHalf) == 0)\n        palindromes.first = 9;\n      else if (n % 2 == 0 && (stol(prevHalf) + 1) % 10 == 0)\n        palindromes.first = stol(prevHalf + '9' + reversedPrevHalf);\n      else\n        palindromes.first = stol(prevHalf + reversedPrevHalf);\n    }\n\n    if (candidate > num)\n      palindromes.second = candidate;\n    else {\n      const string& nextHalf = to_string(stol(half) + 1);\n      const string& reversedNextHalf = reversed(nextHalf.substr(0, n / 2));\n      palindromes.second = stol(nextHalf + reversedNextHalf);\n    }\n\n    return palindromes;\n  }\n\n  string reversed(const string& s) {\n    return {rbegin(s), rend(s)};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/564.html",
    "category": "Algorithms",
    "acceptance_rate": 31.60355003018224,
    "topics": [
      "Math",
      "String"
    ],
    "hints": [
      "Will brute force work for this problem? Think of something else.",
      "Take some examples like 1234, 999,1000, etc and check their closest palindromes. How many different cases are possible?",
      "Do we have to consider only left half or right half of the string or both?",
      "Try to find the closest palindrome of these numbers- 12932, 99800, 12120. Did you observe something?"
    ],
    "likes": 1275,
    "dislikes": 1717,
    "similar_questions": "[{\"title\": \"Find Palindrome With Fixed Length\", \"titleSlug\": \"find-palindrome-with-fixed-length\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Next Palindrome Using Same Digits\", \"titleSlug\": \"next-palindrome-using-same-digits\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Count of Good Integers\", \"titleSlug\": \"find-the-count-of-good-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Largest Palindrome Divisible by K\", \"titleSlug\": \"find-the-largest-palindrome-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"126.7K\", \"totalSubmission\": \"400.9K\", \"totalAcceptedRaw\": 126698, \"totalSubmissionRaw\": 400897, \"acRate\": \"31.6%\"}",
    "title_pt": "Encontrar o Palíndromo Mais Próximo",
    "description_pt": "<p>Dada uma string <code>n</code> representando um inteiro, retorne <em>o inteiro mais próximo (não incluindo ele mesmo), que seja um palíndromo</em>. Se houver empate, retorne <em><strong>o menor deles</strong></em>.</p>\n\n<p>O mais próximo é definido como a diferença absoluta minimizada entre dois inteiros.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = &quot;123&quot;\n<strong>Saída:</strong> &quot;121&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = &quot;1&quot;\n<strong>Saída:</strong> &quot;0&quot;\n<strong>Explicação:</strong> 0 e 2 são os palíndromos mais próximos, mas retornamos o menor, que é 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n.length &lt;= 18</code></li>\n\t<li><code>n</code> consiste apenas de dígitos.</li>\n\t<li><code>n</code> não possui zeros à esquerda.</li>\n\t<li><code>n</code> representa um inteiro no intervalo <code>[1, 10<sup>18</sup> - 1]</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: A força bruta funcionaria para este problema? Pense em outra coisa.",
      "Dica 2: Tente alguns exemplos como 1234, 999,1000, etc. e verifique seus palíndromos mais próximos. Quantos casos diferentes são possíveis?",
      "Dica 3: Precisamos considerar apenas a metade esquerda ou a metade direita da string, ou ambas?",
      "Dica 4: Tente encontrar o palíndromo mais próximo destes números- 12932, 99800, 12120. Você observou algo?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "565",
    "paidOnly": false,
    "title": "Array Nesting",
    "titleSlug": "array-nesting",
    "url": "https://leetcode.com/problems/array-nesting",
    "description_url": "https://leetcode.com/problems/array-nesting/description/",
    "description": "<p>You are given an integer array <code>nums</code> of length <code>n</code> where <code>nums</code> is a permutation of the numbers in the range <code>[0, n - 1]</code>.</p>\n\n<p>You should build a set <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> subjected to the following rule:</p>\n\n<ul>\n\t<li>The first element in <code>s[k]</code> starts with the selection of the element <code>nums[k]</code> of <code>index = k</code>.</li>\n\t<li>The next element in <code>s[k]</code> should be <code>nums[nums[k]]</code>, and then <code>nums[nums[nums[k]]]</code>, and so on.</li>\n\t<li>We stop adding right before a duplicate element occurs in <code>s[k]</code>.</li>\n</ul>\n\n<p>Return <em>the longest length of a set</em> <code>s[k]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [5,4,0,3,1,6,2]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> \nnums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [0,1,2]\n<strong>Output:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt; nums.length</code></li>\n\t<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/array-nesting/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\nThe simplest method is to iterate over all the indices of the given $$nums$$ array. For every index $$i$$ chosen, we find the element $$nums[i]$$ and increment the $$count$$ for a new element added for the current index $$i$$. Since $$nums[i]$$ has to act as the new index for finding the next element belonging to the set corresponding to the index $$i$$, the new index is $$j=nums[i]$$.\n\nWe continue this process of index updation and keep on incrementing the $$count$$ for new elements added to the set corresponding to the index $$i$$. Now, since all the elements in $$nums$$ lie in the range $$(0,..., N-1)$$, the new indices generated will never lie outside the array size limits. But, we'll always reach a point where the current element becomes equal to the element  $$nums[i]$$ with which we started the nestings in the first place. Thus, after this, the new indices generated will be just the repetitions of the previously generated ones, and thus would not lead to an increase in the size of the current set. Thus, this condition of the current number being equal to the starting number acts as the terminating condition for $$count$$ incrementation for a particular index.\n\nWe do the same process for every index chosen as the starting index. At the end, the maximum value of $$count$$ obtained gives the size of the largest set.\n\n<iframe src=\"https://leetcode.com/playground/K6QuRdnw/shared\" frameBorder=\"0\" name=\"K6QuRdnw\" width=\"100%\" height=\"326\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. In worst case, for example- `[1,2,3,4,5,0]`, loop body will be executed $$n^2$$ times.\n\n* Space complexity : $$O(1)$$. Constant space is used.\n\n---\n### Approach #2 Using Visited Array [Accepted]\n\n**Algorithm**\n\nIn the last approach, we observed that in the worst case, all the elements of the $$nums$$ array are added to the sets corresponding to all the starting indices. But, all these sets correspond to the same set of elements only, leading to redundant calculations.\n\nWe consider a simple example and see how this problem can be resolved. From the figure below, we can see that the elements in the current nesting shown by arrows form a cycle. Thus, the same elements will be added to the current set irrespective of the first element chosen to be added to the set out of these marked elements.\n\n![Array_Nesting](../Figures/565/Array_Nesting.PNG)\n\nThus, when we add an element $$nums[j]$$ to a set corresponding to any of the indices, we mark its position as visited in a $$visited$$ array. This is done so that whenever this index is chosen as the starting index in the future, we do not go for redundant $$count$$ calculations, since we've already considered the elements linked with this index, which will be added to a new(duplicate) set.\n\nBy doing so, we ensure that the duplicate sets aren't considered again and again.\n\nFurther, we can also observe that no two elements at indices $$i$$ and $$j$$ will lead to a jump to the same index $$k$$, since it would require $$nums[i] = nums[j] = k$$, which isn't possible since all the elements are distinct. Also, because of the same reasoning, no element outside any cycle could lead to an element inside the cycle. Because of this, the use of $$visited$$ array goes correctly. \n\n<iframe src=\"https://leetcode.com/playground/XQA6FiH7/shared\" frameBorder=\"0\" name=\"XQA6FiH7\" width=\"100%\" height=\"394\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Every element of the $$nums$$ array will be considered at most once.\n\n* Space complexity : $$O(n)$$. $$visited$$ array of size $$n$$ is used.\n\n---\n### Approach #3 Without Using Extra Space [Accepted]\n\n**Algorithm**\n\nIn the last approach, the $$visited$$ array is used just to keep a track of the elements of the array which have already been visited. Instead of making use of a separate array to keep track of the same, we can mark the visited elements in the original array $$nums$$ itself. Since, the range of the elements can only be between 1 to 20,000, we can put a very large integer value `Integer.MAX_VALUE` at the position which has been visited. The rest process of traversals remains the same as in the last approach.\n\n<iframe src=\"https://leetcode.com/playground/7DmKnygx/shared\" frameBorder=\"0\" name=\"7DmKnygx\" width=\"100%\" height=\"394\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Every element of the $$nums$$ array will be considered at most once.\n\n* Space complexity : $$O(1)$$. Constant Space is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def arrayNesting(self, nums: List[int]) -> int:\n    ans = 0\n\n    for num in nums:\n      if num == -1:\n        continue\n      index = num\n      count = 0\n      while nums[index] != -1:\n        temp = index\n        index = nums[index]\n        nums[temp] = -1\n        count += 1\n      ans = max(ans, count)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int arrayNesting(int[] nums) {\n    int ans = 0;\n\n    for (final int num : nums) {\n      if (num == -1)\n        continue;\n      int index = num;\n      int count = 0;\n      while (nums[index] != -1) { // Not yet seen\n        final int cache = index;\n        index = nums[index]; // Get next index\n        nums[cache] = -1;    // Already seen\n        ++count;\n      }\n      ans = Math.max(ans, count);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int arrayNesting(vector<int>& nums) {\n    int ans = 0;\n\n    for (const int num : nums) {\n      if (num == -1)\n        continue;\n      int index = num;\n      int count = 0;\n      while (nums[index] != -1) {  // Not yet seen\n        const int cache = index;\n        index = nums[index];  // Get next index\n        nums[cache] = -1;     // Already seen\n        ++count;\n      }\n      ans = max(ans, count);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/565.html",
    "category": "Algorithms",
    "acceptance_rate": 55.94525886957079,
    "topics": [
      "Array",
      "Depth-First Search"
    ],
    "hints": [],
    "likes": 2239,
    "dislikes": 158,
    "similar_questions": "[{\"title\": \"Nested List Weight Sum\", \"titleSlug\": \"nested-list-weight-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flatten Nested List Iterator\", \"titleSlug\": \"flatten-nested-list-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Nested List Weight Sum II\", \"titleSlug\": \"nested-list-weight-sum-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"139.5K\", \"totalSubmission\": \"249.4K\", \"totalAcceptedRaw\": 139523, \"totalSubmissionRaw\": 249392, \"acRate\": \"55.9%\"}",
    "title_pt": "Aninhamento de Array",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> de comprimento <code>n</code>, em que <code>nums</code> é uma permutação dos números no intervalo <code>[0, n - 1]</code>.</p>\n\n<p>Você deve construir um conjunto <code>s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }</code> sujeito à seguinte regra:</p>\n\n<ul>\n\t<li>O primeiro elemento em <code>s[k]</code> começa com a seleção do elemento <code>nums[k]</code> do <code>index = k</code>.</li>\n\t<li>O próximo elemento em <code>s[k]</code> deve ser <code>nums[nums[k]]</code>, e então <code>nums[nums[nums[k]]]</code>, e assim por diante.</li>\n\t<li>Paramos de adicionar imediatamente antes que ocorra um elemento duplicado em <code>s[k]</code>.</li>\n</ul>\n\n<p>Retorne <em>o maior comprimento de um conjunto</em> <code>s[k]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [5,4,0,3,1,6,2]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> \nnums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nUm dos maiores conjuntos s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [0,1,2]\n<strong>Saída:</strong> 1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt; nums.length</code></li>\n\t<li>Todos os valores de <code>nums</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "566",
    "paidOnly": false,
    "title": "Reshape the Matrix",
    "titleSlug": "reshape-the-matrix",
    "url": "https://leetcode.com/problems/reshape-the-matrix",
    "description_url": "https://leetcode.com/problems/reshape-the-matrix/description/",
    "description": "<p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>\n\n<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>\n\n<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>\n\n<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg\" style=\"width: 613px; height: 173px;\" />\n<pre>\n<strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4\n<strong>Output:</strong> [[1,2,3,4]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg\" style=\"width: 453px; height: 173px;\" />\n<pre>\n<strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4\n<strong>Output:</strong> [[1,2],[3,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-1000 &lt;= mat[i][j] &lt;= 1000</code></li>\n\t<li><code>1 &lt;= r, c &lt;= 300</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/reshape-the-matrix/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:\n    if nums == [] or r * c != len(nums) * len(nums[0]):\n      return nums\n\n    ans = [[0 for j in range(c)] for i in range(r)]\n    k = 0\n\n    for row in nums:\n      for num in row:\n        ans[k // c][k % c] = num\n        k += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] matrixReshape(int[][] nums, int r, int c) {\n    if (nums.length == 0 || r * c != nums.length * nums[0].length)\n      return nums;\n\n    int[][] ans = new int[r][c];\n    int k = 0;\n\n    for (int[] row : nums)\n      for (final int num : row) {\n        ans[k / c][k % c] = num;\n        ++k;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n    if (nums.empty() || r * c != nums.size() * nums[0].size())\n      return nums;\n\n    vector<vector<int>> ans(r, vector<int>(c));\n    int k = 0;\n\n    for (const vector<int>& row : nums)\n      for (const int num : row) {\n        ans[k / c][k % c] = num;\n        ++k;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/566.html",
    "category": "Algorithms",
    "acceptance_rate": 63.81354657003935,
    "topics": [
      "Array",
      "Matrix",
      "Simulation"
    ],
    "hints": [
      "Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one.",
      "M[i][j]=M[n*i+j] , where n is the number of cols. \r\nThis is the one way of converting 2-d indices into one 1-d index.  \r\nNow, how will you convert 1-d index into 2-d indices?",
      "Try to use division and modulus to convert 1-d index into 2-d indices.",
      "M[i] =>  M[i/n][i%n] Will it result in right mapping? Take some example and check this formula."
    ],
    "likes": 3602,
    "dislikes": 426,
    "similar_questions": "[{\"title\": \"Convert 1D Array Into 2D Array\", \"titleSlug\": \"convert-1d-array-into-2d-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"419.8K\", \"totalSubmission\": \"657.9K\", \"totalAcceptedRaw\": 419843, \"totalSubmissionRaw\": 657922, \"acRate\": \"63.8%\"}",
    "title_pt": "Reformatar a Matriz",
    "description_pt": "<p>No MATLAB, existe uma função prática chamada <code>reshape</code> que pode reformar uma matriz <code>m x n</code> em uma nova com um tamanho diferente <code>r x c</code>, mantendo seus dados originais.</p>\n\n<p>Você recebe uma matriz <code>m x n</code> <code>mat</code> e dois inteiros <code>r</code> e <code>c</code> representando o número de linhas e o número de colunas da matriz reformada desejada.</p>\n\n<p>A matriz reformada deve ser preenchida com todos os elementos da matriz original na mesma ordem de percurso por linhas em que eles estavam.</p>\n\n<p>Se a operação <code>reshape</code> com os parâmetros dados for possível e válida, retorne a nova matriz reformada; caso contrário, retorne a matriz original.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg\" style=\"width: 613px; height: 173px;\" />\n<pre>\n<strong>Entrada:</strong> mat = [[1,2],[3,4]], r = 1, c = 4\n<strong>Saída:</strong> [[1,2,3,4]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg\" style=\"width: 453px; height: 173px;\" />\n<pre>\n<strong>Entrada:</strong> mat = [[1,2],[3,4]], r = 2, c = 4\n<strong>Saída:</strong> [[1,2],[3,4]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == mat.length</code></li>\n\t<li><code>n == mat[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 100</code></li>\n\t<li><code>-1000 &lt;= mat[i][j] &lt;= 1000</code></li>\n\t<li><code>1 &lt;= r, c &lt;= 300</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Você sabe como uma matriz 2D é armazenada em memória 1D? Tente mapear 2 dimensões em uma.",
      "Dica 2: M[i][j]=M[n*i+j] , onde n é o número de colunas. \r\nEsta é uma maneira de converter índices 2D em um índice 1D.  \r\nAgora, como você converterá um índice 1D em índices 2D?",
      "Dica 3: Tente usar divisão e módulo para converter um índice 1D em índices 2D.",
      "Dica 4: M[i] =>  M[i/n][i%n] Isso resultará no mapeamento correto? Tente com algum exemplo e verifique essa fórmula."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "567",
    "paidOnly": false,
    "title": "Permutation in String",
    "titleSlug": "permutation-in-string",
    "url": "https://leetcode.com/problems/permutation-in-string",
    "description_url": "https://leetcode.com/problems/permutation-in-string/description/",
    "description": "<p>Given two strings <code>s1</code> and <code>s2</code>, return <code>true</code> if <code>s2</code> contains a <span data-keyword=\"permutation-string\">permutation</span> of <code>s1</code>, or <code>false</code> otherwise.</p>\n\n<p>In other words, return <code>true</code> if one of <code>s1</code>&#39;s permutations is the substring of <code>s2</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidbaooo&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> s2 contains one permutation of s1 (&quot;ba&quot;).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidboaoo&quot;\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/permutation-in-string/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Brute Force\n\n> Note: This approach is included because it is a logical first step towards building an efficient solution. However, it is a brute-force approach and is not expected to pass all test cases. Readers are still recommended to read it because it helps to understand the following approaches.\n\n**Algorithm**\n\nThe simplest method is to generate all the permutations of the short string  and to check if the generated permutation is a substring of the longer string.\n\nIn order to generate all the possible pairings, we make use of a function `permute(string_1, string_2, current_index)`. This function creates all the possible permutations of the short string $$s1$$.\n\nTo do so, permute takes the index of the current element $$current\\_index$$ as one of the arguments. Then, it swaps the current element with every other element in the array, lying towards its right, so as to generate a new ordering of the array elements. After the swapping has been done, it makes another call to permute but this time with the index of the next element in the array. While returning back, we reverse the swapping done in the current function call.\n\nThus, when we reach the end of the array, a new ordering of the array's elements is generated. The following animation depicts the process of generating the permutations.\n\n!?!../Documents/561_Array.json:1000,563!?!\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/LWP4QuTU/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"LWP4QuTU\"></iframe>\n\n**Complexity Analysis**\n\nLet $$n$$ be the length of $$s1$$\n    \n* Time complexity: $$O(n!)$$. The permute method generates all possible permutations of the string `s1`. In a permutation problem, the number of ways to permute a string of length $n$ is $n!$. Each recursive call swaps characters at different positions to explore every possible permutation at each level of recursion. At the first level, there are $n$ choices for which character to place in the first position. At the second level, there are $n−1$ choices for which character to place in the second position, and so on, leading to $n!$ total recursive calls.\n\n* Space complexity: $$O(n^2)$$. The depth of the recursion tree is $$n$$($$n$$ refers to the length of the short string `s1`). Every node of the recursion tree contains a string of max. length $$n$$.\n\n---\n\n### Approach 2: Using sorting:\n\n**Algorithm**\n\nThe idea behind this approach is that one string will be a permutation of another string only if both of them contain the same characters the same number of times. One string $$x$$ is a permutation of other string $$y$$ only if $$sorted(x)=sorted(y)$$. \n\nIn order to check this, we can sort the two strings and compare them.  We sort the short string $$s1$$ and all the substrings of $$s2$$, sort them and compare them with the sorted $$s1$$ string. If the two matches completely, $$s1$$'s permutation is a substring of $$s2$$, otherwise not.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/Wb5Q7yA8/shared\" frameBorder=\"0\" width=\"100%\" height=\"327\" name=\"Wb5Q7yA8\"></iframe>\n\n**Complexity Analysis**\n\nLet $$l_1$$ be the length of string $$s_1$$ and $$l_2$$ be the length of string $$s_2$$.\n    \n* Time complexity: $O((l_2 - l_1) \\cdot l_1 \\log l_1)$.\n  \n  First, we sort $s_1$ which takes $O(l_1 \\log l_1)$. Then, we iterate through a range of $(l_2 - l_1 + 1)$ and within the loop, we sort a substring of length $l_1$. This process takes $O((l_2 - l_1 + 1) \\cdot l_1 \\log l_1)$ time. Overall, we combine both time complexities: $O((l_2 - l_1 + 1 + 1) \\cdot l_1 \\log l_1) \\rightarrow O((l_2 - l_1) \\cdot l_1 \\log l_1)$\n\n* Space complexity: $O(l_1 + S)$. $t$ array is used.\n\n    Some extra space is used when we sort an array of size $n$ in place. The space complexity of the sorting algorithm ($S$) depends on the programming language. The value of $S$ depends on the programming language and the sorting algorithm being used:\n    - In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has a space complexity of $O(n)$\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worst-case space complexity of $O( \\log n )$\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$\n\n    Thus, the total space complexity of the algorithm is $O(l_1 + S)$.\n\n---\n\n### Approach 3: Using Hashmap\n\n**Algorithm**\n\nAs discussed above, one string will be a permutation of another string only if both of them contain the same characters with the same frequency. We can consider every possible substring in the long string $$s2$$ of the same length as that of $$s1$$ and check the frequency of occurence of the characters appearing in the two. If the frequencies of every letter match exactly, then only $$s1$$'s permutation can be a substring of $$s2$$. \n\nIn order to implement this approach, instead of sorting and then comparing the elements for equality, we make use of a hashmap $$s1map$$ which stores the frequency of occurence of all the characters in the short string $$s1$$. We consider every possible substring of $$s2$$ of the same length as that of $$s1$$, find its corresponding hashmap as well, namely $$s2map$$. Thus, the substrings considered can be viewed as a window of length as that of $$s1$$ iterating over $$s2$$. If the two hashmaps obtained are identical for any such window, we can conclude that $$s1$$'s permutation is a substring of $$s2$$, otherwise not.\n    \n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/J6Pashup/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"J6Pashup\"></iframe>\n\n**Complexity Analysis**\n\nLet $$l_1$$ be the length of string $$s_1$$ and $$l_2$$ be the length of string $$s_2$$.\n\n* Time complexity: $O(l_1 + (26 + l_1) \\cdot (l_2 - l_1))$\n  \n  The initialization of the map `s1map` takes $O(l_1)$ since we loop through each character of $s_1$ once and store the counts.\n\n  The outer loop runs $(l_2 - l_1 + 1)$ times, as we need to consider each possible substring of length $l_1$ within $s_2$.\n\n  For each iteration of the outer loop, we build `s2map`, which takes $O(l_1)$ time (since we process $l_1$ characters for each substring in $s_2$).\n\n  In the `matches` function, we iterate through `s1map` to compare it with `s2map`. This takes $O(26) = O(1)$, as the alphabet size is constant (26 characters). Thus, checking equality of the two maps involves a constant-time comparison for each character in the alphabet.\n\n  Thus, the total time complexity becomes: $O(l_1 + (26 + l_1) \\cdot (l_2 - l_1))$.\n\n* Space complexity: $O(l_2 - l_1)$\n  \n  Each substring from $s_2$ of length $l_1$ creates a `HashMap` (`s2map`) to store the character frequencies.\n\n  The size of this `HashMap` is $O(26)$, since there are at most 26 characters in the alphabet.\n  \n  Over $l_2 - l_1 + 1$ iterations of the outer loop, we create one such `HashMap` per iteration, resulting in $O(26 \\cdot (l_2 - l_1 + 1))$ space usage.\n\n  We also create a `HashMap` for $s_1$ (`s1map`), which similarly takes $O(26)$ space.\n  \n  Since we need to store a `HashMap` for each of the $l_2 - l_1 + 1$ substrings in the worst case, the space complexity is proportional to the number of substrings and the size of each `HashMap`. \n  \n  Therefore, the total space complexity is: $O(26 \\cdot (l_2 - l_1 + 1) + 26) = O(26 \\cdot (l_2 - l_1 + 1))$. In simplified terms: $O(l_2 - l_1)$\n\n---\n\n### Approach 4: Using Array [Accepted]\n\n**Algorithm**\n\nInstead of making use of a special HashMap datastructure just to store the frequency of occurence of characters, we can use a simpler array data structure to store the frequencies. Given strings contains only lowercase alphabets ('a' to 'z'). So we need to take an array of size 26.The rest of the process remains the same as the last approach.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/YTLoQomr/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"YTLoQomr\"></iframe>\n\n**Complexity Analysis**\n\nLet $$l_1$$ be the length of string $$s_1$$ and $$l_2$$ be the length of string $$s_2$$.\n\n* Time complexity: $O(l_1 + (26 + l_1) \\cdot (l_2 - l_1))$\n  \n  The initialization of the array `s1arr` takes $O(l_1)$ since we loop through each character of $s_1$ once and store the counts.\n\n  The outer loop runs $(l_2 - l_1 + 1)$ times, as we need to consider each possible substring of length $l_1$ within $s_2$.\n\n  For each iteration of the outer loop, we build `s2arr`, which takes $O(l_1)$ time (since we process $l_1$ characters for each substring in $s_2$).\n\n  In the `matches` function, we iterate through `s1arr` to compare it with `s2arr`. This takes $O(26) = O(1)$, as the alphabet size is constant (26 characters). Thus, checking equality of the two maps involves a constant-time comparison for each character in the alphabet.\n\n  Thus, the total time complexity becomes: $O(l_1 + (26 + l_1) \\cdot (l_2 - l_1))$.\n\n* Space complexity: $O(l_2 - l_1)$\n  \n  Each substring from $s_2$ of length $l_1$ creates a array (`s2arr`) to store the character frequencies.\n\n  The size of this array is $O(26)$, since there are at most 26 characters in the alphabet.\n  \n  Over $l_2 - l_1 + 1$ iterations of the outer loop, we create one such array per iteration, resulting in $O(26 \\cdot (l_2 - l_1 + 1))$ space usage.\n\n  We also create a array for $s_1$ (`s1arr`), which similarly takes $O(26)$ space.\n  \n  Since we need to store a array for each of the $l_2 - l_1 + 1$ substrings in the worst case, the space complexity is proportional to the number of substrings and the size of each array. \n  \n  Therefore, the total space complexity is: $O(26 \\cdot (l_2 - l_1 + 1) + 26) = O(26 \\cdot (l_2 - l_1 + 1))$. In simplified terms: $O(l_2 - l_1)$\n\n---\n### Approach 5: Sliding Window  [Accepted]:\n\n**Algorithm**\n\nInstead of building a new hashmap from scratch for every window we check in $$s2$$, we can just set up a fixed-size array of length 26 once for the first window in $$s2$$. Then, as we slide the window over, we can simply update it. Basically, we’ll remove the character that's no longer in the window and add the new one that’s now part of it. So, the array gets tweaked only at the two spots related to those two characters. Each time we update the array, we just compare all the elements to check if everything matches up for the result we want.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/VaR6ouAa/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VaR6ouAa\"></iframe>\n\n**Complexity Analysis**\n   \nLet $$l_1$$ be the length of string $$s_1$$ and $$l_2$$ be the length of string $$s_2$$.\n\n* Time complexity: $O(l_1 + 26 \\cdot (l_2 - l_1)) = O(l_1 + (l_2 - l_1)) = O(l_2)$\n\n  The loop that populates two frequency arrays runs for $l_1$ iterations, as it processes all characters in $s_1$ and the first $l_1$ characters in $s_2$. This step takes $O(l_1)$ time.\n\n  The outer loop runs $l_2 - l_1$ times, sliding the window of size $l_1$ across $s_2$. For each iteration, two operations are performed:\n     - Increment the count of the new character added to the window (`s2arr[s2.charAt(i + l_1) - 'a']++`).\n     - Decrement the count of the character leaving the window (`s2arr[s2.charAt(i) - 'a']--`).\n  Both of these operations are constant-time, $O(1)$, for each iteration since the arrays are of fixed size (26). Thus, the time complexity for this part is $O(l_2 - l_1)$.\n\n  The `matches` function compares the two arrays element by element, which takes $O(26) = O(1)$ time because the arrays have a fixed size of 26.\n \n  Combining the preprocessing and sliding window steps, the total time complexity is: $O(l_1 + 26 \\cdot (l_2 - l_1))$\n\n  Since $26$ is a constant, this simplifies to: $O(l_1 + (l_2 - l_1)) = O(l_2)$\n\n* Space complexity: $O(26 + 26) = O(1)$\n  \n  Two arrays, `s1arr` and `s2arr`, are used to store character frequencies. Each array has a fixed size of 26, regardless of the lengths of $s_1$ and $s_2$. Therefore, the space used for these arrays is $O(26 + 26) = O(52) = O(1)$.\n\n  No other data structures that depend on the size of $s_1$ or $s_2$ are used. The space required is constant, independent of the input size.\n\n  Thus, the total space complexity is: $O(1)$\n\n---\n### Approach 6: Optimized Sliding Window [Accepted]:\n\n**Algorithm**\n\nThe last approach can be optimized, if instead of comparing all the elements of the `s1arr` for every updated `s2arr` corresponding to every window of $$s2$$ considered, we keep a track of the number of elements which were already matching in the `s1arr` and update just the count of matching elements when we shift the window towards the right.\n\nTo do so, we maintain a `count` variable, which stores the number of characters(out of the 26 alphabets), which have the same frequency of occurence in $$s1$$ and the current window in $$s2$$. When we slide the window, if the deduction of the last element and the addition of the new element leads to a new frequency match of any of the characters, we increment the `count` by 1. If not, we keep the `count` intact. But, if a character whose frequency was the same earlier(prior to addition and removal) is added, it now leads to a frequency mismatch which is taken into account by decrementing the same `count` variable. If, after the shifting of the window, the `count` evaluates to 26, it means all the characters match in frequency totally. So, we return a True in that case immediately.\n\n**Implementation**\n    \n<iframe src=\"https://leetcode.com/playground/FhVsu6SM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"FhVsu6SM\"></iframe>\n\n**Complexity Analysis**\n\nLet $$l_1$$ be the length of string $$s_1$$ and $$l_2$$ be the length of string $$s_2$$.\n\n* Time complexity: $O(l_1 + (l_2 - l_1)) \\approx O(l_2)$\n\n  Populating `s1arr` and `s2arr` takes $O(l_1)$ time since we iterate over the first $l_1$ characters of both strings.\n\n  The outer loop runs $l_2 - l_1$ times. In each iteration, we update two characters (one entering and one leaving the window) in constant time $O(1)$, and we maintain a count of matches. This step takes $O(l_2 - l_1)$.\n\n  Checking if `count == 26` also happens in $O(1)$, since it's a constant comparison.\n\n  Thus, the total time complexity is: $O(l_1 + (l_2 - l_1)) \\approx O(l_2)$\n\n* Space complexity: $$O(1)$$\n  \n  Two fixed-size arrays (`s1arr` and `s2arr`) of size 26 are used for counting character frequencies. No additional space that grows with the input size is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  bool checkInclusion(string s1, string s2) {\n    vector<int> count(128);\n    int required = s1.length();\n\n    for (const char c : s1)\n      ++count[c];\n\n    for (int r = 0; r < s2.length(); ++r) {\n      if (--count[s2[r]] >= 0)\n        --required;\n      if (r >= s1.length())  // The window is oversized\n        if (++count[s2[r - s1.length()]] > 0)\n          ++required;\n      if (required == 0)\n        return true;\n    }\n\n    return false;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkInclusion(String s1, String s2) {\n    int[] count = new int[128];\n    int required = s1.length();\n\n    for (final char c : s1.toCharArray())\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s2.length(); ++r) {\n      if (--count[s2.charAt(r)] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 == s1.length())\n          return true;\n        if (++count[s2.charAt(l++)] > 0)\n          ++required;\n      }\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkInclusion(string s1, string s2) {\n    vector<int> count(128);\n    int required = s1.length();\n\n    for (const char c : s1)\n      ++count[c];\n\n    for (int l = 0, r = 0; r < s2.length(); ++r) {\n      if (--count[s2[r]] >= 0)\n        --required;\n      while (required == 0) {\n        if (r - l + 1 == s1.length())\n          return true;\n        if (++count[s2[l++]] > 0)\n          ++required;\n      }\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/567.html",
    "category": "Algorithms",
    "acceptance_rate": 47.094242306200115,
    "topics": [
      "Hash Table",
      "Two Pointers",
      "String",
      "Sliding Window"
    ],
    "hints": [
      "Obviously, brute force will result in TLE. Think of something else.",
      "How will you check whether one string is a permutation of another string?",
      "One way is to sort the string and then compare. But, Is there a better way?",
      "If one string is a permutation of another string then they must have one common metric. What is that?",
      "Both strings must have same character frequencies, if  one is permutation of another. Which data structure should be used to store frequencies?",
      "What about hash table?  An array of size 26?"
    ],
    "likes": 12272,
    "dislikes": 482,
    "similar_questions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find All Anagrams in a String\", \"titleSlug\": \"find-all-anagrams-in-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1200502, \"totalSubmissionRaw\": 2549154, \"acRate\": \"47.1%\"}",
    "title_pt": "Permutação em String",
    "description_pt": "<p>Dadas duas strings <code>s1</code> e <code>s2</code>, retorne <code>true</code> se <code>s2</code> contiver uma <span data-keyword=\"permutation-string\">permutação</span> de <code>s1</code>, ou <code>false</code> caso contrário.</p>\n\n<p>Em outras palavras, retorne <code>true</code> se uma das permutações de <code>s1</code> for a substring de <code>s2</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidbaooo&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> s2 contém uma permutação de s1 (&quot;ba&quot;).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;ab&quot;, s2 = &quot;eidboaoo&quot;\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Obviamente, a força bruta resultará em TLE. Pense em outra coisa.",
      "- Dica 2: Como você verificará se uma string é uma permutação de outra string?",
      "- Dica 3: Uma maneira é ordenar a string e então comparar. Mas existe uma forma melhor?",
      "- Dica 4: Se uma string for uma permutação de outra string, então elas devem ter uma métrica em comum. Qual é essa?",
      "- Dica 5: Ambas as strings devem ter as mesmas frequências de caracteres, se uma for permutação da outra. Qual estrutura de dados deve ser usada para armazenar frequências?",
      "- Dica 6: E quanto a uma tabela hash? Um array de tamanho 26?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "570",
    "paidOnly": false,
    "title": "Managers with at Least 5 Direct Reports",
    "titleSlug": "managers-with-at-least-5-direct-reports",
    "url": "https://leetcode.com/problems/managers-with-at-least-5-direct-reports",
    "description_url": "https://leetcode.com/problems/managers-with-at-least-5-direct-reports/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| department  | varchar |\n| managerId   | int     |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the name of an employee, their department, and the id of their manager.\nIf managerId is null, then the employee does not have a manager.\nNo employee will be the manager of themself.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find managers with at least <strong>five direct reports</strong>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+-----+-------+------------+-----------+\n| id  | name  | department | managerId |\n+-----+-------+------------+-----------+\n| 101 | John  | A          | null      |\n| 102 | Dan   | A          | 101       |\n| 103 | James | A          | 101       |\n| 104 | Amy   | A          | 101       |\n| 105 | Anne  | A          | 101       |\n| 106 | Ron   | B          | 101       |\n+-----+-------+------------+-----------+\n<strong>Output:</strong> \n+------+\n| name |\n+------+\n| John |\n+------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/managers-with-at-least-5-direct-reports/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/570.html",
    "category": "Database",
    "acceptance_rate": 48.946140909159894,
    "topics": [
      "Database"
    ],
    "hints": [
      "Try to get all the mangerIDs that have count bigger than 5",
      "Use the last hint's result as a table and do join with origin table at id equals to managerId",
      "This is a very good example to show the performance of SQL code. Try to work out other solutions and you may be surprised by running time difference.",
      "If your solution uses 'IN' function and runs more than 5 seconds, try to optimize it by using 'JOIN' instead."
    ],
    "likes": 1441,
    "dislikes": 162,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"677.2K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 677233, \"totalSubmissionRaw\": 1383626, \"acRate\": \"48.9%\"}",
    "title_pt": "Gerentes com Pelo Menos 5 Relatórios Diretos",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| department  | varchar |\n| managerId   | int     |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the name of an employee, their department, and the id of their manager.\nIf managerId is null, then the employee does not have a manager.\nNo employee will be the manager of themself.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar gerentes com pelo menos <strong>cinco relatórios diretos</strong>.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nEmployee table:\n+-----+-------+------------+-----------+\n| id  | name  | department | managerId |\n+-----+-------+------------+-----------+\n| 101 | John  | A          | null      |\n| 102 | Dan   | A          | 101       |\n| 103 | James | A          | 101       |\n| 104 | Amy   | A          | 101       |\n| 105 | Anne  | A          | 101       |\n| 106 | Ron   | B          | 101       |\n+-----+-------+------------+-----------+\n<strong>Saída:</strong> \n+------+\n| name |\n+------+\n| John |\n+------+\n</pre>",
    "hints_pt": [
      "- Dica 1: Tente obter todos os managerIDs que tenham contagem maior que 5",
      "- Dica 2: Use o resultado da última dica como uma tabela e faça o join com a tabela original onde id é igual a managerId",
      "- Dica 3: Este é um exemplo muito bom para mostrar o desempenho do código SQL. Tente elaborar outras soluções e você pode se surpreender com a diferença no tempo de execução.",
      "- Dica 4: Se a sua solução usa a função 'IN' e executa por mais de 5 segundos, tente otimizá-la usando 'JOIN' em vez disso."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "572",
    "paidOnly": false,
    "title": "Subtree of Another Tree",
    "titleSlug": "subtree-of-another-tree",
    "url": "https://leetcode.com/problems/subtree-of-another-tree",
    "description_url": "https://leetcode.com/problems/subtree-of-another-tree/description/",
    "description": "<p>Given the roots of two binary trees <code>root</code> and <code>subRoot</code>, return <code>true</code> if there is a subtree of <code>root</code> with the same structure and node values of<code> subRoot</code> and <code>false</code> otherwise.</p>\n\n<p>A subtree of a binary tree <code>tree</code> is a tree that consists of a node in <code>tree</code> and all of this node&#39;s descendants. The tree <code>tree</code> could also be considered as a subtree of itself.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg\" style=\"width: 532px; height: 400px;\" />\n<pre>\n<strong>Input:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg\" style=\"width: 502px; height: 458px;\" />\n<pre>\n<strong>Input:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the <code>root</code> tree is in the range <code>[1, 2000]</code>.</li>\n\t<li>The number of nodes in the <code>subRoot</code> tree is in the range <code>[1, 1000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= root.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= subRoot.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/subtree-of-another-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isSubtree(TreeNode s, TreeNode t) {\n    if (s == null)\n      return false;\n    if (isSameTree(s, t))\n      return true;\n    return isSubtree(s.left, t) || isSubtree(s.right, t);\n  }\n\n  private boolean isSameTree(TreeNode p, TreeNode q) {\n    if (p == null || q == null)\n      return p == q;\n    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isSubtree(TreeNode* s, TreeNode* t) {\n    if (s == nullptr)\n      return false;\n    if (isSameTree(s, t))\n      return true;\n    return isSubtree(s->left, t) || isSubtree(s->right, t);\n  }\n\n private:\n  bool isSameTree(TreeNode* p, TreeNode* q) {\n    if (!p || !q)\n      return p == q;\n    return p->val == q->val &&\n           isSameTree(p->left, q->left) &&\n           isSameTree(p->right, q->right);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/572.html",
    "category": "Algorithms",
    "acceptance_rate": 49.803170092071554,
    "topics": [
      "Tree",
      "Depth-First Search",
      "String Matching",
      "Binary Tree",
      "Hash Function"
    ],
    "hints": [
      "Which approach is better here- recursive or iterative?",
      "If recursive approach is better, can you write recursive function with its parameters?",
      "Two trees <b>s</b> and <b>t</b> are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae?",
      "Recursive formulae can be: \r\nisIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)"
    ],
    "likes": 8542,
    "dislikes": 564,
    "similar_questions": "[{\"title\": \"Count Univalue Subtrees\", \"titleSlug\": \"count-univalue-subtrees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Subtree Sum\", \"titleSlug\": \"most-frequent-subtree-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1052821, \"totalSubmissionRaw\": 2113976, \"acRate\": \"49.8%\"}",
    "title_pt": "Subárvore de Outra Árvore",
    "description_pt": "<p>Dadas as raízes de duas árvores binárias <code>root</code> e <code>subRoot</code>, retorne <code>true</code> se existir uma subárvore de <code>root</code> com a mesma estrutura e os valores dos nós de<code> subRoot</code>, e <code>false</code> caso contrário.</p>\n\n<p>Uma subárvore de uma árvore binária <code>tree</code> é uma árvore que consiste em um nó em <code>tree</code> e todos os descendentes desse nó. A árvore <code>tree</code> também pode ser considerada uma subárvore de si mesma.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/subtree1-tree.jpg\" style=\"width: 532px; height: 400px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,4,5,1,2], subRoot = [4,1,2]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/subtree2-tree.jpg\" style=\"width: 502px; height: 458px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore <code>root</code> está no intervalo <code>[1, 2000]</code>.</li>\n\t<li>O número de nós na árvore <code>subRoot</code> está no intervalo <code>[1, 1000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= root.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= subRoot.val &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Qual abordagem é melhor aqui — recursiva ou iterativa?",
      "Dica 2: Se a abordagem recursiva for melhor, você consegue escrever uma função recursiva com seus parâmetros?",
      "Dica 3: Duas árvores <b>s</b> e <b>t</b> são consideradas idênticas se seus valores de raiz forem iguais e suas subárvores esquerda e direita forem idênticas. Você consegue escrever isso na forma de fórmulas recursivas?",
      "Dica 4: As fórmulas recursivas podem ser: \r\nisIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "575",
    "paidOnly": false,
    "title": "Distribute Candies",
    "titleSlug": "distribute-candies",
    "url": "https://leetcode.com/problems/distribute-candies",
    "description_url": "https://leetcode.com/problems/distribute-candies/description/",
    "description": "<p>Alice has <code>n</code> candies, where the <code>i<sup>th</sup></code> candy is of type <code>candyType[i]</code>. Alice noticed that she started to gain weight, so she visited a doctor.</p>\n\n<p>The doctor advised Alice to only eat <code>n / 2</code> of the candies she has (<code>n</code> is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor&#39;s advice.</p>\n\n<p>Given the integer array <code>candyType</code> of length <code>n</code>, return <em>the <strong>maximum</strong> number of different types of candies she can eat if she only eats </em><code>n / 2</code><em> of them</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> candyType = [1,1,2,2,3,3]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> candyType = [1,1,2,3]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> candyType = [6,6,6,6]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == candyType.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>n</code>&nbsp;is even.</li>\n\t<li><code>-10<sup>5</sup> &lt;= candyType[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/distribute-candies/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def distributeCandies(self, candies: List[int]) -> int:\n    return min(len(candies) // 2, len(set(candies)))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int distributeCandies(int[] candies) {\n    BitSet bitset = new BitSet(200001);\n\n    for (final int candy : candies)\n      bitset.set(candy + 100000);\n\n    return Math.min(candies.length / 2, bitset.cardinality());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int distributeCandies(vector<int>& candies) {\n    bitset<200001> bitset;\n\n    for (const int candy : candies)\n      bitset.set(candy + 100000);\n\n    return min(candies.size() / 2, bitset.count());\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/575.html",
    "category": "Algorithms",
    "acceptance_rate": 69.37932923327223,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [
      "To maximize the number of kinds of candies, we should try to distribute candies such that Alice will gain all kinds.",
      "What is the upper limit of the number of kinds of candies Alice will gain? Remember candies are to distributed equally.",
      "Which data structure is the most suitable for finding the number of kinds of candies?",
      "Will hashset solves the problem? Inserting all candies kind in the hashset and then checking its size with upper limit."
    ],
    "likes": 1631,
    "dislikes": 1414,
    "similar_questions": "[{\"title\": \"Minimum Number of Operations to Satisfy Conditions\", \"titleSlug\": \"minimum-number-of-operations-to-satisfy-conditions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check if Grid Satisfies Conditions\", \"titleSlug\": \"check-if-grid-satisfies-conditions\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"339.4K\", \"totalSubmission\": \"489.3K\", \"totalAcceptedRaw\": 339443, \"totalSubmissionRaw\": 489258, \"acRate\": \"69.4%\"}",
    "title_pt": "Distribuir Doces",
    "description_pt": "<p>Alice tem <code>n</code> doces, em que o doce <code>i<sup>th</sup></code> é do tipo <code>candyType[i]</code>. Alice percebeu que começou a engordar, então visitou um médico.</p>\n\n<p>O médico aconselhou Alice a comer apenas <code>n / 2</code> dos doces que ela tem (<code>n</code> é sempre par). Alice gosta muito de seus doces e quer comer o maior número possível de tipos diferentes de doces, enquanto ainda segue o conselho do médico.</p>\n\n<p>Dado o array inteiro <code>candyType</code> de comprimento <code>n</code>, retorne <em>o número <strong>máximo</strong> de tipos diferentes de doces que ela pode comer se ela comer apenas </em><code>n / 2</code><em> deles</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candyType = [1,1,2,2,3,3]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Alice só pode comer 6 / 2 = 3 doces. Como existem apenas 3 tipos, ela pode comer um de cada tipo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candyType = [1,1,2,3]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Alice só pode comer 4 / 2 = 2 doces. Quer ela coma os tipos [1,2], [1,3] ou [2,3], ela ainda só pode comer 2 tipos diferentes.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> candyType = [6,6,6,6]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Alice só pode comer 4 / 2 = 2 doces. Mesmo podendo comer 2 doces, ela só tem 1 tipo.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == candyType.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>n</code>&nbsp;é par.</li>\n\t<li><code>-10<sup>5</sup> &lt;= candyType[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Para maximizar o número de tipos de doces, devemos tentar distribuir os doces de forma que Alice obtenha todos os tipos.",
      "Dica 2: Qual é o limite superior do número de tipos de doces que Alice obterá? Lembre-se de que os doces devem ser distribuídos igualmente.",
      "Dica 3: Qual estrutura de dados é a mais adequada para encontrar o número de tipos de doces?",
      "Dica 4: Um hashset resolve o problema? Inserindo todos os tipos de doces no hashset e então verificando seu tamanho com o limite superior."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "576",
    "paidOnly": false,
    "title": "Out of Boundary Paths",
    "titleSlug": "out-of-boundary-paths",
    "url": "https://leetcode.com/problems/out-of-boundary-paths",
    "description_url": "https://leetcode.com/problems/out-of-boundary-paths/description/",
    "description": "<p>There is an <code>m x n</code> grid with a ball. The ball is initially at the position <code>[startRow, startColumn]</code>. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply <strong>at most</strong> <code>maxMove</code> moves to the ball.</p>\n\n<p>Given the five integers <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code>, <code>startColumn</code>, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png\" style=\"width: 500px; height: 296px;\" />\n<pre>\n<strong>Input:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\n<strong>Output:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png\" style=\"width: 500px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\n<strong>Output:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>0 &lt;= maxMove &lt;= 50</code></li>\n\t<li><code>0 &lt;= startRow &lt; m</code></li>\n\t<li><code>0 &lt;= startColumn &lt; n</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/out-of-boundary-paths/solutions/",
    "solution": "[TOC]\n## Summary\n\n\n\n## Solution\n\n---\n### Approach 1: Brute Force\n\n**Algorithm**\n\nIn the brute force approach, we try to take one step in every direction and decrement the number of pending moves for each step taken. Whenever we reach out of the boundary while taking the steps, we deduce that one extra path is available to take the ball out. \n\nIn order to implement the same, we make use of a recursive function `findPaths(m,n,N,i,j)` which takes the current number of moves($$N$$) along with the current position($$(i,j)$$ as some of the parameters and returns the number of moves possible to take the ball out with the current pending moves from the current position. Now, we take a step in every direction and update the corresponding indices involved along with the current number of pending moves. \n\nFurther, if we run out of moves at any moment, we return a 0 indicating that the current set of moves doesn't take the ball out of boundary.\n\n<iframe src=\"https://leetcode.com/playground/EdwZjt6g/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"EdwZjt6g\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(4^n)$$. Size of recursion tree will be $$4^n$$. Here, $$n$$ refers to the number of moves allowed.\n\n* Space complexity : $$O(n)$$. The depth of the recursion tree can go upto $$n$$.\n\n---\n### Approach 2: Recursion with Memoization\n\n**Algorithm**\n\nIn the brute force approach, while going through the various branches of the recursion tree, we could reach the same position with the same number of moves left. \n\nThus, a lot of redundant function calls are made with the same set of parameters leading to a useless increase in runtime. We can remove this redundancy by making use of a memoization array, $$memo$$. $$memo[i][j][k]$$ is used to store the number of possible moves leading to a path out of the boundary if the current position is given by the indices $$(i, j)$$ and number of moves left is $$k$$. \n\nThus, now if a function call with some parameters is repeated, the $$memo$$ array will already contain valid values corresponding to that function call resulting in pruning of the search space.\n\n<iframe src=\"https://leetcode.com/playground/8NApVNQk/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"8NApVNQk\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(mnN)$$. We need to fill the $$memo$$ array once with dimensions $$m \\times n \\times N$$. Here, $$m$$, $$n$$ refer to the number of rows and columns of the given grid respectively. $$N$$ refers to the total number of allowed moves.\n\n* Space complexity : $$O(mnN)$$. $$memo$$ array of size $$m \\times n \\times N$$ is used.\n\n---\n\n### Approach 3: Dynamic Programming\n\n**Algorithm**\n\nThe idea behind this approach is that if we can reach some position in $$x$$ moves, we can reach all its adjacent positions in $$x+1$$ moves. Based on this idea, we make use of a 2-D $$dp$$ array to store the number of ways in which a particular position can be reached. $$dp[i][j]$$ refers to the number of ways the position corresponding to the indices $$(i,j)$$ can be reached given some particular number of moves.\n\nNow, if the current $$dp$$ array stores the number of ways the various positions can be reached by making use of $$x-1$$ moves, in order to determine the number of ways the position $$(i,j)$$ can be reached by making use of $$x$$ moves, we need to update the corresponding $$dp$$ entry as $$dp[i][j] = dp[i-1][j] + dp[i+1][j] + dp[i][j-1] + dp[i][j+1]$$ taking care of boundary conditions. This happens because we can reach the index $$(i,j)$$ from any of the four adjacent positions and the total number of ways of reaching the index $$(i,j)$$ in $$x$$ moves is the sum of the ways of reaching the adjacent positions in $$x-1$$ moves. \n\nBut, if we alter the $$dp$$ array, now some of the entries will correspond to $$x-1$$ moves and the updated ones will correspond to $$x$$ moves. Thus, we need to find a way to tackle this issue. So, instead of updating the $$dp$$ array for the current($$x$$) moves, we make use of a temporary 2-D array $$temp$$ to store the updated results for $$x$$ moves, making use of the results obtained for $$dp$$ array corresponding to $$x-1$$ moves. After all the entries for all the positions have been considered for $$x$$ moves, we update the $$dp$$ array based on $$temp$$. Thus, $$dp$$ now contains the entries corresponding to $$x$$ moves.\n\nThus, we start off by considering zero move available for which we make an initial entry of $$dp[x][y] = 1$$($$(x,y)$$ is the initial position), since we can reach only this position in zero move. Then, we increase the number of moves to 1 and update all the $$dp$$ entries appropriately. We do so for all the moves possible from 1 to N. \n\nIn order to update $$count$$, which indicates the total number of possible moves which lead an out of boundary path, we need to perform the update only when we reach the boundary. We update the count as $$count = count + dp[i][j]$$, where $$(i,j)$$ corresponds to one of the boundaries. But, if $$(i,j)$$ is simultaneously a part of multiple boundaries, we need to add the $$dp[i][j]$$ factor multiple times(same as the number of boundaries to which $$(i,j)$$ belongs).\n\nAfter we are done with all the $$N$$ moves, $$count$$ gives the required result.\n\nThe following animation illustrates the process:\n\n!?!../Documents/576_Boundary_Paths.json:1000,563!?!\n\n\n<iframe src=\"https://leetcode.com/playground/mkUawRuw/shared\" frameBorder=\"0\" width=\"100%\" height=\"480\" name=\"mkUawRuw\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(Nmn)$$. We need to fill the $$dp$$ array with dimensions $$m \\times n$$ $$N$$ times. Here $$m \\times n$$ refers to the size of the grid and $$N$$ refers to the number of moves available.\n\n* Space complexity : $$O(mn)$$. $$dp$$ and $$temp$$ array of size $$m \\times n$$ are used.",
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n    constexpr int kMod = 1'000'000'007;\n    const vector<int> dirs{0, 1, 0, -1, 0};\n    int ans = 0;\n    // dp[i][j] := # of paths to move the ball (i, j) out of bound\n    vector<vector<int>> dp(m, vector<int>(n));\n    dp[startRow][startColumn] = 1;\n\n    while (maxMove--) {\n      vector<vector<int>> newDp(m, vector<int>(n));\n      for (int r = 0; r < m; ++r)\n        for (int c = 0; c < n; ++c)\n          if (dp[r][c] > 0)\n            for (int k = 0; k < 4; ++k) {\n              const int x = r + dirs[k];\n              const int y = c + dirs[k + 1];\n              if (x < 0 || x == m || y < 0 || y == n)\n                ans = (ans + dp[r][c]) % kMod;\n              else\n                newDp[x][y] = (newDp[x][y] + dp[r][c]) % kMod;\n            }\n      dp = move(newDp);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n    this.m = m;\n    this.n = n;\n    // dp[k][i][j] := # of paths to move the ball (i, j) out of bound w/ k moves\n    dp = new Integer[maxMove + 1][m][n];\n    return findPaths(maxMove, startRow, startColumn);\n  }\n\n  private static final int kMod = 1_000_000_007;\n  private int m;\n  private int n;\n  private Integer[][][] dp;\n\n  private int findPaths(int k, int i, int j) {\n    if (i < 0 || i == m || j < 0 || j == n)\n      return 1;\n    if (k == 0)\n      return 0;\n    if (dp[k][i][j] != null)\n      return dp[k][i][j];\n    return dp[k][i][j] = ((findPaths(k - 1, i + 1, j) + findPaths(k - 1, i - 1, j)) % kMod +\n                          (findPaths(k - 1, i, j + 1) + findPaths(k - 1, i, j - 1)) % kMod) %\n                         kMod;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {\n    this->m = m;\n    this->n = n;\n    // dp[k][i][j] := # of paths to move the ball (i, j) out of bound w/ k moves\n    dp.resize(maxMove + 1, vector<vector<int>>(m, vector<int>(n, -1)));\n    return findPaths(maxMove, startRow, startColumn);\n  }\n\n private:\n  constexpr static int kMod = 1'000'000'007;\n  int m;\n  int n;\n  vector<vector<vector<int>>> dp;\n\n  int findPaths(int k, int i, int j) {\n    if (i < 0 || i == m || j < 0 || j == n)\n      return 1;\n    if (k == 0)\n      return 0;\n    if (dp[k][i][j] != -1)\n      return dp[k][i][j];\n    return dp[k][i][j] =\n      ((findPaths(k - 1, i + 1, j) + findPaths(k - 1, i - 1, j)) % kMod +\n       (findPaths(k - 1, i, j + 1) + findPaths(k - 1, i, j - 1)) % kMod) %\n        kMod;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/576.html",
    "category": "Algorithms",
    "acceptance_rate": 48.129519987503,
    "topics": [
      "Dynamic Programming"
    ],
    "hints": [
      "Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it.",
      "Can we use some space to store the number of paths and update them after every move?",
      "One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways.\r\n\r\nCan you use this thing to solve the problem?"
    ],
    "likes": 3930,
    "dislikes": 295,
    "similar_questions": "[{\"title\": \"Knight Probability in Chessboard\", \"titleSlug\": \"knight-probability-in-chessboard\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Execution of All Suffix Instructions Staying in a Grid\", \"titleSlug\": \"execution-of-all-suffix-instructions-staying-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"218.8K\", \"totalSubmission\": \"454.5K\", \"totalAcceptedRaw\": 218753, \"totalSubmissionRaw\": 454509, \"acRate\": \"48.1%\"}",
    "title_pt": "Caminhos Fora dos Limites",
    "description_pt": "<p>Há uma grade <code>m x n</code> com uma bola. A bola está inicialmente na posição <code>[startRow, startColumn]</code>. Você pode mover a bola para uma das quatro células adjacentes na grade (possivelmente para fora da grade, cruzando o limite da grade). Você pode aplicar <strong>no máximo</strong> <code>maxMove</code> movimentos à bola.</p>\n\n<p>Dados os cinco inteiros <code>m</code>, <code>n</code>, <code>maxMove</code>, <code>startRow</code> e <code>startColumn</code>, retorne o número de caminhos para mover a bola para fora do limite da grade. Como a resposta pode ser muito grande, retorne-a <strong>módulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_1.png\" style=\"width: 500px; height: 296px;\" />\n<pre>\n<strong>Entrada:</strong> m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\n<strong>Saída:</strong> 6\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/out_of_boundary_paths_2.png\" style=\"width: 500px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\n<strong>Saída:</strong> 12\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>0 &lt;= maxMove &lt;= 50</code></li>\n\t<li><code>0 &lt;= startRow &lt; m</code></li>\n\t<li><code>0 &lt;= startColumn &lt; n</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Percorrer cada caminho é viável? Há muitos caminhos possíveis para uma matriz pequena. Tente otimizá-lo.",
      "Dica 2: Podemos usar algum espaço para armazenar o número de caminhos e atualizá-los após cada movimento?",
      "Dica 3: Uma coisa óbvia: a bola só sairá do limite ao cruzá-lo. Além disso, existe apenas uma forma possível de a bola sair do limite a partir de uma célula na borda, exceto para células de canto. A partir da célula de canto, a bola pode sair de duas formas diferentes.\n\nVocê pode usar isso para resolver o problema?"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "577",
    "paidOnly": false,
    "title": "Employee Bonus",
    "titleSlug": "employee-bonus",
    "url": "https://leetcode.com/problems/employee-bonus",
    "description_url": "https://leetcode.com/problems/employee-bonus/description/",
    "description": "<p>Table: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| empId       | int     |\n| name        | varchar |\n| supervisor  | int     |\n| salary      | int     |\n+-------------+---------+\nempId is the column with unique values for this table.\nEach row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Bonus</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| empId       | int  |\n| bonus       | int  |\n+-------------+------+\nempId is the column of unique values for this table.\nempId is a foreign key (reference column) to empId from the Employee table.\nEach row of this table contains the id of an employee and their respective bonus.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to report the name and bonus amount of each employee with a bonus <strong>less than</strong> <code>1000</code>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nEmployee table:\n+-------+--------+------------+--------+\n| empId | name   | supervisor | salary |\n+-------+--------+------------+--------+\n| 3     | Brad   | null       | 4000   |\n| 1     | John   | 3          | 1000   |\n| 2     | Dan    | 3          | 2000   |\n| 4     | Thomas | 3          | 4000   |\n+-------+--------+------------+--------+\nBonus table:\n+-------+-------+\n| empId | bonus |\n+-------+-------+\n| 2     | 500   |\n| 4     | 2000  |\n+-------+-------+\n<strong>Output:</strong> \n+------+-------+\n| name | bonus |\n+------+-------+\n| Brad | null  |\n| John | null  |\n| Dan  | 500   |\n+------+-------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/employee-bonus/solutions/",
    "solution": "[TOC]\n\n# Solution\n\n---\n\n\n\n\n## pandas\n\n### Approach 1: Filter and Retrieve \n\n##### Algorithm\n\n1. Define the `employee_bonus` function that takes two DataFrames, `employee` and `bonus`, as input parameters and specifies that it returns a DataFrame.\n\n2. Use the Pandas merge function to combine the `employee` and `bonus` DataFrames on the `empId` column using a left join. This combines employee data with their respective bonuses.\n\n3. Apply a filter to the merged DataFrame to include only rows where the bonus is less than 1000 or where the bonus is missing (NaN). Use boolean indexing for filtering.\n\n4. Choose the `name` and `bonus` columns from the filtered DataFrame to extract the relevant information.\n\n5. Return the filtered DataFrame as the output of the function.\n\n##### Code\n\n```python\nimport pandas as pd\n\ndef employee_bonus(employee: pd.DataFrame, bonus: pd.DataFrame) -> pd.DataFrame:\n    # Merge Employee and Bonus tables using a left join\n    result_df = pd.merge(employee, bonus, on='empId', how='left')\n\n    # Filter rows where bonus is less than 1000 or missing\n    result_df = result_df[(result_df['bonus'] < 1000) | result_df['bonus'].isnull()]\n\n    # Select \"name\" and \"bonus\" columns\n    result_df = result_df[['name', 'bonus']]\n\n    return result_df\n\n\n\n```\n\n<br>\n\n## Database\n\n\n### Approach 1: Using `OUTER JOIN` and `WHERE` clause\n\n\n#### Algorithm\n\n1. Initialize Query: Start an SQL query.\n\n2. Since foreign key **Bonus.empId** refers to **Employee.empId** and some employees do not have bonus records, we can use `OUTER JOIN` to link these two tables as the first step.\n\n\n```sql\nSELECT\n    Employee.name, Bonus.bonus\nFROM\n    Employee\n        LEFT OUTER JOIN\n    Bonus ON Employee.empid = Bonus.empid\n;\n```\n>Note: \"LEFT OUTER JOIN\" could be written as \"LEFT JOIN\".\n\nThe output to run this code with the sample data is as below.\n\n```\n| name   | bonus |\n|--------|-------|\n| Dan    | 500   |\n| Thomas | 2000  |\n| Brad   |       |\n| John   |       |\n```\nThe bonus value for `Brad` and `John` is empty, which is actually `NULL` in the database. \"Conceptually, NULL means “a missing unknown value” and it is treated somewhat differently from other values.\" Check the [Working with NULL Values](https://dev.mysql.com/doc/refman/5.7/en/working-with-null.html) in MySQL manual for more details. In addition, we have to use `IS NULL` or `IS NOT NULL` to compare a value with `NULL`.\n\n3. At last, we can add a `WHERE` clause with the proper conditions to filter these records.\n\n#### Implementation\n\n```mysql []\nSELECT\n    Employee.name, Bonus.bonus\nFROM\n    Employee\n        LEFT JOIN\n    Bonus ON Employee.empid = Bonus.empid\nWHERE\n    bonus < 1000 OR bonus IS NULL\n;\n```\n\n\n<br>",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/577.html",
    "category": "Database",
    "acceptance_rate": 77.12440985666734,
    "topics": [
      "Database"
    ],
    "hints": [
      "If the EmpId in table Employee has no match in table Bonus, we consider that the corresponding bonus is null and null is smaller than 1000.",
      "Inner join is the default join, we can solve the mismatching problem by using outer join."
    ],
    "likes": 1253,
    "dislikes": 261,
    "similar_questions": "[{\"title\": \"Combine Two Tables\", \"titleSlug\": \"combine-two-tables\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"726.6K\", \"totalSubmission\": \"942.1K\", \"totalAcceptedRaw\": 726611, \"totalSubmissionRaw\": 942132, \"acRate\": \"77.1%\"}",
    "title_pt": "Bônus dos Funcionários",
    "description_pt": "<p>Tabela: <code>Employee</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| empId       | int     |\n| name        | varchar |\n| supervisor  | int     |\n| salary      | int     |\n+-------------+---------+\nempId is the column with unique values for this table.\nEach row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Bonus</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| empId       | int  |\n| bonus       | int  |\n+-------------+------+\nempId is the column of unique values for this table.\nempId is a foreign key (reference column) to empId from the Employee table.\nEach row of this table contains the id of an employee and their respective bonus.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para relatar o nome e o valor do bônus de cada funcionário com um bônus <strong>menor que</strong> <code>1000</code>.</p>\n\n<p>Retorne a tabela resultante em <strong>qualquer ordem</strong>.</p>\n\n<p>O&nbsp;formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Employee:\n+-------+--------+------------+--------+\n| empId | name   | supervisor | salary |\n+-------+--------+------------+--------+\n| 3     | Brad   | null       | 4000   |\n| 1     | John   | 3          | 1000   |\n| 2     | Dan    | 3          | 2000   |\n| 4     | Thomas | 3          | 4000   |\n+-------+--------+------------+--------+\nTabela Bonus:\n+-------+-------+\n| empId | bonus |\n+-------+-------+\n| 2     | 500   |\n| 4     | 2000  |\n+-------+-------+\n<strong>Saída:</strong> \n+------+-------+\n| name | bonus |\n+------+-------+\n| Brad | null  |\n| John | null  |\n| Dan  | 500   |\n+------+-------+\n</pre>",
    "hints_pt": [
      "Dica 1: Se o EmpId na tabela Employee não tiver correspondência na tabela Bonus, consideramos que o bônus correspondente é null e null é menor que 1000.",
      "Dica 2: Inner join é o join padrão; podemos resolver o problema de incompatibilidade usando outer join."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "581",
    "paidOnly": false,
    "title": "Shortest Unsorted Continuous Subarray",
    "titleSlug": "shortest-unsorted-continuous-subarray",
    "url": "https://leetcode.com/problems/shortest-unsorted-continuous-subarray",
    "description_url": "https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/",
    "description": "<p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.</p>\n\n<p>Return <em>the shortest such subarray and output its length</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,6,4,8,10,9,15]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?",
    "solution_url": "https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findUnsortedSubarray(self, nums: List[int]) -> int:\n    mini = math.inf\n    maxi = -math.inf\n    flag = False\n\n    for i in range(1, len(nums)):\n      if nums[i] < nums[i - 1]:\n        flag = True\n      if flag:\n        mini = min(mini, nums[i])\n\n    flag = False\n\n    for i in reversed(range(len(nums) - 1)):\n      if nums[i] > nums[i + 1]:\n        flag = True\n      if flag:\n        maxi = max(maxi, nums[i])\n\n    for l in range(len(nums)):\n      if nums[l] > mini:\n        break\n\n    for r, num in reversed(list(enumerate(nums))):\n      if num < maxi:\n        break\n\n    return 0 if l >= r else r - l + 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findUnsortedSubarray(int[] nums) {\n    final int n = nums.length;\n    int min = Integer.MAX_VALUE;\n    int max = Integer.MIN_VALUE;\n    boolean meetDecrease = false;\n    boolean meetIncrease = false;\n\n    for (int i = 1; i < n; ++i) {\n      if (nums[i] < nums[i - 1])\n        meetDecrease = true;\n      if (meetDecrease)\n        min = Math.min(min, nums[i]);\n    }\n\n    for (int i = n - 2; i >= 0; --i) {\n      if (nums[i] > nums[i + 1])\n        meetIncrease = true;\n      if (meetIncrease)\n        max = Math.max(max, nums[i]);\n    }\n\n    int l = 0;\n    for (l = 0; l < n; ++l)\n      if (nums[l] > min)\n        break;\n\n    int r = 0;\n    for (r = n - 1; r >= 0; --r)\n      if (nums[r] < max)\n        break;\n\n    return l > r ? 0 : r - l + 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findUnsortedSubarray(vector<int>& nums) {\n    const int n = nums.size();\n    int mini = INT_MAX;\n    int maxi = INT_MIN;\n    bool meetDecrease = false;\n    bool meetIncrease = false;\n\n    for (int i = 1; i < n; ++i) {\n      if (nums[i] < nums[i - 1])\n        meetDecrease = true;\n      if (meetDecrease)\n        mini = min(mini, nums[i]);\n    }\n\n    for (int i = n - 2; i >= 0; --i) {\n      if (nums[i] > nums[i + 1])\n        meetIncrease = true;\n      if (meetIncrease)\n        maxi = max(maxi, nums[i]);\n    }\n\n    int l;\n    for (l = 0; l < n; ++l)\n      if (nums[l] > mini)\n        break;\n\n    int r;\n    for (r = n - 1; r >= 0; --r)\n      if (nums[r] < maxi)\n        break;\n\n    return l < r ? r - l + 1 : 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/581.html",
    "category": "Algorithms",
    "acceptance_rate": 37.36634771816245,
    "topics": [
      "Array",
      "Two Pointers",
      "Stack",
      "Greedy",
      "Sorting",
      "Monotonic Stack"
    ],
    "hints": [],
    "likes": 7857,
    "dislikes": 271,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"356.5K\", \"totalSubmission\": \"954K\", \"totalAcceptedRaw\": 356463, \"totalSubmissionRaw\": 953968, \"acRate\": \"37.4%\"}",
    "title_pt": "Subarray Contínuo Desordenado Mais Curto",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, você precisa encontrar um <b>subarray contínuo</b> tal que, se você ordenar apenas esse subarray em ordem não decrescente, então o array inteiro ficará ordenado em ordem não decrescente.</p>\n\n<p>Retorne <em>o subarray mais curto assim e forneça o seu comprimento</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,6,4,8,10,9,15]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> Você precisa ordenar [6, 4, 8, 10, 9] em ordem crescente para fazer com que o array inteiro fique ordenado em ordem crescente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4]\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n\n<p>&nbsp;</p>\n<strong>Desafio extra:</strong> Você consegue resolver isso em complexidade de tempo <code>O(n)</code>?",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "583",
    "paidOnly": false,
    "title": "Delete Operation for Two Strings",
    "titleSlug": "delete-operation-for-two-strings",
    "url": "https://leetcode.com/problems/delete-operation-for-two-strings",
    "description_url": "https://leetcode.com/problems/delete-operation-for-two-strings/description/",
    "description": "<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p>\n\n<p>In one <strong>step</strong>, you can delete exactly one character in either string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot;\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li>\n\t<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/delete-operation-for-two-strings/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minDistance(self, word1: str, word2: str) -> int:\n    m = len(word1)\n    n = len(word2)\n    dp = [0] * (n + 1)\n\n    for j in range(n + 1):\n      dp[j] = j\n\n    for i in range(1, m + 1):\n      newDp = [i] + [0] * n\n      for j in range(1, n + 1):\n        if word1[i - 1] == word2[j - 1]:\n          newDp[j] = dp[j - 1]\n        else:\n          newDp[j] = min(newDp[j - 1], dp[j]) + 1\n      dp = newDp\n\n    return dp[n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minDistance(String word1, String word2) {\n    final int k = lcs(word1, word2);\n    return (word1.length() - k) + (word2.length() - k);\n  }\n\n  private int lcs(final String A, final String B) {\n    final int m = A.length();\n    final int n = B.length();\n    // dp[i][j] := LCS's length of A[0..i) and B[0..j)\n    int[][] dp = new int[m + 1][n + 1];\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (A.charAt(i - 1) == B.charAt(j - 1))\n          dp[i][j] = 1 + dp[i - 1][j - 1];\n        else\n          dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n\n    return dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minDistance(string word1, string word2) {\n    const int k = lcs(word1, word2);\n    return (word1.length() - k) + (word2.length() - k);\n  }\n\n private:\n  int lcs(const string& A, const string& B) {\n    const int m = A.length();\n    const int n = B.length();\n    // dp[i][j] := LCS's length of A[0..i) and B[0..j)\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (A[i - 1] == B[j - 1])\n          dp[i][j] = 1 + dp[i - 1][j - 1];\n        else\n          dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/583.html",
    "category": "Algorithms",
    "acceptance_rate": 63.46701517177923,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 5950,
    "dislikes": 90,
    "similar_questions": "[{\"title\": \"Edit Distance\", \"titleSlug\": \"edit-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum ASCII Delete Sum for Two Strings\", \"titleSlug\": \"minimum-ascii-delete-sum-for-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Common Subsequence\", \"titleSlug\": \"longest-common-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Make Three Strings Equal\", \"titleSlug\": \"make-three-strings-equal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"311.8K\", \"totalSubmission\": \"491.2K\", \"totalAcceptedRaw\": 311775, \"totalSubmissionRaw\": 491240, \"acRate\": \"63.5%\"}",
    "title_pt": "Operação de Exclusão para Duas Strings",
    "description_pt": "<p>Dadas duas strings <code>word1</code> e <code>word2</code>, retorne <em>o número mínimo de <strong>passos</strong> necessários para fazer</em> <code>word1</code> <em>e</em> <code>word2</code> <em>serem iguais</em>.</p>\n\n<p>Em um <strong>passo</strong>, você pode deletar exatamente um caractere em qualquer uma das strings.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Você precisa de um passo para transformar &quot;sea&quot; em &quot;ea&quot; e de outro passo para transformar &quot;eat&quot; em &quot;ea&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot;\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li>\n\t<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "584",
    "paidOnly": false,
    "title": "Find Customer Referee",
    "titleSlug": "find-customer-referee",
    "url": "https://leetcode.com/problems/find-customer-referee",
    "description_url": "https://leetcode.com/problems/find-customer-referee/description/",
    "description": "<p>Table: <code>Customer</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| referee_id  | int     |\n+-------------+---------+\nIn SQL, id is the primary key column for this table.\nEach row of this table indicates the id of a customer, their name, and the id of the customer who referred them.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Find the names of the customer that are <strong>not referred by</strong> the customer with <code>id = 2</code>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nCustomer table:\n+----+------+------------+\n| id | name | referee_id |\n+----+------+------------+\n| 1  | Will | null       |\n| 2  | Jane | null       |\n| 3  | Alex | 2          |\n| 4  | Bill | null       |\n| 5  | Zack | 1          |\n| 6  | Mark | 2          |\n+----+------+------------+\n<strong>Output:</strong> \n+------+\n| name |\n+------+\n| Will |\n| Jane |\n| Bill |\n| Zack |\n+------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/find-customer-referee/solutions/",
    "solution": "[TOC]\n\n## Solution\n---\n### Approach: Using `<>`(`!=`) and `IS NULL` [Accepted]\n\n**Intuition**\n\nSome people come out the following solution by intuition.\n```sql\nSELECT name FROM customer WHERE referee_Id <> 2;\n```\n\nHowever, this query will only return one result:Zack although there are 4 customers not referred by Jane (including Jane herself). All the customers who were referred by nobody at all (`NULL` value in the referee_id column) don’t show up. But why?\n\n**Algorithm**\n\nMySQL uses three-valued logic -- TRUE, FALSE and UNKNOWN. Anything compared to NULL evaluates to the third value: UNKNOWN. That “anything” includes NULL itself! That’s why MySQL provides the `IS NULL` and `IS NOT NULL` operators to specifically check for NULL.\n\nThus, one more condition 'referee_id IS NULL' should be added to the WHERE clause as below.\n\n**MySQL**\n\n```sql\nSELECT name FROM customer WHERE referee_id <> 2 OR referee_id IS NULL;\n```\nor\n```mysql\nSELECT name FROM customer WHERE referee_id != 2 OR referee_id IS NULL;\n```\n\n**Tips**\n\nThe following solution is also wrong for the same reason as mentioned above. The key is to always use `IS NULL` or `IS NOT NULL` operators to specifically check for NULL value.\n\n```sql\nSELECT name FROM customer WHERE referee_id = NULL OR referee_id <> 2;\n```",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/584.html",
    "category": "Database",
    "acceptance_rate": 71.73923715986095,
    "topics": [
      "Database"
    ],
    "hints": [
      "Be careful of the NULL value"
    ],
    "likes": 2554,
    "dislikes": 395,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1563559, \"totalSubmissionRaw\": 2179504, \"acRate\": \"71.7%\"}",
    "title_pt": "Encontrar Clientes Não Indicados pelo Referenciador",
    "description_pt": "<p>Tabela: <code>Customer</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| name        | varchar |\n| referee_id  | int     |\n+-------------+---------+\nIn SQL, id is the primary key column for this table.\nEach row of this table indicates the id of a customer, their name, and the id of the customer who referred them.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Encontre os nomes dos clientes que <strong>não foram indicados por</strong> o cliente com <code>id = 2</code>.</p>\n\n<p>Retorne a tabela resultante em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nCustomer table:\n+----+------+------------+\n| id | name | referee_id |\n+----+------+------------+\n| 1  | Will | null       |\n| 2  | Jane | null       |\n| 3  | Alex | 2          |\n| 4  | Bill | null       |\n| 5  | Zack | 1          |\n| 6  | Mark | 2          |\n+----+------+------------+\n<strong>Saída:</strong> \n+------+\n| name |\n+------+\n| Will |\n| Jane |\n| Bill |\n| Zack |\n+------+\n</pre>",
    "hints_pt": [
      "Dica 1: Tome cuidado com o valor NULL"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "585",
    "paidOnly": false,
    "title": "Investments in 2016",
    "titleSlug": "investments-in-2016",
    "url": "https://leetcode.com/problems/investments-in-2016",
    "description_url": "https://leetcode.com/problems/investments-in-2016/description/",
    "description": "<p>Table: <code>Insurance</code></p>\n\n<pre>\n+-------------+-------+\n| Column Name | Type  |\n+-------------+-------+\n| pid         | int   |\n| tiv_2015    | float |\n| tiv_2016    | float |\n| lat         | float |\n| lon         | float |\n+-------------+-------+\npid is the primary key (column with unique values) for this table.\nEach row of this table contains information about one policy where:\npid is the policyholder&#39;s policy ID.\ntiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016.\nlat is the latitude of the policy holder&#39;s city. It&#39;s guaranteed that lat is not NULL.\nlon is the longitude of the policy holder&#39;s city. It&#39;s guaranteed that lon is not NULL.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to report the sum of all total investment values in 2016 <code>tiv_2016</code>, for all policyholders who:</p>\n\n<ul>\n\t<li>have the same <code>tiv_2015</code> value as one or more other policyholders, and</li>\n\t<li>are not located in the same city as any other policyholder (i.e., the (<code>lat, lon</code>) attribute pairs must be unique).</li>\n</ul>\n\n<p>Round <code>tiv_2016</code> to <strong>two decimal places</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nInsurance table:\n+-----+----------+----------+-----+-----+\n| pid | tiv_2015 | tiv_2016 | lat | lon |\n+-----+----------+----------+-----+-----+\n| 1   | 10       | 5        | 10  | 10  |\n| 2   | 20       | 20       | 20  | 20  |\n| 3   | 10       | 30       | 20  | 20  |\n| 4   | 10       | 40       | 40  | 40  |\n+-----+----------+----------+-----+-----+\n<strong>Output:</strong> \n+----------+\n| tiv_2016 |\n+----------+\n| 45.00    |\n+----------+\n<strong>Explanation:</strong> \nThe first record in the table, like the last record, meets both of the two criteria.\nThe tiv_2015 value 10 is the same as the third and fourth records, and its location is unique.\n\nThe second record does not meet any of the two criteria. Its tiv_2015 is not like any other policyholders and its location is the same as the third record, which makes the third record fail, too.\nSo, the result is the sum of tiv_2016 of the first and last record, which is 45.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/investments-in-2016/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/585.html",
    "category": "Database",
    "acceptance_rate": 49.9597427415678,
    "topics": [
      "Database"
    ],
    "hints": [
      "Make the (LAT, LON) a pair to represent the location information"
    ],
    "likes": 726,
    "dislikes": 572,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"206K\", \"totalSubmission\": \"412.3K\", \"totalAcceptedRaw\": 206005, \"totalSubmissionRaw\": 412345, \"acRate\": \"50.0%\"}",
    "title_pt": "Investimentos em 2016",
    "description_pt": "<p>Tabela: <code>Insurance</code></p>\n\n<pre>\n+-------------+-------+\n| Nome da Coluna | Tipo  |\n+-------------+-------+\n| pid         | int   |\n| tiv_2015    | float |\n| tiv_2016    | float |\n| lat         | float |\n| lon         | float |\n+-------------+-------+\npid is the chave primária (column with unique values) for this table.\nEach row of this table contains information about one policy where:\npid is the policyholder&#39;s policy ID.\ntiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016.\nlat is the latitude of the policy holder&#39;s city. It&#39;s guaranteed that lat is not NULL.\nlon is the longitude of the policy holder&#39;s city. It&#39;s guaranteed that lon is not NULL.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para reportar a soma de todos os valores totais de investimento em 2016 <code>tiv_2016</code>, para todos os titulares de apólice que:</p>\n\n<ul>\n\t<li>tenham o mesmo valor de <code>tiv_2015</code> que um ou mais outros titulares de apólice, e</li>\n\t<li>não estejam localizados na mesma cidade que qualquer outro titular de apólice (isto é, os pares de atributos (<code>lat, lon</code>) devem ser únicos).</li>\n</ul>\n\n<p>Arredonde <code>tiv_2016</code> para <strong>duas casas decimais</strong>.</p>\n\n<p>O&nbsp;formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Insurance:\n+-----+----------+----------+-----+-----+\n| pid | tiv_2015 | tiv_2016 | lat | lon |\n+-----+----------+----------+-----+-----+\n| 1   | 10       | 5        | 10  | 10  |\n| 2   | 20       | 20       | 20  | 20  |\n| 3   | 10       | 30       | 20  | 20  |\n| 4   | 10       | 40       | 40  | 40  |\n+-----+----------+----------+-----+-----+\n<strong>Saída:</strong> \n+----------+\n| tiv_2016 |\n+----------+\n| 45.00    |\n+----------+\n<strong>Explicação:</strong> \nO primeiro registro na tabela, assim como o último registro, atende aos dois critérios.\nO valor de tiv_2015 10 é o mesmo do terceiro e do quarto registros, e sua localização é única.\n\nO segundo registro não atende a nenhum dos dois critérios. Seu tiv_2015 não é igual ao de nenhum outro titular de apólice e sua localização é a mesma do terceiro registro, o que faz o terceiro registro falhar também.\nPortanto, o resultado é a soma de tiv_2016 do primeiro e do último registro, que é 45.\n</pre>",
    "hints_pt": [
      "Dica 1: Faça de (LAT, LON) um par para representar as informações de localização"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "586",
    "paidOnly": false,
    "title": "Customer Placing the Largest Number of Orders",
    "titleSlug": "customer-placing-the-largest-number-of-orders",
    "url": "https://leetcode.com/problems/customer-placing-the-largest-number-of-orders",
    "description_url": "https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/description/",
    "description": "<p>Table: <code>Orders</code></p>\n\n<pre>\n+-----------------+----------+\n| Column Name     | Type     |\n+-----------------+----------+\n| order_number    | int      |\n| customer_number | int      |\n+-----------------+----------+\norder_number is the primary key (column with unique values) for this table.\nThis table contains information about the order ID and the customer ID.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the <code>customer_number</code> for the customer who has placed <strong>the largest number of orders</strong>.</p>\n\n<p>The test cases are generated so that <strong>exactly one customer</strong> will have placed more orders than any other customer.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nOrders table:\n+--------------+-----------------+\n| order_number | customer_number |\n+--------------+-----------------+\n| 1            | 1               |\n| 2            | 2               |\n| 3            | 3               |\n| 4            | 3               |\n+--------------+-----------------+\n<strong>Output:</strong> \n+-----------------+\n| customer_number |\n+-----------------+\n| 3               |\n+-----------------+\n<strong>Explanation:</strong> \nThe customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. \nSo the result is customer_number 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> What if more than one customer has the largest number of orders, can you find all the <code>customer_number</code> in this case?</p>\n",
    "solution_url": "https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/586.html",
    "category": "Database",
    "acceptance_rate": 64.40504064612875,
    "topics": [
      "Database"
    ],
    "hints": [
      "MySQL uses a different expression to get the first records other than MSSQL's TOP expression."
    ],
    "likes": 1056,
    "dislikes": 85,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"342.7K\", \"totalSubmission\": \"532.2K\", \"totalAcceptedRaw\": 342733, \"totalSubmissionRaw\": 532152, \"acRate\": \"64.4%\"}",
    "title_pt": "Cliente que Realizou a Maior Quantidade de Pedidos",
    "description_pt": "<p>Tabela: <code>Orders</code></p>\n\n<pre>\n+-----------------+----------+\n| Nome da Coluna  | Tipo     |\n+-----------------+----------+\n| order_number    | int      |\n| customer_number | int      |\n+-----------------+----------+\norder_number é a chave primária (coluna com valores únicos) para esta tabela.\nEsta tabela contém informações sobre o ID do pedido e o ID do cliente.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar o <code>customer_number</code> do cliente que realizou <strong>a maior quantidade de pedidos</strong>.</p>\n\n<p>Os casos de teste são gerados de forma que <strong>exatamente um cliente</strong> terá realizado mais pedidos do que qualquer outro cliente.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Orders:\n+--------------+-----------------+\n| order_number | customer_number |\n+--------------+-----------------+\n| 1            | 1               |\n| 2            | 2               |\n| 3            | 3               |\n| 4            | 3               |\n+--------------+-----------------+\n<strong>Saída:</strong> \n+-----------------+\n| customer_number |\n+-----------------+\n| 3               |\n+-----------------+\n<strong>Explicação:</strong> \nO cliente de número 3 tem dois pedidos, o que é maior do que o cliente 1 ou 2, pois cada um deles tem apenas um pedido. \nPortanto, o resultado é customer_number 3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> E se mais de um cliente tiver a maior quantidade de pedidos, você consegue encontrar todos os <code>customer_number</code> nesse caso?</p>",
    "hints_pt": [
      "Dica 1: MySQL usa uma expressão diferente para obter os primeiros registros, diferente da expressão TOP do MSSQL."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "587",
    "paidOnly": false,
    "title": "Erect the Fence",
    "titleSlug": "erect-the-fence",
    "url": "https://leetcode.com/problems/erect-the-fence",
    "description_url": "https://leetcode.com/problems/erect-the-fence/description/",
    "description": "<p>You are given an array <code>trees</code> where <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents the location of a tree in the garden.</p>\n\n<p>Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if <strong>all the trees are enclosed</strong>.</p>\n\n<p>Return <em>the coordinates of trees that are exactly located on the fence perimeter</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg\" style=\"width: 400px; height: 393px;\" />\n<pre>\n<strong>Input:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n<strong>Output:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]]\n<strong>Explanation:</strong> All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg\" style=\"width: 400px; height: 393px;\" />\n<pre>\n<strong>Input:</strong> trees = [[1,2],[2,2],[4,2]]\n<strong>Output:</strong> [[4,2],[2,2],[1,2]]\n<strong>Explanation:</strong> The fence forms a line that passes through all the trees.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= trees.length &lt;= 3000</code></li>\n\t<li><code>trees[i].length == 2</code></li>\n\t<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li>\n\t<li>All the given positions are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/erect-the-fence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n    hull = []\n\n    trees.sort(key=lambda x: (x[0], x[1]))\n\n    def cross(p: List[int], q: List[int], r: List[int]) -> int:\n      return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1])\n\n    # Build lower hull: left-to-right scan\n    for tree in trees:\n      while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:\n        hull.pop()\n      hull.append(tuple(tree))\n    hull.pop()\n\n    # Build upper hull: right-to-left scan\n    for tree in reversed(trees):\n      while len(hull) > 1 and cross(hull[-1], hull[-2], tree) > 0:\n        hull.pop()\n      hull.append(tuple(tree))\n\n    # Remove redundant elements from the stack\n    return list(set(hull))",
    "solution_code_java": "\t\t\t\n\n// Monotone Chain\nclass Solution {\n  public int[][] outerTrees(int[][] trees) {\n    Stack<int[]> hull = new Stack<>();\n\n    Arrays.sort(trees, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);\n\n    // Build lower hull: left-to-right scan\n    for (int[] tree : trees) {\n      while (hull.size() > 1 && cross(hull.peek(), hull.get(hull.size() - 2), tree) > 0)\n        hull.pop();\n      hull.push(tree);\n    }\n    hull.pop();\n\n    // Build upper hull: right-to-left scan\n    for (int i = trees.length - 1; i >= 0; --i) {\n      while (hull.size() > 1 && cross(hull.peek(), hull.get(hull.size() - 2), trees[i]) > 0)\n        hull.pop();\n      hull.push(trees[i]);\n    }\n\n    // Remove redundant elements from the stack\n    HashSet<int[]> unique = new HashSet<>(hull);\n    return unique.toArray(new int[unique.size()][]);\n  }\n\n  private int cross(int[] p, int[] q, int[] r) {\n    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\n// Monotone Chain\nclass Solution {\n public:\n  vector<vector<int>> outerTrees(vector<vector<int>>& trees) {\n    vector<vector<int>> hull;\n\n    sort(begin(trees), end(trees), [](const auto& a, const auto& b) {\n      return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0];\n    });\n\n    // Build lower hull: left-to-right scan\n    for (const auto& tree : trees) {\n      while (hull.size() > 1 &&\n             cross(hull.back(), hull[hull.size() - 2], tree) > 0)\n        hull.pop_back();\n      hull.push_back(tree);\n    }\n    hull.pop_back();\n\n    // Build upper hull: right-to-left scan\n    for (int i = trees.size() - 1; i >= 0; --i) {\n      while (hull.size() > 1 &&\n             cross(hull.back(), hull[hull.size() - 2], trees[i]) > 0)\n        hull.pop_back();\n      hull.push_back(trees[i]);\n    }\n\n    // Remove redundant elements from the stack\n    sort(begin(hull), end(hull), [](const auto& a, const auto& b) {\n      return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0];\n    });\n    hull.erase(\n        unique(begin(hull), end(hull),\n               [](const auto& a,\n                  const auto& b) { return a[0] == b[0] && a[1] == b[1]; }),\n        end(hull));\n    return hull;\n  }\n\n private:\n  int cross(const vector<int>& p, const vector<int>& q, const vector<int>& r) {\n    return (q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/587.html",
    "category": "Algorithms",
    "acceptance_rate": 52.14154110194089,
    "topics": [
      "Array",
      "Math",
      "Geometry"
    ],
    "hints": [],
    "likes": 1496,
    "dislikes": 646,
    "similar_questions": "[{\"title\": \"Erect the Fence II\", \"titleSlug\": \"erect-the-fence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sort the Students by Their Kth Score\", \"titleSlug\": \"sort-the-students-by-their-kth-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"62K\", \"totalSubmission\": \"118.9K\", \"totalAcceptedRaw\": 61977, \"totalSubmissionRaw\": 118863, \"acRate\": \"52.1%\"}",
    "title_pt": "Construir a Cerca",
    "description_pt": "<p>Você recebe um array <code>trees</code> em que <code>trees[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> representa a localização de uma árvore no jardim.</p>\n\n<p>Cerque todo o jardim usando o comprimento mínimo de corda, pois ela é cara. O jardim está bem cercado apenas se <strong>todas as árvores estiverem enclausuradas</strong>.</p>\n\n<p>Retorne <emas coordenadas das árvores que estão exatamente localizadas no perímetro da cerca</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect2-plane.jpg\" style=\"width: 400px; height: 393px;\" />\n<pre>\n<strong>Entrada:</strong> trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n<strong>Saída:</strong> [[1,1],[2,0],[4,2],[3,3],[2,4]]\n<strong>Explicação:</strong> Todas as árvores estarão no perímetro da cerca, exceto a árvore em [2, 2], que estará dentro da cerca.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/24/erect1-plane.jpg\" style=\"width: 400px; height: 393px;\" />\n<pre>\n<strong>Entrada:</strong> trees = [[1,2],[2,2],[4,2]]\n<strong>Saída:</strong> [[4,2],[2,2],[1,2]]\n<strong>Explicação:</strong> A cerca forma uma linha que passa por todas as árvores.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= trees.length &lt;= 3000</code></li>\n\t<li><code>trees[i].length == 2</code></li>\n\t<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 100</code></li>\n\t<li>Todas as posições fornecidas são <strong>únicas</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "589",
    "paidOnly": false,
    "title": "N-ary Tree Preorder Traversal",
    "titleSlug": "n-ary-tree-preorder-traversal",
    "url": "https://leetcode.com/problems/n-ary-tree-preorder-traversal",
    "description_url": "https://leetcode.com/problems/n-ary-tree-preorder-traversal/description/",
    "description": "<p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes&#39; values</em>.</p>\n\n<p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Output:</strong> [1,3,5,6,2,4]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>\n",
    "solution_url": "https://leetcode.com/problems/n-ary-tree-preorder-traversal/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> preorder(Node root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<Integer> ans = new ArrayList<>();\n    Deque<Node> stack = new ArrayDeque<>();\n    stack.push(root);\n\n    while (!stack.isEmpty()) {\n      root = stack.pop();\n      ans.add(root.val);\n      for (int i = root.children.size() - 1; i >= 0; --i)\n        stack.push(root.children.get(i));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> preorder(Node* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<int> ans;\n    stack<Node*> stack{{root}};\n\n    while (!stack.empty()) {\n      root = stack.top(), stack.pop();\n      ans.push_back(root->val);\n      for (auto it = rbegin(root->children); it != rend(root->children); ++it)\n        stack.push(*it);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/589.html",
    "category": "Algorithms",
    "acceptance_rate": 76.15351784365869,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search"
    ],
    "hints": [],
    "likes": 3213,
    "dislikes": 203,
    "similar_questions": "[{\"title\": \"Binary Tree Preorder Traversal\", \"titleSlug\": \"binary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Level Order Traversal\", \"titleSlug\": \"n-ary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Postorder Traversal\", \"titleSlug\": \"n-ary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"463.9K\", \"totalSubmission\": \"609.2K\", \"totalAcceptedRaw\": 463912, \"totalSubmissionRaw\": 609180, \"acRate\": \"76.2%\"}",
    "title_pt": "Percurso em Pré-Ordem de Árvore N-ária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore n-ária, retorne <em>o percurso em pré-ordem dos valores de seus nós</em>.</p>\n\n<p>A serialização de entrada de Nary-Tree é representada em seu percurso em ordem de nível. Cada grupo de filhos é separado pelo valor null (veja os exemplos)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<p><img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Saída:</strong> [1,3,5,6,2,4]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<p><img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" /></p>\n\n<pre>\n<strong>Entrada:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Saída:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>A altura da árvore n-ária é menor ou igual a <code>1000</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> A solução recursiva é trivial, você conseguiria fazê-la iterativamente?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "590",
    "paidOnly": false,
    "title": "N-ary Tree Postorder Traversal",
    "titleSlug": "n-ary-tree-postorder-traversal",
    "url": "https://leetcode.com/problems/n-ary-tree-postorder-traversal",
    "description_url": "https://leetcode.com/problems/n-ary-tree-postorder-traversal/description/",
    "description": "<p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes&#39; values</em>.</p>\n\n<p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" />\n<pre>\n<strong>Input:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Output:</strong> [5,6,3,2,4,1]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" />\n<pre>\n<strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>\n",
    "solution_url": "https://leetcode.com/problems/n-ary-tree-postorder-traversal/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nThe N-ary tree is a generalization of a binary tree where each node can have more than two children. In postorder traversal, the traversal order is as follows:\n\n1. Visit all the children of a node from left to right.\n2. After all the children have been visited, visit the node itself.\n\nThe problem provides the tree in a level-order traversal format, where children of a node are grouped and separated by a null value.\n\nIf you are completely unfamiliar with N-ary trees, check out this LeetCode [Explore Card](https://leetcode.com/explore/learn/card/n-ary-tree/) for an in-depth discussion.\n    \n---\n\n### Approach 1: Recursive\n\n#### Intuition\n\nBefore we explore the solution, let's visualize the postorder traversal in this slideshow:\n\n!?!../Documents/590/slideshow.json:934,902!?!\n\nLet's walk through the process using a recursive function `traversePostorder`. This function will call itself for each child of the current node, effectively breaking down the traversal into smaller, manageable subproblems. The key idea here is that recursion allows us to naturally explore the entire depth of each subtree before moving on to the next sibling subtree.\n\n1. Base Case: If the node has no children (i.e., it's a leaf node), the function simply adds the node's value to the result list.\n2. Recursive Step: For a non-leaf node, the function iterates over all its children, recursively calling `traversePostorder` on each one. After all children have been processed, the function adds the current node's value to the result list.\n\nFor example, consider an n-ary tree where the root has three children. The function will:\n- Traverse all the subtrees rooted at the first child.\n- After finishing with the first subtree, it moves to the second child and repeats the process.\n- Finally, after all subtrees have been traversed, the function adds the root node’s value to the result list.\n\nThe result list now contains the nodes' values in the correct postorder sequence.\n\nThis approach effectively mimics the natural recursive nature of postorder traversal, where the exploration of each subtree is completed before moving to the next.\n\n#### Algorithm\n\nMain method `postorder`:\n\n- Initialize a list `result` to store the postorder traversal of the nodes' values.\n- If the input `root` node is `null`, return the empty `result` list immediately. \n- Invoke the helper method `traversePostorder` to perform the postorder traversal.\n- Return `result` as our answer.\n\nHelper method `traversePostorder`:\n\n- Define a method `traversePostorder` with parameters: `currentNode` and the `postorderList` to store the result.\n- If `currentNode` is `null`, return.\n- Loop over each `childNode` of `currentNode`:\n  - Recursively call `traversePostorder` on each `childNode`.\n- Add the value of `currentNode` to `postorderList`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/U4oRxsP8/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"U4oRxsP8\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the number of nodes in the tree.\n\n- Time complexity: $O(m)$\n\n    The method `traversePostorder` visits each node in the tree exactly once. Thus, the time complexity of the algorithm is $O(m)$.\n\n- Space complexity: $O(m)$\n\n    The `traversePostorder` method uses recursion, and the maximum depth of the recursion is the height of the tree, which is $O(m)$ in the worst case (for a skewed tree).  \n\n    Thus, the space complexity of the algorithm is also $O(m)$.\n\n---\n\n### Approach 2: Iterative (Explicit Reversal)\n\n#### Intuition\n\nIn contrast to the recursive method, implementing an iterative approach for postorder traversal in an n-ary tree presents a challenge. The recursive method naturally processes nodes in a bottom-up manner, but this behavior doesn't translate directly to an iterative stack-based approach, since a stack processes elements in a last-in-first-out (LIFO) order.\n\nTo achieve postorder traversal iteratively, we can adopt a method that initially resembles preorder traversal but with some modifications.\n\n1. Simulate Preorder with Stack: We start by pushing the root node onto the stack. As long as the stack isn’t empty, we pop the top element, add it to the result list, and then push all its children onto the stack from left to right.\n   \n   - This order means that when children are popped from the stack for further evaluation, they come out in the reverse order (right to left). Thus, at this point, our traversal order is root -> right-to-left children.\n\n2. Reverse the Result: After the entire tree has been processed, and the stack is empty, the result list will reflect the reverse of what we want. By reversing this result list, we obtain the correct postorder traversal, where each node’s children are fully processed before the node itself.\n\nThis approach leverages the stack to mimic the recursive behavior, but because of the LIFO nature of the stack, we reverse the result at the end to achieve the desired postorder sequence. Although this method doesn't traverse the tree in a strict postorder manner, it remains a valid solution since the problem only requires the correct order in the final result.\n\n#### Algorithm\n \n- Create a list `result` to store the postorder traversal of the nodes' values.\n- If the input `root` node is `null`, return the empty result list immediately.\n- Initialize a `stack` and push the root node onto it. This stack will be used to traverse the tree.\n- While the `stack` is not empty:\n  - Pop a node from `stack` and assign it to a variable `currentNode`.\n  - Add the value of `currentNode` to `result`.\n  - Iterate through the `children` of `currentNode`. For each `child` node:\n    - Push `child` onto the `stack`.\n- Reverse the `result` list.\n- Return `result` as our answer.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/LAiQ7Az3/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"LAiQ7Az3\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the number of nodes in the tree.\n\n* Time complexity: $O(m)$\n\n    The main loop iterates over every node in the tree, taking $O(m)$ time. Each stack operation inside the loop takes constant time. Reversing the `result` list takes an additional linear time.\n\n    Thus, the overall time complexity of the algorithm is $O(m)$.\n\n* Space complexity: $O(m)$\n\n    In the worst case, if the tree is highly unbalanced (e.g., a skewed tree), the stack can grow to store all nodes at once, contributing $O(m)$ to the space complexity. No other additional data structures are used. \n\n    Thus, the space complexity of the algorithm is $O(m)$.\n---\n\n### Approach 3: Iterative (Two Stacks)\n\n#### Intuition\n\nThis approach refines the iterative method by utilizing two stacks to better manage the order in which nodes are processed, ultimately eliminating the need to reverse the result at the end. \n\nIn this method, we use two stacks: `nodeStack` for the main traversal and `reverseStack` to temporarily hold the nodes in reverse order before they are added to the final result. \n\nWe start by pushing the `root` node onto the `nodeStack`. As long as `nodeStack` is not empty, we proceed with the following steps.\n   \nWe pop the top node from `nodeStack`. Instead of adding it directly to the result list (as its children haven't been processed yet), we push it onto `reverseStack`. This postpones the addition of the node to the final result, allowing us to process its children first.\n\nNow we iterate over the children of the current node from left to right, pushing each child onto `nodeStack`. Due to the LIFO nature of stacks, these children will be popped and processed in the reverse order (right to left). As a result, the nodes in `reverseStack` will eventually be ordered such that when we pop them, we get the correct postorder sequence: children from left to right, followed by their parent node.\n\nAfter processing all nodes, `reverseStack` will contain the nodes in postorder, but in reverse order. We then simply pop elements from `reverseStack` one by one and add them to our result list. This ensures that the final list is in the correct postorder sequence.\n\n#### Algorithm\n \n- Initialize a list `result` to store the postorder traversal of the nodes' values.\n- If the input `root` node is `null`, return the empty `result` list immediately.\n- Initialize two stacks: `nodeStack` for traversal and `reverseStack` to store nodes in reverse order.\n- Push `root` onto the `nodeStack` to start the traversal.\n- While `nodeStack` is not empty:\n  - Pop a node `currentNode` from the `nodeStack`.\n  - Push `currentNode` onto `reverseStack`.\n  - Iterate through the `children` of `currentNode`. For each node `child`:\n    - Push each `child` onto `nodeStack` to ensure they are processed in the subsequent iterations.\n- While `reverseStack` is not empty:\n  - Pop a node from `reverseStack` and assign it to `currentNode`.\n  - Add the value of `currentNode` to `result`.\n- Return the `result` list.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/29SXBMBk/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"29SXBMBk\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the number of nodes in the tree.\n\n* Time complexity: $O(m)$\n\n    The first loop iterates over each node in the tree exactly once. Each node is pushed onto `nodeStack` and then moved to `reverseStack`. Since each node is processed exactly once, the time complexity for this loop is $O(m)$.\n\n    The second loop also processes each node exactly once, adding their values to the `result` list. This loop has a time complexity of $O(m)$.\n\n    Thus, the overall time complexity of the algorithm is $O(m) + O(m) = O(m)$.\n\n* Space complexity: $O(m)$\n\n    The `nodeStack` and `reverseStack` can each hold up to $m$ nodes in the worst case. This makes the space complexity of the algorithm $O(m)$.\n\n---\n\n### Approach 4: Iterative (Without Reverse)\n\n#### Intuition\n\nIn this approach, we aim to closely mimic the natural flow of recursion using a single stack, avoiding the need to reverse the final result by carefully managing when nodes are added to the result list.\n\nTo replicate the recursive process, we need to simulate the behavior where each node is visited twice: first when we encounter it initially and later after all its children have been processed. The key idea here is to use a flag to track whether a node has been visited once before adding it to the result list.\n\nWe start by pushing the root node onto the stack with a `visited` flag set to `false`. This flag indicates whether the node has been fully processed (i.e., whether its children have been visited).\n\nAs we iterate, we pop the top element from the stack and check its `visited` flag:\n   - First Encounter (`visited` = `false`): If this is the first time we're seeing this node, we update its flag to `true` and push it back onto the stack. Then, we push all its children onto the stack from right to left. This ensures that when we revisit these nodes, they will be processed in left-to-right order.\n   \n   - Second Encounter (`visited` = `true`): When the node is encountered again (after its children have been processed), we add it to the result list. This step corresponds to the natural postorder sequence, where a node is added to the result after all its children have been visited.\n\nBy the time the stack is empty, all nodes will have been processed in the correct postorder sequence, and the result list will reflect the correct traversal without the need for any additional reversal.\n\n#### Algorithm\n \n- Create a list `result` to store the postorder traversal of the nodes' values.\n- If the input `root` node is `null`, return the empty `result` list immediately.\n- Create a stack `nodeStack` of type `NodeVisitPair` that will hold pairs of nodes and their visit status.\n- Push the `root` node onto the stack with `isVisited` set to `false`, indicating that the node has not yet been fully processed.\n- While `nodeStack` is not empty:\n  - Pop a pair from the `nodeStack` and assign it to `currentPair`.\n  - If `currentPair.isVisited` is `true`, add the node's value to `result`.\n  - Else, set `currentPair.isVisited` to `true` and push `currentPair` back onto the stack.\n  - Retrieve the children of the current node and set it to a list `children`.\n  - Iterate over `children` in reverse order and push each child onto the stack.\n- Return `result`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/nW2cReWj/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"nW2cReWj\"></iframe>\n\n#### Complexity Analysis\n\nLet $m$ be the number of nodes in the tree.\n\n* Time complexity: $O(m)$\n\n    Each node is pushed onto the stack twice: once with `isVisited = false` and once with `isVisited = true`. Consequently, each node is popped from the stack twice. Overall, this makes the time complexity of the algorithm $O(4 \\cdot m) = O(m)$.\n\n* Space complexity: $O(m)$\n\n    The `nodeStack` will, in the worst case (for a skewed tree), contain all `m` nodes of the tree. Each entry in the stack takes constant space. \n\n    Thus, the space complexity of the algorithm is $O(m)$.\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> postorder(Node root) {\n    if (root == null)\n      return new ArrayList<>();\n\n    List<Integer> ans = new ArrayList<>();\n    Deque<Node> stack = new ArrayDeque<>();\n    stack.push(root);\n\n    while (!stack.isEmpty()) {\n      root = stack.pop();\n      ans.add(root.val);\n      for (Node child : root.children)\n        stack.push(child);\n    }\n\n    Collections.reverse(ans);\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> postorder(Node* root) {\n    if (root == nullptr)\n      return {};\n\n    vector<int> ans;\n    stack<Node*> stack{{root}};\n\n    while (!stack.empty()) {\n      root = stack.top(), stack.pop();\n      ans.push_back(root->val);\n      for (Node* child : root->children)\n        stack.push(child);\n    }\n\n    reverse(begin(ans), end(ans));\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/590.html",
    "category": "Algorithms",
    "acceptance_rate": 80.6282860306875,
    "topics": [
      "Stack",
      "Tree",
      "Depth-First Search"
    ],
    "hints": [],
    "likes": 2704,
    "dislikes": 119,
    "similar_questions": "[{\"title\": \"Binary Tree Postorder Traversal\", \"titleSlug\": \"binary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Level Order Traversal\", \"titleSlug\": \"n-ary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Preorder Traversal\", \"titleSlug\": \"n-ary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"398.3K\", \"totalSubmission\": \"493.9K\", \"totalAcceptedRaw\": 398259, \"totalSubmissionRaw\": 493945, \"acRate\": \"80.6%\"}",
    "title_pt": "Travessia em Pós-Ordem de Árvore N-ária",
    "description_pt": "<p>Dado o <code>root</code> de uma árvore n-ária, retorne <em>a travessia em pós-ordem dos valores de seus nós</em>.</p>\n\n<p>A serialização de entrada da Nary-Tree é representada em sua travessia em ordem de nível. Cada grupo de filhos é separado pelo valor null (Veja os exemplos)</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png\" style=\"width: 100%; max-width: 300px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,null,3,2,4,null,5,6]\n<strong>Saída:</strong> [5,6,3,2,4,1]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png\" style=\"width: 296px; height: 241px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n<strong>Saída:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>A altura da árvore n-ária é menor ou igual a <code>1000</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> A solução recursiva é trivial, você conseguiria fazê-la iterativamente?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "591",
    "paidOnly": false,
    "title": "Tag Validator",
    "titleSlug": "tag-validator",
    "url": "https://leetcode.com/problems/tag-validator",
    "description_url": "https://leetcode.com/problems/tag-validator/description/",
    "description": "<p>Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.</p>\n\n<p>A code snippet is valid if all the following rules hold:</p>\n\n<ol>\n\t<li>The code must be wrapped in a <b>valid closed tag</b>. Otherwise, the code is invalid.</li>\n\t<li>A <b>closed tag</b> (not necessarily valid) has exactly the following format : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Among them, <code>&lt;TAG_NAME&gt;</code> is the start tag, and <code>&lt;/TAG_NAME&gt;</code> is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is <b>valid</b> if and only if the TAG_NAME and TAG_CONTENT are valid.</li>\n\t<li>A <b>valid</b> <code>TAG_NAME</code> only contain <b>upper-case letters</b>, and has length in range [1,9]. Otherwise, the <code>TAG_NAME</code> is <b>invalid</b>.</li>\n\t<li>A <b>valid</b> <code>TAG_CONTENT</code> may contain other <b>valid closed tags</b>, <b>cdata</b> and any characters (see note1) <b>EXCEPT</b> unmatched <code>&lt;</code>, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the <code>TAG_CONTENT</code> is <b>invalid</b>.</li>\n\t<li>A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.</li>\n\t<li>A <code>&lt;</code> is unmatched if you cannot find a subsequent <code>&gt;</code>. And when you find a <code>&lt;</code> or <code>&lt;/</code>, all the subsequent characters until the next <code>&gt;</code> should be parsed as TAG_NAME (not necessarily valid).</li>\n\t<li>The cdata has the following format : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. The range of <code>CDATA_CONTENT</code> is defined as the characters between <code>&lt;![CDATA[</code> and the <b>first subsequent</b> <code>]]&gt;</code>.</li>\n\t<li><code>CDATA_CONTENT</code> may contain <b>any characters</b>. The function of cdata is to forbid the validator to parse <code>CDATA_CONTENT</code>, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as <b>regular characters</b>.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> \nThe code is wrapped in a closed tag : &lt;DIV&gt; and &lt;/DIV&gt;. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> code = &quot;&lt;DIV&gt;&gt;&gt;  ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong>\nWe first separate the code into : start_tag|tag_content|end_tag.\nstart_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b>\nend_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b>\ntag_content could also be separated into : text1|cdata|text2.\ntext1 -&gt; <b>&quot;&gt;&gt;  ![cdata[]] &quot;</b>\ncdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, where the CDATA_CONTENT is <b>&quot;&lt;div&gt;]&gt;&quot;</b>\ntext2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b>\nThe reason why start_tag is NOT <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> is because of the rule 6.\nThe reason why cdata is NOT <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> is because of the rule 7.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> code = &quot;&lt;A&gt;  &lt;B&gt; &lt;/A&gt;   &lt;/B&gt;&quot;\n<strong>Output:</strong> false\n<strong>Explanation:</strong> Unbalanced. If &quot;&lt;A&gt;&quot; is closed, then &quot;&lt;B&gt;&quot; must be unmatched, and vice versa.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= code.length &lt;= 500</code></li>\n\t<li><code>code</code> consists of English letters, digits, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, and <code>&#39; &#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/tag-validator/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Stack\n\nSummarizing the given problem, we can say that we need to determine whether a tag is valid or not, by checking the following properties.\n\n1. The code should be wrapped in a valid closed tag.\n\n2. The `TAG_NAME` should be valid.\n\n3. The `TAG_CONTENT` should be valid.\n\n4. The **cdata** should be valid.\n\n5. All the tags should be closed. i.e. each start-tag should have a corresponding end-tag and vice-versa and the order of the tags should be correct as well.\n\nIn order to check the validity of all these, firstly, we need to identify which parts of the given $$code$$ string act as which part from the above-mentioned categories. To understand how it's done, we'll go through the implementation and the reasoning behind it step by step.\n\nWe iterate over the given $$code$$ string. Whenever a `<` is encountered(unless we are currently inside `<![CDATA[...]]>`), it indicates the beginning of either a `TAG_NAME`(start tag or end tag) or the beginning of cdata as per the conditions given in the problem statement. \n\nIf the character immediately following this `<` is an `!`, the characters following this `<` can't be a part of a valid `TAG_NAME`, since only upper-case letters(in case of a start tag) or `/` followed by upper-case letters(in the case of an end tag). Thus, the choice now narrows down to only **cdata**. Thus, we need to check if the current bunch of characters following `<!`(including it) constitute a valid **cdata**. To do this, firstly we find out the first matching `]]>` following the current `<!` to mark the ending of **cdata**. If no such matching `]]>` exists, the $$code$$ string is considered as invalid. Apart from this, the `<!` should also be immediately followed by `CDATA[` for the **cdata** to be valid. The characters lying inside the  `<![CDATA[` and `]]>` do not have any constraints on them.\n\nIf the character immediately following the `<` encountered isn't an `!`, this `<` can only mark the beginning of `TAG_NAME`. Now, since a valid start tag can't contain anything except upper-case letters if a `/` is found after `<`, the `</` pair indicates the beginning of an end tag. Now, when a `<` refers to the beginning of a `TAG_NAME`(either start-tag or end-tag), we find out the first closing `>` following the `<` to find out the substring(say $$s$$), that constitutes the `TAG_NAME`. This $$s$$ should satisfy all the criteria to constitute a valid `TAG_NAME`. Thus, for every such $$s$$, we check if it contains all upper-case letters and also check its length(It should be between 1 to 9). If any of the criteria isn't fulfilled, $$s$$ doesn't constitute a valid `TAG_NAME`. Hence, the $$code$$ string turns out to be invalid as well.\n\nApart from checking the validity of the `TAG_NAME`, we also need to ensure that the tags always exist in pairs. i.e. for every start-tag, a corresponding end-tag should always exist. Further, we can note that in case of multiple `TAG_NAME`'s, the `TAG_NAME` whose start-tag comes later than the other ones, should have its end-tag appearing before the end-tags of those other `TAG_NAME`'s. i.e. the tag that starts later should end first. \n\nFrom this, we get the intuition that we can make use of a $$stack$$ to check the existence of matching start and end-tags. Thus, whenever we find out a valid start-tag, as mentioned above, we push its `TAG_NAME` string onto a $$stack$$. Now, whenever an end-tag is found, we compare its `TAG_NAME` with the `TAG_NAME` at the top of the $$stack$$ and remove this element from the $$stack$$. If the two don't match, this implies that either the current end-tag has no corresponding start-tag or there is a problem with the ordering of the tags. The two need to match for the tag-pair to be valid since there can't exist an end-tag without a corresponding start-tag and vice-versa. Thus, if a match isn't found, we can conclude that the given $$code$$ string is invalid.\n\nNow, after the complete $$code$$ string has been traversed, the $$stack$$ should be empty if all the start-tags have their corresponding end-tags as well. If the $$stack$$ isn't empty, this implies that some start-tag doesn't have the corresponding end-tag, violating the closed-tag's validity condition.\n\nFurther, we also need to ensure that the given $$code$$ is completely enclosed within closed tags. For this, we need to ensure that the first **cdata** found is also inside the closed tags. Thus, when we find a possibility of the presence of **cdata**, we proceed further only if we've already found a start tag, indicated by a non-empty stack. Further, to ensure that no data lies after the last end-tag, we need to ensure that the $$stack$$ doesn't become empty before we reach the end of the given $$code$$ string since an empty $$stack$$ indicates that the last end-tag has been encountered.\n\nThe following animation depicts the process.\n\n!?!../Documents/Tag_Validator_Stack.json:1000,563!?!\n\n\n<iframe src=\"https://leetcode.com/playground/akLDftNr/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"akLDftNr\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. We traverse over the given $$code$$ string of length $$n$$.\n\n* Space complexity : $$O(n)$$. The stack can grow upto a size of $$n/3$$ in the worst case. e.g. In case of `<A><B><C><D>`, $$n$$=12 and number of tags = 12/3 = 4.\n<br>\n<br>\n\n---\n### Approach 2: Regex\n\nInstead of manually checking the given $$code$$ string for checking the validity of `TAG_NAME`, `TAG_CONTENT` and **cdata**, we can make use of an inbuilt java functionality known as regular expressions.\n\nA regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. The most common quantifiers used in regular expressions are listed below. A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed to occur.\n\n`?`\tThe question mark indicates zero or one occurrence of the preceding element. For example, colou?r matches both \"color\" and \"colour\".\n\n`*`\tThe asterisk indicates zero or more occurrences of the preceding element. For example, ab*c matches \"ac\", \"abc\", \"abbc\", \"abbbc\", and so on.\n\n`+`\tThe plus sign indicates one or more occurrences of the preceding element. For example, ab+c matches \"abc\", \"abbc\", \"abbbc\", and so on, but not \"ac\".\n\n`{n}` The preceding item is matched exactly **n** times.\n\n`{min,}` The preceding item is matched **min** or more times.\n\n`{min,max}`\tThe preceding item is matched at least **min** times, but not more than **max** times.\n\n`|` A vertical bar separates alternatives. For example, gray|grey can match \"gray\" or \"grey\".\n\n`()` Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gray|grey and gr(a|e)y are equivalent patterns that both describe the set of \"gray\" or \"grey\".\n\n`[...]`\tMatches any single character in brackets.\n\n`[^...]`\tMatches any single character not in brackets.\n\nThus, by making use of regex, we can directly check the validity of the $$code$$ string directly(except the nesting of the inner tags) by using the regex expression below:\n\n`<([A-Z]{1,9})>([^<]*((<\\/?[A-Z]{1,9}>)|(<!\\[CDATA\\[(.*?)]]>))?[^<]*)*<\\/\\1>`\n\nThe image below shows the portion of the string that each part of the expression helps to match:\n\n![Regex](../Figures/591/591_Tag_Validator.PNG)\n\n\n\nBut, if we make use of back-referencing as mentioned above, the matching process takes a very large amount of CPU time. Thus, we use the regex only to check the validity of the `TAG_CONTENT`, `TAG_NAME` and the **cdata**. We check the presence of the outermost closed tags by making use of a $$stack$$ as done in the last approach.\n\nThe rest of the process remains the same as in the last approach, except that we need not manually check the validity of `TAG_CONTENT`, `TAG_NAME`, and the **cdata**, since it is already done by the regex expression. We only need to check the presence of inner closed tags.\n\nCheck [this](http://regexr.com/) link for testing any regular expression on a sample text.\n\n<iframe src=\"https://leetcode.com/playground/Pzdftc9z/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Pzdftc9z\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: Regular Expressions are/can be implemented in the form of finite-state machines. Thus, the time complexity is dependent on the internal representation. In the case of any suggestions, please comment below.\n\n* Space complexity: $$O(n)$$. The stack can grow up to a size of $$n/3$$ in the worst case. e.g. In case of `<A><B><C><D>`, $$n$$=12 and number of tags = 12/3 = 4.\n<br>\n<br>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isValid(self, code: str) -> bool:\n    if code[0] != '<' or code[-1] != '>':\n      return False\n\n    containsTag = False\n    stack = []\n\n    def isValidCdata(s: str) -> bool:\n      return s.find('[CDATA[') == 0\n\n    def isValidTagName(tagName: str, isEndTag: bool) -> bool:\n      nonlocal containsTag\n      if not tagName or len(tagName) > 9:\n        return False\n      if any(not c.isupper() for c in tagName):\n        return False\n\n      if isEndTag:\n        return stack and stack.pop() == tagName\n\n      containsTag = True\n      stack.append(tagName)\n      return True\n\n    i = 0\n    while i < len(code):\n      if not stack and containsTag:\n        return False\n      if code[i] == '<':\n        # Inside a tag, so we can check if it's a cdata\n        if stack and code[i + 1] == '!':\n          closeIndex = code.find(']]>', i + 2)\n          if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]):\n            return False\n        elif code[i + 1] == '/':  # End tag\n          closeIndex = code.find('>', i + 2)\n          if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True):\n            return False\n        else:  # Start tag\n          closeIndex = code.find('>', i + 1)\n          if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False):\n            return False\n        i = closeIndex\n      i += 1\n\n    return not stack and containsTag",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isValid(String code) {\n    if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>')\n      return false;\n\n    Deque<String> stack = new ArrayDeque<>();\n\n    for (int i = 0; i < code.length(); ++i) {\n      int closeIndex = 0;\n      if (stack.isEmpty() && containsTag)\n        return false;\n      if (code.charAt(i) == '<') {\n        // Inside a tag, so we can check if it's a cdata\n        if (!stack.isEmpty() && code.charAt(i + 1) == '!') {\n          closeIndex = code.indexOf(\"]]>\", i + 2);\n          if (closeIndex < 0 || !isValidCdata(code.substring(i + 2, closeIndex)))\n            return false;\n        } else if (code.charAt(i + 1) == '/') { // End tag\n          closeIndex = code.indexOf('>', i + 2);\n          if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 2, closeIndex), true))\n            return false;\n        } else { // Start tag\n          closeIndex = code.indexOf('>', i + 1);\n          if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 1, closeIndex), false))\n            return false;\n        }\n        i = closeIndex;\n      }\n    }\n\n    return stack.isEmpty() && containsTag;\n  }\n\n  private boolean containsTag = false;\n\n  private boolean isValidCdata(final String s) {\n    return s.indexOf(\"[CDATA[\") == 0;\n  }\n\n  private boolean isValidTagName(Deque<String> stack, String tagName, boolean isEndTag) {\n    if (tagName.isEmpty() || tagName.length() > 9)\n      return false;\n\n    for (final char c : tagName.toCharArray())\n      if (!Character.isUpperCase(c))\n        return false;\n\n    if (isEndTag)\n      return !stack.isEmpty() && stack.pop().equals(tagName);\n\n    containsTag = true;\n    stack.push(tagName);\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isValid(string code) {\n    if (code[0] != '<' || code.back() != '>')\n      return false;\n\n    stack<string> stack;\n\n    for (int i = 0; i < code.length(); ++i) {\n      int closeIndex = 0;\n      if (stack.empty() && containsTag)\n        return false;\n      if (code[i] == '<') {\n        // Inside a tag, so we can check if it's a cdata\n        if (!stack.empty() && code[i + 1] == '!') {\n          closeIndex = code.find(\"]]>\", i + 2);\n          if (closeIndex == string::npos ||\n              !isValidCdata(code.substr(i + 2, closeIndex - i - 2)))\n            return false;\n        } else if (code[i + 1] == '/') {  // End tag\n          closeIndex = code.find('>', i + 2);\n          if (closeIndex == string::npos ||\n              !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2),\n                              true))\n            return false;\n        } else {  // Start tag\n          closeIndex = code.find('>', i + 1);\n          if (closeIndex == string::npos ||\n              !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1),\n                              false))\n            return false;\n        }\n        i = closeIndex;\n      }\n    }\n\n    return stack.empty() && containsTag;\n  }\n\n private:\n  bool containsTag = false;\n\n  bool isValidCdata(const string& s) {\n    return s.find(\"[CDATA[\") == 0;\n  }\n\n  bool isValidTagName(stack<string>& stack, const string& tagName,\n                      bool isEndTag) {\n    if (tagName.empty() || tagName.length() > 9)\n      return false;\n\n    for (const char c : tagName)\n      if (!isupper(c))\n        return false;\n\n    if (isEndTag) {\n      if (stack.empty())\n        return false;\n      if (stack.top() != tagName)\n        return false;\n      stack.pop();\n      return true;\n    }\n\n    containsTag = true;\n    stack.push(tagName);\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/591.html",
    "category": "Algorithms",
    "acceptance_rate": 38.892909621247014,
    "topics": [
      "String",
      "Stack"
    ],
    "hints": [],
    "likes": 174,
    "dislikes": 652,
    "similar_questions": "[{\"title\": \"Add Bold Tag in String\", \"titleSlug\": \"add-bold-tag-in-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"17.7K\", \"totalSubmission\": \"45.6K\", \"totalAcceptedRaw\": 17734, \"totalSubmissionRaw\": 45597, \"acRate\": \"38.9%\"}",
    "title_pt": "Validador de Tags",
    "description_pt": "<p>Dada uma string que representa um trecho de código, implemente um validador de tags para analisar o código e retornar se ele é válido.</p>\n\n<p>Um trecho de código é válido se todas as seguintes regras forem verdadeiras:</p>\n\n<ol>\n\t<li>O código deve estar envolvido por uma <b>tag fechada válida</b>. Caso contrário, o código é inválido.</li>\n\t<li>Uma <b>tag fechada</b> (não necessariamente válida) tem exatamente o seguinte formato : <code>&lt;TAG_NAME&gt;TAG_CONTENT&lt;/TAG_NAME&gt;</code>. Entre eles, <code>&lt;TAG_NAME&gt;</code> é a tag de abertura, e <code>&lt;/TAG_NAME&gt;</code> é a tag de fechamento. O TAG_NAME nas tags de abertura e fechamento deve ser o mesmo. Uma tag fechada é <b>válida</b> se e somente se o TAG_NAME e o TAG_CONTENT forem válidos.</li>\n\t<li>Um <b>válido</b> <code>TAG_NAME</code> contém apenas <b>letras maiúsculas</b>, e tem comprimento no intervalo [1,9]. Caso contrário, o <code>TAG_NAME</code> é <b>inválido</b>.</li>\n\t<li>Um <b>válido</b> <code>TAG_CONTENT</code> pode conter outras <b>tags fechadas válidas</b>, <b>cdata</b> e quaisquer caracteres (veja a nota1) <b>EXCETO</b> <code>&lt;</code> sem correspondente, tag de abertura e fechamento sem correspondente, e tags sem correspondente ou tags fechadas com TAG_NAME inválido. Caso contrário, o <code>TAG_CONTENT</code> é <b>inválido</b>.</li>\n\t<li>Uma tag de abertura está sem correspondente se não existir nenhuma tag de fechamento com o mesmo TAG_NAME, e vice-versa. No entanto, você também precisa considerar a questão do desbalanceamento quando as tags estão aninhadas.</li>\n\t<li>Um <code>&lt;</code> está sem correspondente se você não conseguir encontrar um <code>&gt;</code> subsequente. E quando você encontrar um <code>&lt;</code> ou <code>&lt;/</code>, todos os caracteres subsequentes até o próximo <code>&gt;</code> devem ser analisados como TAG_NAME (não necessariamente válido).</li>\n\t<li>O cdata tem o seguinte formato : <code>&lt;![CDATA[CDATA_CONTENT]]&gt;</code>. O intervalo de <code>CDATA_CONTENT</code> é definido como os caracteres entre <code>&lt;![CDATA[</code> e o <b>primeiro</b> <code>]]&gt;</code> subsequente.</li>\n\t<li><code>CDATA_CONTENT</code> pode conter <b>quaisquer caracteres</b>. A função do cdata é impedir que o validador analise <code>CDATA_CONTENT</code>, então mesmo que ele tenha alguns caracteres que possam ser analisados como tag (não importa se válidos ou inválidos), você deve tratá-los como <b>caracteres regulares</b>.</li>\n</ol>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> code = &quot;&lt;DIV&gt;This is the first line &lt;![CDATA[&lt;div&gt;]]&gt;&lt;/DIV&gt;&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> \nO código está envolvido por uma tag fechada : &lt;DIV&gt; e &lt;/DIV&gt;. \nO TAG_NAME é válido, o TAG_CONTENT consiste em alguns caracteres e cdata. \nEmbora CDATA_CONTENT tenha uma tag de abertura sem correspondente com TAG_NAME inválido, ele deve ser considerado como texto puro, não analisado como uma tag.\nPortanto, TAG_CONTENT é válido, e então o código é válido. Assim, retorne true.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> code = &quot;&lt;DIV&gt;&gt;&gt;  ![cdata[]] &lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&gt;]&lt;/DIV&gt;&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong>\nPrimeiro separamos o código em : start_tag|tag_content|end_tag.\nstart_tag -&gt; <b>&quot;&lt;DIV&gt;&quot;</b>\nend_tag -&gt; <b>&quot;&lt;/DIV&gt;&quot;</b>\ntag_content também pode ser separado em : text1|cdata|text2.\ntext1 -&gt; <b>&quot;&gt;&gt;  ![cdata[]] &quot;</b>\ncdata -&gt; <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;&quot;</b>, onde o CDATA_CONTENT é <b>&quot;&lt;div&gt;]&gt;&quot;</b>\ntext2 -&gt; <b>&quot;]]&gt;&gt;]&quot;</b>\nA razão pela qual start_tag NÃO é <b>&quot;&lt;DIV&gt;&gt;&gt;&quot;</b> é por causa da regra 6.\nA razão pela qual cdata NÃO é <b>&quot;&lt;![CDATA[&lt;div&gt;]&gt;]]&gt;]]&gt;&quot;</b> é por causa da regra 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> code = &quot;&lt;A&gt;  &lt;B&gt; &lt;/A&gt;   &lt;/B&gt;&quot;\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Desbalanceado. Se &quot;&lt;A&gt;&quot; for fechado, então &quot;&lt;B&gt;&quot; deve estar sem correspondente, e vice-versa.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= code.length &lt;= 500</code></li>\n\t<li><code>code</code> consiste em letras do inglês, dígitos, <code>&#39;&lt;&#39;</code>, <code>&#39;&gt;&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;!&#39;</code>, <code>&#39;[&#39;</code>, <code>&#39;]&#39;</code>, <code>&#39;.&#39;</code>, e <code>&#39; &#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "592",
    "paidOnly": false,
    "title": "Fraction Addition and Subtraction",
    "titleSlug": "fraction-addition-and-subtraction",
    "url": "https://leetcode.com/problems/fraction-addition-and-subtraction",
    "description_url": "https://leetcode.com/problems/fraction-addition-and-subtraction/description/",
    "description": "<p>Given a string <code>expression</code> representing an expression of fraction addition and subtraction, return the calculation result in string format.</p>\n\n<p>The final result should be an <a href=\"https://en.wikipedia.org/wiki/Irreducible_fraction\" target=\"_blank\">irreducible fraction</a>. If your final result is an integer, change it to the format of a fraction that has a denominator <code>1</code>. So in this case, <code>2</code> should be converted to <code>2/1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> expression = &quot;-1/2+1/2&quot;\n<strong>Output:</strong> &quot;0/1&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> expression = &quot;-1/2+1/2+1/3&quot;\n<strong>Output:</strong> &quot;1/3&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> expression = &quot;1/3-1/2&quot;\n<strong>Output:</strong> &quot;-1/6&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The input string only contains <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> and <code>&#39;-&#39;</code>. So does the output.</li>\n\t<li>Each fraction (input and output) has the format <code>&plusmn;numerator/denominator</code>. If the first input fraction or the output is positive, then <code>&#39;+&#39;</code> will be omitted.</li>\n\t<li>The input only contains valid <strong>irreducible fractions</strong>, where the <strong>numerator</strong> and <strong>denominator</strong> of each fraction will always be in the range <code>[1, 10]</code>. If the denominator is <code>1</code>, it means this fraction is actually an integer in a fraction format defined above.</li>\n\t<li>The number of given fractions will be in the range <code>[1, 10]</code>.</li>\n\t<li>The numerator and denominator of the <strong>final result</strong> are guaranteed to be valid and in the range of <strong>32-bit</strong> int.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/fraction-addition-and-subtraction/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a string `expression` that contains a series of fraction additions and subtractions. Our task is to evaluate the expression and return the result as a simplified fraction in its irreducible form, meaning the fraction cannot be reduced further.  \n\nTo achieve this, we need to:  \n1. Parse the string `expression` to extract individual fractions and their corresponding operators (addition or subtraction).  \n2. Perform the arithmetic operations on these fractions.  \n3. Simplify the resulting fraction to its irreducible form using the greatest common divisor (GCD).  \n\n### Approach 1: Manual Parsing + Common Denominator \n\n### Intuition\n\nOne way to approach this question is to manually parse the `expression` string to extract each fraction’s numerator and denominator. As we parse each fraction, we can update a running total of the result fraction by adding or subtracting the current fraction from it.  \n\nTo add or subtract fractions, we need to find a common denominator between the currently parsed fraction and the running result. A straightforward approach is to use the product of the two denominators as the common denominator. This allows us to rewrite both fractions with this common denominator and then perform the addition or subtraction.  \n\nFor example, given two fractions:  \n- Current fraction: $\\frac{\\text{currNum}}{\\text{currDenom}}$  \n\n- Running result: $\\frac{\\text{num}}{\\text{denom}}$  \n\nWe can express their sum as:  \n\n$\\text{newNum} = \\text{currNum} \\times \\text{denom} + \\text{num} \\times \\text{currDenom}$\n\n$\\text{newDenom} = \\text{currDenom} \\times \\text{denom}$\n\nAfter we finish processing all fractions, the resulting fraction may not be in its simplest form. To simplify it, we divide the numerator and the denominator by their greatest common divisor (GCD). The GCD can be efficiently calculated using Euclid’s Algorithm, which is based on the recursive formula: \n \n$\\text{gcd}(a, b) = \\text{gcd}(b \\mod a, a)$\nwith base case $\\text{gcd}(0, b) = b$.  \n\nGiven `expression = \"1/3-1/2+1/6\"`, we parse and calculate as follows:\n- First fraction parsed: $\\frac{1}{3}$  \n- Second fraction parsed: $\\frac{-1}{2}$  \n- Subtract $\\frac{1}{2}$ using a common denominator of 6: $\\frac{2}{6} - \\frac{3}{6} = \\frac{-1}{6}$  \n- Third fraction parsed: $\\frac{1}{6}$\n- Add $\\frac{1}{6}$ using a common denominator of $36$: $\\frac{-6}{36} + \\frac{6}{36} = \\frac{0}{36}$\n\nThe final result is $\\frac{0}{36}$, which will be reduced to $\\frac{0}{1}$\n\n### Algorithm \n\n1. Define helper function `FindGCD(a, b)` to find the greatest common divisor:\n    * If `a == 0` return `b`\n    * Return `FindGCD(b % a, a)`\n2. Initialize our running result fraction with  numerator `num = 0` and denominator `denom = 1`\n3. Iterate through each character in `expression`:\n    * Initialize numerator `currNum = 0` and denominator `currDenom = 0` for the current fraction being parsed.\n    * Initialize a boolean `isNegative = false` to account for negative fractions.\n    * If current character is a negative sign or positive sign:\n        * Set `isNegative` to `true` if character is negative sign\n        * Move on to next character\n    * Build the current numerator - While the current character is a number: \n        * Convert the character to its numerical value `val`\n        * Append the digit to `currNum` by performing `currNum = currNum * 10 + val`\n    * If `isNegative = true`, we set `currNum *= -1` to make it negative\n    * At this point, we are done iterating through the numerator, and can skip the divisor character to begin parsing the denominator\n    * Build the current denominator - While the current character is a number:\n        * Convert the character to its numerical value `val`\n        * Append the digit to `currDenom` by performing `currDenom = currDenom * 10 + val`\n    * Add the current fraction with the running result fraction:\n        * `num` is updated to `num * currDenom + currNum * denom`\n        * `denom` is updated to `denom * currDenom`\n4. Call `FindGCD(num, denom)` and store result in `gcd`.\n5. Reduce the result fraction by dividing `num` and `denom` by `gcd`\n6. Return `num + \"/\" + denom` to return the resulting fraction in string format\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/h4zAuuef/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"h4zAuuef\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(n)$\n\n    The loop to parse through `expression` runs $O(n)$ times. Inside the loop, the math operations to combine fractions and find a common denominator is done in $O(1)$ time. Thus, the loop in total takes $O(n)$ time. \n\n    The `FindGCD` function uses Euclid's algorithm, which runs in $\\log(\\min(a, b))$ time. \n\n    Thus, the total time complexity is $O(n)$.\n\n* Space Complexity: $O(\\log(\\min(a, b)))$\n\n    The space complexity is determined by the recursive overhead from the `FindGCD` algorithm. The max depth of the call stack would be $O(\\log(\\min(a, b)))$. Thus, the total space complexity is $O(\\log(\\min(a, b)))$.\n\n### Approach 2 - Parsing with Regular Expressions\n\n### Intuition\n\n> **Note:** We understand that most people are not familiar with the intricacies of regular expressions. We include this approach for the sake of article completeness, but we recognize most interviewers will not expect you to know the exact regex patterns needed without additional help.\n\nIn the first approach, we manually parsed the `expression` string, which can be tedious and error-prone. A more efficient and reliable method is to use regular expressions (regex) to tokenize the string. Most languages provide utility functions that will tokenize a string based on a given delimiter expression written in regex. For example, if we are given a string `3a5a10`, and we provide `a` as our delimiter, then the string will be separated into `3`, `5`, and `10`. For this approach, we will come up with a regex expression to match the delimiters needed to split `expression`.\n\n##### Regular Expression Breakdown\n\nWe would like to break down `expression` into segments representing individual numbers (either numerator or denominator) along with their corresponding signs. We observe that each fraction is separated by a `/` character, so let's start by simply using `/` as our delimiter expression. The breakdown for `expression` using this regex is shown below: \n\n![Tokenizing with first regex expression](../Figures/592/first_regex.png)\n\nWe notice that this isn't a sufficient regex expression to match our desired delimiters, as `2 + 1` should ideally be two separate tokens: `2` and `+1`. To address this, we can add in a regex \"lookahead\" expression that will create a new token if the next character is a `+` or a `-`, and will add the character to the new token. This lookahead expression can be expressed as `(?=[-+])`. Here, the `(?=)` portion indicates looking ahead at the next character, and the `[-+]` argument indicates that the lookahead should be done for either the `-` character or `+` character.\n\nCombining these two expressions with the logical OR operator (`|`), the resulting regex pattern becomes: `/|(?=[-+])`. With this, we can properly split `expression` using `/`, `+`, and `-` as delimiters. The final breakdown is shown below:\n\n![Tokenizing with second regex expression](../Figures/592/second_regex.png)\n\nThis pattern allows us to tokenize the string into manageable parts, making it easier to iterate through each fraction and apply the arithmetic operations as in Approach 1.  \n\n### Algorithm\n\n1. Define helper function `FindGCD(a, b)` to find the greatest common divisor:\n    * If `a == 0` return `b`\n    * Return `FindGCD(b % a, a)`\n2. Separate `expression` into tokens by using the regex `/|(?=[-+])` as the delimiter. Store the tokens into array `nums`\n3. Initialize our running result fraction with  numerator `num = 0` and denominator `denom = 0`\n4. Initialize `i = 0` to iterate through `nums`\n5. While `i < nums.length`:\n    * **Get the numerator and denominator of next fraction**: `currNum = nums[i]` and `currDenom=nums[i+1]`\n    * **Perform fraction addition/subtraction**: \n        * `num` is updated to `num * currDenom + currNum * denom`\n        * `denom` is updated to `denom * currDenom`\n    * **Update iterator**: `i += 2`\n6. Call `FindGCD(num, denom)` and store result in `gcd`.\n7. Reduce the result fraction by dividing `num` and `denom` by `gcd`\n8. Return `num + \"/\" + denom` to return the resulting fraction in string format\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/dswBCwud/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"dswBCwud\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(n)$\n\n    The regex parsing will take $O(n)$ time. Processing the `nums` array and performing the fraction math will take a total of $O(n)$ time as well. The `FindGCD` function runs in $\\log(\\min(a, b))$ time. \n\n    Thus, the total time complexity is $O(n)$.\n\n* Space Complexity: $O(\\log(\\min(a, b)))$\n\n    Like before, the space complexity is determined by the recursive overhead from the `FindGCD` algorithm. The max depth of the call stack would be $O(\\log(\\min(a, b)))$. Thus, the total space complexity is $O(\\log(\\min(a, b)))$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def fractionAddition(self, expression: str) -> str:\n    ints = list(map(int, re.findall('[+-]?[0-9]+', expression)))\n    A = 0\n    B = 1\n\n    for a, b in zip(ints[::2], ints[1::2]):\n      A = A * b + a * B\n      B *= b\n      g = math.gcd(A, B)\n      A //= g\n      B //= g\n\n    return str(A) + '/' + str(B)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String fractionAddition(String expression) {\n    Scanner sc = new Scanner(expression).useDelimiter(\"/|(?=[+-])\");\n    int A = 0;\n    int B = 1;\n\n    // Init: A / B = 0 / 1\n    // A / B + a / b = (Ab + aB) / Bb\n    // So, each round set A = Ab + aB, B = Bb\n    while (sc.hasNext()) {\n      final int a = sc.nextInt();\n      final int b = sc.nextInt();\n      A = A * b + a * B;\n      B *= b;\n      final int g = gcd(A, B);\n      A /= g;\n      B /= g;\n    }\n\n    return A + \"/\" + B;\n  }\n\n  private int gcd(int a, int b) {\n    return a == 0 ? Math.abs(b) : gcd(b % a, a);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string fractionAddition(string expression) {\n    istringstream iss(expression);\n    char _;\n    int a;\n    int b;\n    int A = 0;\n    int B = 1;\n\n    // Init: A / B = 0 / 1\n    // A / B + a / b = (Ab + aB) / Bb\n    // So, each round set A = Ab + aB, B = Bb\n    while (iss >> a >> _ >> b) {\n      A = A * b + a * B;\n      B *= b;\n      const int g = abs(__gcd(A, B));\n      A /= g;\n      B /= g;\n    }\n\n    return to_string(A) + \"/\" + to_string(B);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/592.html",
    "category": "Algorithms",
    "acceptance_rate": 66.15030836209877,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 873,
    "dislikes": 691,
    "similar_questions": "[{\"title\": \"Solve the Equation\", \"titleSlug\": \"solve-the-equation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"132K\", \"totalSubmission\": \"199.6K\", \"totalAcceptedRaw\": 132038, \"totalSubmissionRaw\": 199603, \"acRate\": \"66.2%\"}",
    "title_pt": "Adição e Subtração de Frações",
    "description_pt": "<p>Dada uma string <code>expression</code> que representa uma expressão de adição e subtração de frações, retorne o resultado do cálculo em formato de string.</p>\n\n<p>O resultado final deve ser uma <a href=\"https://en.wikipedia.org/wiki/Irreducible_fraction\" target=\"_blank\">fração irredutível</a>. Se o seu resultado final for um inteiro, altere-o para o formato de uma fração que tenha denominador <code>1</code>. Portanto, neste caso, <code>2</code> deve ser convertido para <code>2/1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> expression = &quot;-1/2+1/2&quot;\n<strong>Saída:</strong> &quot;0/1&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> expression = &quot;-1/2+1/2+1/3&quot;\n<strong>Saída:</strong> &quot;1/3&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> expression = &quot;1/3-1/2&quot;\n<strong>Saída:</strong> &quot;-1/6&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>A string de entrada contém apenas <code>&#39;0&#39;</code> a <code>&#39;9&#39;</code>, <code>&#39;/&#39;</code>, <code>&#39;+&#39;</code> e <code>&#39;-&#39;</code>. A saída também contém.</li>\n\t<li>Cada fração (entrada e saída) tem o formato <code>&plusmn;numerator/denominator</code>. Se a primeira fração de entrada ou a saída for positiva, então <code>&#39;+&#39;</code> será omitido.</li>\n\t<li>A entrada contém apenas <strong>frações irredutíveis</strong> válidas, em que o <strong>numerator</strong> e o <strong>denominator</strong> de cada fração estarão sempre no intervalo <code>[1, 10]</code>. Se o denominator for <code>1</code>, isso significa que essa fração é, na verdade, um inteiro no formato de fração definido acima.</li>\n\t<li>O número de frações fornecidas estará no intervalo <code>[1, 10]</code>.</li>\n\t<li>O numerator e o denominator do <strong>resultado final</strong> têm garantia de serem válidos e estarem no intervalo de um int de <strong>32 bits</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "593",
    "paidOnly": false,
    "title": "Valid Square",
    "titleSlug": "valid-square",
    "url": "https://leetcode.com/problems/valid-square",
    "description_url": "https://leetcode.com/problems/valid-square/description/",
    "description": "<p>Given the coordinates of four points in 2D space <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code>, return <code>true</code> <em>if the four points construct a square</em>.</p>\n\n<p>The coordinate of a point <code>p<sub>i</sub></code> is represented as <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. The input is <strong>not</strong> given in any order.</p>\n\n<p>A <strong>valid square</strong> has four equal sides with positive length and four equal angles (90-degree angles).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\n<strong>Output:</strong> false\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\n<strong>Output:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-square/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Accepted]\n\nThe idea behind determining whether 4 given set of points constitute a valid square or not is really simple. Firstly, we need to determine if the sides of the quadrilateral formed by these 4 points are equal. But checking only this won't suffice. Since, this condition will be satisfied even in the case of a rhombus, where all the four sides are equal but the adjacent sides aren't perpendicular to each other. Thus, we also need to check if the lengths of the diagonals formed between the corners of the quadrilateral are equal. If both the conditions are satisfied, then only the given set of points can be deemed appropriate for constituting a square.\n\nNow, the problem arises in determining which pairs of points act as the adjacent points on the square boundary. So, the simplest method is to consider every possible case. For the given 4 points, $$[p_0, p_1, p_2, p_3]$$, there are a total of 4! ways in which these points can be arranged to be considered as the square's boundaries. We can generate every possible permutation and check if any permutation leads to the valid square arrangement of points.\n\n<iframe src=\"https://leetcode.com/playground/2NJc8Xxy/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"2NJc8Xxy\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(1)$$. Constant number of permutations($$4!$$) are generated.\n\n* Space complexity : $$O(1)$$. Constant space is required.\n\n---\n### Approach #2 Using Sorting [Accepted]\n\nInstead of considering all the permutations of arrangements possible, we can make use of maths to simplify this problem a bit. If we sort the given set of points based on their x-coordinate values, and in the case of a tie, based on their y-coordinate value, we can obtain an arrangement, which directly reflects the arrangement of points on a valid square boundary possible.\n\nConsider the only possible cases as shown in the figure below:\n\n![Valid_Square](../Figures/593_Valid_Square_1.PNG)\n\nIn each case, after sorting, we obtain the following conclusion regarding the connections of the points:\n\n1. $$p_0p_1$$, $$p_1p_3$$, $$p_3p_2$$ and $$p_2p_0$$ form the four sides of any valid square.\n\n2. $$p_0p_3$$ and $$p_1p_2$$ form the diagonals of the square.\n\nThus, once the sorting of the points is done, based on the above knowledge, we can directly compare $$p_0p_1$$, $$p_1p_3$$, $$p_3p_2$$ and $$p_2p_0$$ for equality of lengths(corresponding to the sides); and $$p_0p_3$$ and $$p_1p_2$$ for equality of lengths(corresponding to the diagonals).\n\n<iframe src=\"https://leetcode.com/playground/5985SrgC/shared\" frameBorder=\"0\" width=\"100%\" height=\"446\" name=\"5985SrgC\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(1)$$. Sorting 4 points takes constant time.\n\n* Space complexity : $$O(1)$$. Constant space is required.\n\n---\n### Approach #3 Checking every case [Accepted]\n\n**Algorithm**\n\nIf we consider all the permutations descripting the arrangement of points as in the brute force approach, we can come up with the following set of 24 arrangements:\n\n![Valid_Square](../Figures/593_Valid_Square_2.PNG)\n\nIn this figure, the rows with the same shaded color indicate that the corresponding arrangements lead to the same set of edges and diagonals. Thus, we can see that only three unique cases exist. Thus, instead of generating all the 24 permutations, we check for the equality of edges and diagonals for only the three distinct cases.\n\n<iframe src=\"https://leetcode.com/playground/UEVGf4Ly/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"UEVGf4Ly\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(1)$$. A fixed number of comparisons are done.\n\n* Space complexity : $$O(1)$$. No extra space required.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n    def dist(p1: List[int], p2: List[int]) -> int:\n      return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2\n\n    distSet = set([dist(*pair)\n                   for pair in list(itertools.combinations([p1, p2, p3, p4], 2))])\n\n    return 0 not in distSet and len(distSet) == 2",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {\n    Set<Integer> distSet = new HashSet<>();\n    int[][] points = {p1, p2, p3, p4};\n\n    for (int i = 0; i < 4; ++i)\n      for (int j = i + 1; j < 4; ++j)\n        distSet.add(dist(points[i], points[j]));\n\n    return !distSet.contains(0) && distSet.size() == 2;\n  }\n\n  private int dist(int[] p1, int[] p2) {\n    return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool validSquare(vector<int>& p1, vector<int>& p2,\n                   vector<int>& p3, vector<int>& p4) {\n    unordered_set<int> distSet;\n    vector<vector<int>> points{p1, p2, p3, p4};\n\n    for (int i = 0; i < 4; ++i)\n      for (int j = i + 1; j < 4; ++j)\n        distSet.insert(dist(points[i], points[j]));\n\n    return !distSet.count(0) && distSet.size() == 2;\n  }\n\n private:\n  int dist(vector<int>& p1, vector<int>& p2) {\n    return (p1[0] - p2[0]) * (p1[0] - p2[0]) +\n           (p1[1] - p2[1]) * (p1[1] - p2[1]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/593.html",
    "category": "Algorithms",
    "acceptance_rate": 44.22004560723466,
    "topics": [
      "Math",
      "Geometry"
    ],
    "hints": [],
    "likes": 1091,
    "dislikes": 912,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"118.9K\", \"totalSubmission\": \"268.8K\", \"totalAcceptedRaw\": 118870, \"totalSubmissionRaw\": 268815, \"acRate\": \"44.2%\"}",
    "title_pt": "Quadrado Válido",
    "description_pt": "<p>Dadas as coordenadas de quatro pontos no espaço 2D <code>p1</code>, <code>p2</code>, <code>p3</code> e <code>p4</code>, retorne <code>true</code> <em>se os quatro pontos construírem um quadrado</em>.</p>\n\n<p>A coordenada de um ponto <code>p<sub>i</sub></code> é representada como <code>[x<sub>i</sub>, y<sub>i</sub>]</code>. A entrada <strong>não</strong> é fornecida em nenhuma ordem.</p>\n\n<p>Um <strong>quadrado válido</strong> tem quatro lados iguais com comprimento positivo e quatro ângulos iguais (ângulos de 90 graus).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\n<strong>Saída:</strong> false\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\n<strong>Saída:</strong> true\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>p1.length == p2.length == p3.length == p4.length == 2</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "594",
    "paidOnly": false,
    "title": "Longest Harmonious Subsequence",
    "titleSlug": "longest-harmonious-subsequence",
    "url": "https://leetcode.com/problems/longest-harmonious-subsequence",
    "description_url": "https://leetcode.com/problems/longest-harmonious-subsequence/description/",
    "description": "<p>We define a harmonious array as an array where the difference between its maximum value and its minimum value is <b>exactly</b> <code>1</code>.</p>\n\n<p>Given an integer array <code>nums</code>, return the length of its longest harmonious <span data-keyword=\"subsequence-array\">subsequence</span> among all its possible subsequences.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,3,2,2,5,2,3,7]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">5</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The longest harmonious subsequence is <code>[3,2,2,2,3]</code>.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,2,3,4]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">2</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>The longest harmonious subsequences are <code>[1,2]</code>, <code>[2,3]</code>, and <code>[3,4]</code>, all of which have a length of 2.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">nums = [1,1,1,1]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">0</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>No harmonic subsequence exists.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-harmonious-subsequence/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLHS(self, nums: List[int]) -> int:\n    ans = 0\n    count = Counter(nums)\n\n    for num, freq in count.items():\n      if num + 1 in count:\n        ans = max(ans, freq + count[num + 1])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findLHS(int[] nums) {\n    int ans = 0;\n    Map<Integer, Integer> count = new HashMap<>();\n\n    for (final int num : nums)\n      count.put(num, count.getOrDefault(num, 0) + 1);\n\n    for (final int num : count.keySet())\n      if (count.containsKey(num + 1))\n        ans = Math.max(ans, count.get(num) + count.get(num + 1));\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLHS(vector<int>& nums) {\n    int ans = 0;\n    unordered_map<int, int> count;\n\n    for (const int num : nums)\n      ++count[num];\n\n    for (const auto& [num, freq] : count)\n      if (count.count(num + 1))\n        ans = max(ans, freq + count[num + 1]);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/594.html",
    "category": "Algorithms",
    "acceptance_rate": 56.96515715114493,
    "topics": [
      "Array",
      "Hash Table",
      "Sliding Window",
      "Sorting",
      "Counting"
    ],
    "hints": [],
    "likes": 2282,
    "dislikes": 302,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"200.3K\", \"totalSubmission\": \"351.6K\", \"totalAcceptedRaw\": 200308, \"totalSubmissionRaw\": 351632, \"acRate\": \"57.0%\"}",
    "title_pt": "Subsequência Harmoniosa Mais Longa",
    "description_pt": "<p>Definimos um array harmonioso como um array em que a diferença entre seu valor máximo e seu valor mínimo é <b>exatamente</b> <code>1</code>.</p>\n<p>Dado um array de inteiros <code>nums</code>, retorne o comprimento de sua mais longa <span data-keyword=\"subsequence-array\">subsequência</span> harmoniosa entre todas as suas subsequências possíveis.</p>\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,3,2,2,5,2,3,7]</span></p>\n<p><strong>Saída:</strong> <span class=\"example-io\">5</span></p>\n<p><strong>Explicação:</strong></p>\n<p>A mais longa subsequência harmoniosa é <code>[3,2,2,2,3]</code>.</p>\n</div>\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,2,3,4]</span></p>\n<p><strong>Saída:</strong> <span class=\"example-io\">2</span></p>\n<p><strong>Explicação:</strong></p>\n<p>As mais longas subsequências harmoniosas são <code>[1,2]</code>, <code>[2,3]</code> e <code>[3,4]</code>, todas com comprimento 2.</p>\n</div>\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">nums = [1,1,1,1]</span></p>\n<p><strong>Saída:</strong> <span class=\"example-io\">0</span></p>\n<p><strong>Explicação:</strong></p>\n<p>Nenhuma subsequência harmoniosa existe.</p>\n</div>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "595",
    "paidOnly": false,
    "title": "Big Countries",
    "titleSlug": "big-countries",
    "url": "https://leetcode.com/problems/big-countries",
    "description_url": "https://leetcode.com/problems/big-countries/description/",
    "description": "<p>Table: <code>World</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| name        | varchar |\n| continent   | varchar |\n| area        | int     |\n| population  | int     |\n| gdp         | bigint  |\n+-------------+---------+\nname is the primary key (column with unique values) for this table.\nEach row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>A country is <strong>big</strong> if:</p>\n\n<ul>\n\t<li>it has an area of at least&nbsp;three million (i.e., <code>3000000 km<sup>2</sup></code>), or</li>\n\t<li>it has a population of at least&nbsp;twenty-five million (i.e., <code>25000000</code>).</li>\n</ul>\n\n<p>Write a solution to find the name, population, and area of the <strong>big countries</strong>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nWorld table:\n+-------------+-----------+---------+------------+--------------+\n| name        | continent | area    | population | gdp          |\n+-------------+-----------+---------+------------+--------------+\n| Afghanistan | Asia      | 652230  | 25500100   | 20343000000  |\n| Albania     | Europe    | 28748   | 2831741    | 12960000000  |\n| Algeria     | Africa    | 2381741 | 37100000   | 188681000000 |\n| Andorra     | Europe    | 468     | 78115      | 3712000000   |\n| Angola      | Africa    | 1246700 | 20609294   | 100990000000 |\n+-------------+-----------+---------+------------+--------------+\n<strong>Output:</strong> \n+-------------+------------+---------+\n| name        | population | area    |\n+-------------+------------+---------+\n| Afghanistan | 25500100   | 652230  |\n| Algeria     | 37100000   | 2381741 |\n+-------------+------------+---------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/big-countries/solutions/",
    "solution": "<!-- Don't delete this -->\n[TOC]\n\n# Solution\n\n---\n\n## pandas\n\n### Approach: Filtering rows\n\n#### Intuition\n\n<table>\n  <tr>\n    <th>name</th>\n    <th>continent</th>\n    <th>area</th>\n    <th>population</th>\n    <th>gdp</th>\n  </tr>\n  <tr>\n    <td>Afghanistan</td>\n    <td>Asia</td>\n    <td>652230</td>\n    <td>25500100</td>\n    <td>20343000000</td>\n  </tr>\n  <tr>\n    <td>Albania</td>\n    <td>Europe</td>\n    <td>28748</td>\n    <td>2831741</td>\n    <td>12960000000</td>\n  </tr>\n  <tr>\n    <td>Algeria</td>\n    <td>Africa</td>\n    <td>2381741</td>\n    <td>37100000</td>\n    <td>188681000000</td>\n  </tr>\n  <tr>\n    <td>Andorra</td>\n    <td>Europe</td>\n    <td>468</td>\n    <td>78115</td>\n    <td>3712000000</td>\n  </tr>\n  <tr>\n    <td>Angola</td>\n    <td>Africa</td>\n    <td>1246700</td>\n    <td>20609294</td>\n    <td>100990000000</td>\n  </tr>\n</table>\n\n<br>\nTo determine whether a country is considered `big`, there are two conditions to verify, as stated in the description:\n\n- The country must have an area of at least three million square kilometers, denoted as `area >= 3,000,000`.\n\n- The population of the country should be a minimum of twenty-five million, expressed as `population >= 25,000,000`.\n\n#### Algorithm\n\nFirst, we apply row filtering to identify the countries that satisfy the conditions.\n\n\n```python\n    df = world[(world['area'] >= 3000000) | (world['population'] >= 25000000)]\n```\n\nThis step filters out the rows representing countries that do not meet the conditions, leaving the remaining table as follows.\n\n<table>\n  <tr>\n    <th>name</th>\n    <th>continent</th>\n    <th>area</th>\n    <th>population</th>\n    <th>gdp</th>\n  </tr>\n  <tr>\n    <td>Afghanistan</td>\n    <td>Asia</td>\n    <td>652230</td>\n    <td>25500100</td>\n    <td>20343000000</td>\n  </tr>\n  <tr>\n    <td>Algeria</td>\n    <td>Africa</td>\n    <td>2381741</td>\n    <td>37100000</td>\n    <td>188681000000</td>\n  </tr>\n</table>\n\n\n<br>\n\nNoting that the table has five columns, we need to return three columns according to the requirements of the problem. Thus the next step is returning the three required columns with the relative order as: `name`, `population`, and `area`.\n\n```python\n    df = df[['name', 'population', 'area']]\n```\n\n<table>\n  <tr>\n    <th>name</th>\n    <th>population</th>\n    <th>area</th>\n  </tr>\n  <tr>\n    <td>Afghanistan</td>\n    <td>25500100</td>\n    <td>652230</td>\n  </tr>\n  <tr>\n    <td>Algeria</td>\n    <td>37100000</td>\n    <td>2381741</td> \n  </tr>\n</table>\n \n<br>\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/3C3wJk4h/shared\" frameBorder=\"0\" width=\"100%\" height=\"140\" name=\"3C3wJk4h\"></iframe>\n\n<br>\n\n---\n\n## Database\n\n<!-- h3 for approaches -->\n### Approach: Filtering rows using `WHERE`\n\n<!-- h4 for sections -->\n#### Algorithm\n\nTo determine whether a country is considered `big`, there are two conditions to verify, as stated in the description:\n\n- The country must have an area of at least three million square kilometers, denoted as `area >= 3,000,000`.\n\n- The population of the country should be a minimum of twenty-five million, expressed as `population >= 25,000,000`.\n\n\n```sql\nSELECT \n    * \nFROM \n    world \nWHERE \n    area >= 3000000 \n    OR population >= 25000000\n```\n\n<br>\n\nNoting that we need to return three columns according to the requirements of the problem. Thus the next step is selecting the three required columns with the relative order as: `name`, `population`, and `area`. The complete answer is as follows.\n\n```sql\nSELECT\n    name, population, area\nFROM\n    world\nWHERE\n    area >= 3000000 OR population >= 25000000\n;\n```",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/595.html",
    "category": "Database",
    "acceptance_rate": 68.19453438866785,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 3028,
    "dislikes": 1350,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1830179, \"totalSubmissionRaw\": 2683762, \"acRate\": \"68.2%\"}",
    "title_pt": "Grandes Países",
    "description_pt": "<p>Tabela: <code>World</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| name        | varchar |\n| continent   | varchar |\n| area        | int     |\n| population  | int     |\n| gdp         | bigint  |\n+-------------+---------+\nname é a chave primária (coluna com valores únicos) para esta tabela.\nCada linha desta tabela fornece informações sobre o nome de um país, o continente ao qual ele pertence, sua área, a população e seu valor de PIB.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Um país é <strong>grande</strong> se:</p>\n\n<ul>\n\t<li>ele tem uma área de pelo menos&nbsp;três milhões (ou seja, <code>3000000 km<sup>2</sup></code>), ou</li>\n\t<li>ele tem uma população de pelo menos&nbsp;vinte e cinco milhões (ou seja, <code>25000000</code>).</li>\n</ul>\n\n<p>Escreva uma solução para encontrar o nome, a população e a área dos <strong>grandes países</strong>.</p>\n\n<p>Retorne a tabela de परिणामados em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela World:\n+-------------+-----------+---------+------------+--------------+\n| name        | continent | area    | population | gdp          |\n+-------------+-----------+---------+------------+--------------+\n| Afghanistan | Asia      | 652230  | 25500100   | 20343000000  |\n| Albania     | Europe    | 28748   | 2831741    | 12960000000  |\n| Algeria     | Africa    | 2381741 | 37100000   | 188681000000 |\n| Andorra     | Europe    | 468     | 78115      | 3712000000   |\n| Angola      | Africa     | 1246700 | 20609294   | 100990000000 |\n+-------------+-----------+---------+------------+--------------+\n<strong>Saída:</strong> \n+-------------+------------+---------+\n| name        | population | area    |\n+-------------+------------+---------+\n| Afghanistan | 25500100   | 652230  |\n| Algeria     | 37100000   | 2381741 |\n+-------------+------------+---------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "596",
    "paidOnly": false,
    "title": "Classes More Than 5 Students",
    "titleSlug": "classes-more-than-5-students",
    "url": "https://leetcode.com/problems/classes-more-than-5-students",
    "description_url": "https://leetcode.com/problems/classes-more-than-5-students/description/",
    "description": "<p>Table: <code>Courses</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| student     | varchar |\n| class       | varchar |\n+-------------+---------+\n(student, class) is the primary key (combination of columns with unique values) for this table.\nEach row of this table indicates the name of a student and the class in which they are enrolled.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find all the classes that have <strong>at least five students</strong>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nCourses table:\n+---------+----------+\n| student | class    |\n+---------+----------+\n| A       | Math     |\n| B       | English  |\n| C       | Math     |\n| D       | Biology  |\n| E       | Math     |\n| F       | Computer |\n| G       | Math     |\n| H       | Math     |\n| I       | Math     |\n+---------+----------+\n<strong>Output:</strong> \n+---------+\n| class   |\n+---------+\n| Math    |\n+---------+\n<strong>Explanation:</strong> \n- Math has 6 students, so we include it.\n- English has 1 student, so we do not include it.\n- Biology has 1 student, so we do not include it.\n- Computer has 1 student, so we do not include it.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/classes-more-than-5-students/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/596.html",
    "category": "Database",
    "acceptance_rate": 60.39753092856667,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1165,
    "dislikes": 1079,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"625.5K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 625531, \"totalSubmissionRaw\": 1035691, \"acRate\": \"60.4%\"}",
    "title_pt": "Turmas com Mais de 5 Estudantes",
    "description_pt": "<p>Tabela: <code>Courses</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Tipo    |\n+-------------+---------+\n| student     | varchar |\n| class       | varchar |\n+-------------+---------+\n(student, class) é a chave primária (combinação de colunas com valores únicos) desta tabela.\nCada linha desta tabela indica o nome de um estudante e a turma na qual ele está matriculado.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar todas as turmas que têm <strong>pelo menos cinco estudantes</strong>.</p>\n\n<p>Retorne a tabela resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O&nbsp;formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Courses:\n+---------+----------+\n| student | class    |\n+---------+----------+\n| A       | Math     |\n| B       | English  |\n| C       | Math     |\n| D       | Biology  |\n| E       | Math     |\n| F       | Computer |\n| G       | Math     |\n| H       | Math     |\n| I       | Math     |\n+---------+----------+\n<strong>Saída:</strong> \n+---------+\n| class   |\n+---------+\n| Math    |\n+---------+\n<strong>Explicação:</strong> \n- Math tem 6 estudantes, então a incluímos.\n- English tem 1 estudante, então não a incluímos.\n- Biology tem 1 estudante, então não a incluímos.\n- Computer tem 1 estudante, então não a incluímos.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "598",
    "paidOnly": false,
    "title": "Range Addition II",
    "titleSlug": "range-addition-ii",
    "url": "https://leetcode.com/problems/range-addition-ii",
    "description_url": "https://leetcode.com/problems/range-addition-ii/description/",
    "description": "<p>You are given an <code>m x n</code> matrix <code>M</code> initialized with all <code>0</code>&#39;s and an array of operations <code>ops</code>, where <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> means <code>M[x][y]</code> should be incremented by one for all <code>0 &lt;= x &lt; a<sub>i</sub></code> and <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p>\n\n<p>Count and return <em>the number of maximum integers in the matrix after performing all the operations</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg\" style=\"width: 750px; height: 176px;\" />\n<pre>\n<strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The maximum integer in M is 2, and there are four of it in M. So return 4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\n<strong>Output:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> m = 3, n = 3, ops = []\n<strong>Output:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>ops[i].length == 2</code></li>\n\t<li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li>\n\t<li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/range-addition-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n    minY = m\n    minX = n\n\n    for y, x in ops:\n      minY = min(minY, y)\n      minX = min(minX, x)\n\n    return minX * minY",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxCount(int m, int n, int[][] ops) {\n    int minY = m;\n    int minX = n;\n\n    for (int[] op : ops) {\n      minY = Math.min(minY, op[0]);\n      minX = Math.min(minX, op[1]);\n    }\n\n    return minX * minY;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxCount(int m, int n, vector<vector<int>>& ops) {\n    int minY = m;\n    int minX = n;\n\n    for (const vector<int>& op : ops) {\n      minY = min(minY, op[0]);\n      minX = min(minX, op[1]);\n    }\n\n    return minX * minY;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/598.html",
    "category": "Algorithms",
    "acceptance_rate": 57.20174706777249,
    "topics": [
      "Array",
      "Math"
    ],
    "hints": [],
    "likes": 984,
    "dislikes": 978,
    "similar_questions": "[{\"title\": \"Range Addition\", \"titleSlug\": \"range-addition\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Matrix After Queries\", \"titleSlug\": \"sum-of-matrix-after-queries\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"116.6K\", \"totalSubmission\": \"203.8K\", \"totalAcceptedRaw\": 116558, \"totalSubmissionRaw\": 203768, \"acRate\": \"57.2%\"}",
    "title_pt": "Adição de Intervalo II",
    "description_pt": "<p>Você recebe uma matriz <code>m x n</code> <code>M</code> inicializada com todos os <code>0</code>&#39;s e um array de operações <code>ops</code>, em que <code>ops[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> significa que <code>M[x][y]</code> deve ser incrementado em um para todo <code>0 &lt;= x &lt; a<sub>i</sub></code> e <code>0 &lt;= y &lt; b<sub>i</sub></code>.</p>\n\n<p>Conte e retorne <em>o número de inteiros máximos na matriz após realizar todas as operações</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/02/ex1.jpg\" style=\"width: 750px; height: 176px;\" />\n<pre>\n<strong>Entrada:</strong> m = 3, n = 3, ops = [[2,2],[3,3]]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> O inteiro máximo em M é 2, e há quatro dele em M. Portanto, retorne 4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\n<strong>Saída:</strong> 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> m = 3, n = 3, ops = []\n<strong>Saída:</strong> 9\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= ops.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>ops[i].length == 2</code></li>\n\t<li><code>1 &lt;= a<sub>i</sub> &lt;= m</code></li>\n\t<li><code>1 &lt;= b<sub>i</sub> &lt;= n</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "599",
    "paidOnly": false,
    "title": "Minimum Index Sum of Two Lists",
    "titleSlug": "minimum-index-sum-of-two-lists",
    "url": "https://leetcode.com/problems/minimum-index-sum-of-two-lists",
    "description_url": "https://leetcode.com/problems/minimum-index-sum-of-two-lists/description/",
    "description": "<p>Given two arrays of strings <code>list1</code> and <code>list2</code>, find the <strong>common strings with the least index sum</strong>.</p>\n\n<p>A <strong>common string</strong> is a string that appeared in both <code>list1</code> and <code>list2</code>.</p>\n\n<p>A <strong>common string with the least index sum</strong> is a common string such that if it appeared at <code>list1[i]</code> and <code>list2[j]</code> then <code>i + j</code> should be the minimum value among all the other <strong>common strings</strong>.</p>\n\n<p>Return <em>all the <strong>common strings with the least index sum</strong></em>. Return the answer in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;]\n<strong>Output:</strong> [&quot;Shogun&quot;]\n<strong>Explanation:</strong> The only common string is &quot;Shogun&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;]\n<strong>Output:</strong> [&quot;Shogun&quot;]\n<strong>Explanation:</strong> The common string with the least index sum is &quot;Shogun&quot; with index sum = (0 + 1) = 1.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;]\n<strong>Output:</strong> [&quot;sad&quot;,&quot;happy&quot;]\n<strong>Explanation:</strong> There are three common strings:\n&quot;happy&quot; with index sum = (0 + 1) = 1.\n&quot;sad&quot; with index sum = (1 + 0) = 1.\n&quot;good&quot; with index sum = (2 + 2) = 4.\nThe strings with the least index sum are &quot;sad&quot; and &quot;happy&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li>\n\t<li><code>list1[i]</code> and <code>list2[i]</code> consist of spaces <code>&#39; &#39;</code> and English letters.</li>\n\t<li>All the strings of <code>list1</code> are <strong>unique</strong>.</li>\n\t<li>All the strings of <code>list2</code> are <strong>unique</strong>.</li>\n\t<li>There is at least a common string between <code>list1</code> and <code>list2</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-index-sum-of-two-lists/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Using HashMap [Accepted]\n\nIn this approach, we compare every string in $$list1$$ and $$list2$$ by traversing over the whole list $$list2$$ for every string chosen from $$list1$$. We make use of a hashmap $$map$$, which contains elements of the form $$(sum : list_{sum})$$. Here, $$sum$$ refers to the sum of indices of matching elements and $$list_{sum}$$ refers to the list of matching strings whose indices' sum equals $$sum$$. \n\nThus, while doing the comparisons, whenever a match between a string at $$i^{th}$$ index of $$list1$$ and $$j^{th}$$ index of $$list2$$ is found, we make an entry in the $$map$$ corresponding to the sum $$i + j$$, if this entry isn't already present. If an entry with this sum already exists, we need to keep a track of all the strings which lead to the same index sum. Thus, we append the current string to the list of strings corresponding to sum $$i + j$$.\n\nAt the end, we traverse over the keys of the $$map$$ and find out the list of strings corresponding to the key reprsenting the minimum sum.\n\n<iframe src=\"https://leetcode.com/playground/Rxg7wbHW/shared\" frameBorder=\"0\" name=\"Rxg7wbHW\" width=\"100%\" height=\"394\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(l_1*l_2*x)$$. Every item of $$list1$$ is compared with all the items of $$list2$$. $$l_1$$ and $$l_2$$ are the lengths of $$list1$$ and $$list2$$ respectively. And $$x$$ refers to average string length.\n\n* Space complexity : $$O(l_1*l_2*x)$$. In worst case all items of $$list1$$ and $$list2$$ are same. In that case, hashmap size grows upto $$l_1*l_2*x$$, where $$x$$ refers to average string length.\n\n---\n### Approach #2 Without Using HashMap [Accepted]\n\n**Algorithm**\n\nAnother method could be to traverse over the various $$sum$$(index sum) values and determine if any such string exists in $$list1$$ and $$list2$$ such that the sum of its indices in the two lists equals $$sum$$. \n\nNow, we know that the value of index sum, $$sum$$ could range from 0 to $$m + n - 1$$. Here, $$m$$ and $$n$$ refer to the length of lists $$list1$$ and $$list2$$ respectively. Thus, we choose every value of $$sum$$ in ascending order. For every $$sum$$ chosen, we iterate over $$list1$$. Suppose, currently the string at $$i^{th}$$ index in $$list1$$ is being considered. Now, in order for the index sum $$sum$$ to be the one corresponding to matching strings in $$list1$$ and $$list2$$, the string at index $$j$$ in $$list2$$ should match the string at index $$i$$ in $$list1$$, such that $$sum = i + j$$.\n\nOr, stating in other terms, the string at index $$j$$ in $$list2$$ should be equal to the string at index $$i$$ in $$list1$$, such that $$j = sum - i$$. Thus, for a particular $$sum$$ and $$i$$(from $$list1$$), we can directly determine that we need to check the element at index $$ j= sum - i$$ in $$list2$$, instead of traversing over the whole $$list2$$. \n\nDoing such checks/comparisons, iterate over all the indices of $$list1$$ for every $$sum$$ value chosen. Whenver a match occurs between $$list1$$ and $$list2$$, we put the matching string in a list $$res$$. \n\nWe do the same process of checking the strings for all the  values of $$sum$$ in ascending order. After completing every iteration over $$list1$$ for a particular $$sum$$, we check if the $$res$$ list is empty or not. If it is empty, we need to continue the process with the next $$sum$$ value considered. If not, the current $$res$$ gives the required list with minimum index sum. This is because we are already considering the index sum values in ascending order. So, the first list to be found is the required resultant list.\n\nThe following example depicts the process:\n\n!?!../Documents/599_Min_Index_Sum.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/HhLorCYq/shared\" frameBorder=\"0\" name=\"HhLorCYq\" width=\"100%\" height=\"309\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O((l_1+l_2)^2*x)$$. There are two nested loops upto $$l_1+l_2$$ and string comparison takes $$x$$ time. Here, $$x$$ refers to the average string length.\n\n* Space complexity : $$O(r*x)$$. $$res$$ list is used to store the result. Assuming $$r$$ is the length of $$res$$.\n\n---\n### Approach #3 Using HashMap (linear) [Accepted]\n\nWe make use of a HashMap to solve the given problem in a different way in this approach. Firstly, we traverse over the whole $$list1$$ and create an entry for each element of $$list1$$ in a HashMap $$map$$, of the form $$(list[i], i)$$. Here, $$i$$ refers to the index of the $$i^{th}$$ element, and $$list[i]$$ is the $$i^{th}$$ element itself. Thus, we create a mapping from the elements of $$list1$$ to their indices.\n\nNow, we traverse over $$list2$$. For every element ,$$list2[j]$$, of $$list2$$ encountered, we check if the same element already exists as a key in the $$map$$. If so, it means that the element exists in both $$list1$$ and $$list2$$. Thus, we find out the sum of indices corresponding to this element in the two lists, given by $sum=map.get(list2[j])+j$. If this $sum$ is less than the minimum sum obtained till now, we update the resultant list to be returned, $$res$$, with the element $$list2[j]$$ as the only entry in it. \n\nIf the $$sum$$ is equal to the minimum sum obtained till now, we put an extra entry corresponding to the element $$list2[j]$$ in the $$res$$ list.\n\nBelow code is inspired by [@cloud.runner](http://leetcode.com/cloud.runner)\n\n<iframe src=\"https://leetcode.com/playground/FatTyfy6/shared\" frameBorder=\"0\" name=\"FatTyfy6\" width=\"100%\" height=\"411\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(l_1+l_2)$$. Every item of $$list2$$ is checked in a map of $$list1$$. $$l_1$$ and $$l_2$$ are the lengths of $$list1$$ and $$list2$$ respectively.\n\n* Space complexity : $$O(l_1*x)$$. hashmap size grows upto $$l_1*x$$, where $$x$$ refers to average string length.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n    ans = []\n    restaurantToIndex = {restaurant: i for i,\n                         restaurant in enumerate(list1)}\n    minSum = math.inf\n\n    for i, restaurant in enumerate(list2):\n      if restaurant in restaurantToIndex:\n        summ = restaurantToIndex[restaurant] + i\n        if summ < minSum:\n          ans.clear()\n        if summ <= minSum:\n          ans.append(restaurant)\n          minSum = summ\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String[] findRestaurant(String[] list1, String[] list2) {\n    List<String> ans = new LinkedList<>();\n    Map<String, Integer> restaurantToIndex = new HashMap<>();\n    int minSum = Integer.MAX_VALUE;\n\n    for (int i = 0; i < list1.length; ++i)\n      restaurantToIndex.put(list1[i], i);\n\n    for (int i = 0; i < list2.length; ++i) {\n      final String restaurant = list2[i];\n      if (restaurantToIndex.containsKey(restaurant)) {\n        final int sum = restaurantToIndex.get(restaurant) + i;\n        if (sum < minSum) {\n          minSum = sum;\n          ans.clear();\n          ans.add(restaurant);\n        } else if (sum == minSum) {\n          ans.add(restaurant);\n        }\n      }\n    }\n\n    return ans.toArray(new String[0]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {\n    vector<string> ans;\n    unordered_map<string, int> restaurantToIndex;\n    int minSum = INT_MAX;\n\n    for (int i = 0; i < list1.size(); ++i)\n      restaurantToIndex[list1[i]] = i;\n\n    for (int i = 0; i < list2.size(); ++i) {\n      const string& restaurant = list2[i];\n      if (restaurantToIndex.count(restaurant)) {\n        const int sum = restaurantToIndex[restaurant] + i;\n        if (sum < minSum) {\n          minSum = sum;\n          ans = {restaurant};\n        } else if (sum == minSum) {\n          ans.push_back(restaurant);\n        }\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/599.html",
    "category": "Algorithms",
    "acceptance_rate": 57.77925489823696,
    "topics": [
      "Array",
      "Hash Table",
      "String"
    ],
    "hints": [],
    "likes": 2032,
    "dislikes": 411,
    "similar_questions": "[{\"title\": \"Intersection of Two Linked Lists\", \"titleSlug\": \"intersection-of-two-linked-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"273.8K\", \"totalSubmission\": \"473.9K\", \"totalAcceptedRaw\": 273813, \"totalSubmissionRaw\": 473895, \"acRate\": \"57.8%\"}",
    "title_pt": "Soma Mínima de Índices de Duas Listas",
    "description_pt": "<p>Dadas duas arrays de strings <code>list1</code> e <code>list2</code>, encontre as <strong>strings comuns com a menor soma de índices</strong>.</p>\n\n<p>Uma <strong>string comum</strong> é uma string que apareceu em ambas <code>list1</code> e <code>list2</code>.</p>\n\n<p>Uma <strong>string comum com a menor soma de índices</strong> é uma string comum tal que, se ela apareceu em <code>list1[i]</code> e <code>list2[j]</code>, então <code>i + j</code> deve ser o valor mínimo entre todas as outras <strong>strings comuns</strong>.</p>\n\n<p>Retorne <em>todas as <strong>strings comuns com a menor soma de índices</strong></em>. Retorne a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;Piatti&quot;,&quot;The Grill at Torrey Pines&quot;,&quot;Hungry Hunter Steakhouse&quot;,&quot;Shogun&quot;]\n<strong>Saída:</strong> [&quot;Shogun&quot;]\n<strong>Explicação:</strong> A única string comum é &quot;Shogun&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> list1 = [&quot;Shogun&quot;,&quot;Tapioca Express&quot;,&quot;Burger King&quot;,&quot;KFC&quot;], list2 = [&quot;KFC&quot;,&quot;Shogun&quot;,&quot;Burger King&quot;]\n<strong>Saída:</strong> [&quot;Shogun&quot;]\n<strong>Explicação:</strong> A string comum com a menor soma de índices é &quot;Shogun&quot; com soma de índices = (0 + 1) = 1.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> list1 = [&quot;happy&quot;,&quot;sad&quot;,&quot;good&quot;], list2 = [&quot;sad&quot;,&quot;happy&quot;,&quot;good&quot;]\n<strong>Saída:</strong> [&quot;sad&quot;,&quot;happy&quot;]\n<strong>Explicação:</strong> Há três strings comuns:\n&quot;happy&quot; com soma de índices = (0 + 1) = 1.\n&quot;sad&quot; com soma de índices = (1 + 0) = 1.\n&quot;good&quot; com soma de índices = (2 + 2) = 4.\nAs strings com a menor soma de índices são &quot;sad&quot; e &quot;happy&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= list1.length, list2.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= list1[i].length, list2[i].length &lt;= 30</code></li>\n\t<li><code>list1[i]</code> e <code>list2[i]</code> consistem de espaços <code>&#39; &#39;</code> e letras do inglês.</li>\n\t<li>Todas as strings de <code>list1</code> são <strong>únicas</strong>.</li>\n\t<li>Todas as strings de <code>list2</code> são <strong>únicas</strong>.</li>\n\t<li>Há pelo menos uma string comum entre <code>list1</code> e <code>list2</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "600",
    "paidOnly": false,
    "title": "Non-negative Integers without Consecutive Ones",
    "titleSlug": "non-negative-integers-without-consecutive-ones",
    "url": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones",
    "description_url": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/description/",
    "description": "<p>Given a positive integer <code>n</code>, return the number of the integers in the range <code>[0, n]</code> whose binary representations <strong>do not</strong> contain consecutive ones.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 5\n<strong>Output:</strong> 5\n<strong>Explanation:</strong>\nHere are the non-negative integers &lt;= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2\n<strong>Output:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/solutions/",
    "solution": "[TOC]\n\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\nThe brute force approach is simple. We can traverse through all the numbers from $$1$$ to $$num$$. For every current number chosen, we can check all the consecutive positions in this number to check if the number contains two consecutive ones or not. If not, we increment the $$count$$ of the resultant numbers with no consecutive ones. \n\nTo check if a $$1$$ exists at the position $$x$$(counting from the LSB side), in the current number $$n$$, we can proceed as follows. We can shift a binary $$1$$ $$x-1$$ times towards the left to get a number $$y$$ which has a $$1$$ only at the $$x^{th}$$ position. Now, logical ANDing of $$n$$ and $$y$$ will result in a logical $$1$$ output only if $$n$$ contains $$1$$ at the $$x^{th}$$ position.\n\n<iframe src=\"https://leetcode.com/playground/EvkBtbbs/shared\" frameBorder=\"0\" name=\"EvkBtbbs\" width=\"100%\" height=\"377\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(32*n)$$. We test  the 32 consecutive positions of every number from $$0$$ to $$n$$. Here, $$n$$ refers to given number. \n\n* Space complexity : $$O(1)$$. Constant space is used.\n\n---\n### Approach #2 Better Brute Force [Time Limit Exceeded]\n\n**Algorithm**\n\nIn the last approach, we generated every number and then checked if it contains consecutive ones at any position or not. Instead of this, we can generate only the required kind of numbers. e.g. If we genearte numbers in the order of the number of bits in the current number, if we get a binary number `110` on the way at the step of 3-bit number generation. Now, since this number already contains two consecutive ones, it is useless to generate number with more number of bits with the current bitstream as the suffix(e.g. numbers of the form `1110` and `0110`).\n\nThe current approach is based on the above idea. We can start with the LSB position, by placing a `0` and a `1` at the LSB. These two initial numbers correspond to the 1-bit numbers which don't contain any consecutive ones. Now, taking `0` as the initial suffix, if we want to generate two bit numbers with no two consecutive 1's, we can append a `1` and a `0` both in front of the initial `0` generating the numbers `10` and `00` as the two bit numbers ending with a `0` with no two consecutive 1's.\n\nBut, when we take `1` as the initial suffix, we can append a `0` to it to generate `01` which doesn't contain any consecutive ones. But, adding a `1` won't satisfy this criteria(`11` will be generated). Thus, while generating the current number, we need to keep a track of the point that whether a `1` was added as the last prefix or not. If yes, we can't append a new `1` and only `0` can be appended. If a `0` was appended as the last prefix, both `0` and `1` can be appended in the new bit-pattern without creating a violating number.\nThus, we can continue forward with the 3-bit number generation only with `00`, `01` and `10` as the new suffixes  in the same manner. \n\nTo get a count of numbers lesser than $$num$$, with no two consecutive 1's, based on the above discussion, we make use of a recursive function `find(i, sum, num, prev)`. This function returns the count of binary numbers with $$i$$ bits with no two consecutive 1's. Here, $$sum$$ refers to the binary number generated till now(the prefix obtained as the input). $$num$$ refers to the given number. $$prev$$ is a boolean variable that indicates whether the last prefix added was a `1` or a `0`.\n\nIf the last prefix was a `0`, we can add both `1` and `0` as the new prefix. Thus, we need to make a function call `find(i + 1, sum, num, false) + find(i + 1, sum + (1 << i), num, true)`. Here, the first sub-part refers to a `0` being added at the $$i^{th}$$ position. Thus, we pass a `false` as the prefix in this case. The second sub-part refers to a `1` being added at the $$i^{th}$$ position. Thus, we pass `true` as the prefix in this case. \n\nIf the last prefix was a `1`, we can add only a `0` as the new prefix. Thus, only one function call `find(i + 1, sum, num, false)` is made in this case. \n\nFurther, we need to stop the number generation whenver the current input number($$sum$$) exceeds the given number $$num$$. \n\n![Tree](../Figures/600_Non_Negative_2.PNG)\n\n<iframe src=\"https://leetcode.com/playground/QN3EABd5/shared\" frameBorder=\"0\" name=\"QN3EABd5\" width=\"100%\" height=\"292\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(x)$$. Only $$x$$ numbers are generated. Here, $$x$$ refers to the resultant count to be returned.\n\n* Space complexity : $$O(log(max\\_int)=32)$$. The depth of recursion tree can go upto $$32$$.\n\n---\n### Approach #3 Using Bit Manipulation [Accepted]\n\n**Algorithm**\n\nBefore we discuss the idea behind this approach, we consider another simple idea that will be used in the current approach. \n\nSuppose, we need to find the count of binary numbers with $$n$$ bits such that these numbers don't contain consecutive 1's. In order to do so, we can look at the problem in a recursive fashion. Suppose $$f[i]$$ gives the count of such binary numbers with $$i$$ bits. In order to determine the value of $$f[n]$$, which is the requirement, we can consider the cases shown below:\n\n![Recursive_Function](../Figures/600_Non_Negative_1.png)\n\nFrom the above figure, we can see that if we know the value of $$f[n-1]$$ and $$f[n-2]$$, in order to generate the required binary numbers with $$n$$ bits, we can append a `0` to all the binary numbers contained in $$f[n-1]$$ without creating an invalid number. These numbers give a factor of $$f[n-1]$$ to be included in $$f[n]$$. But, we can't append a `1` to all these numbers, since it could lead to the presence of two consecutive ones in the newly generated numbers. Thus, for the currently generated numbers to end with a `1`, we need to ensure that the second last position is always `0`. Thus, we need to fix a `01` at the end of all the numbers contained in $$f[n-2]$$. This gives a factor of $$f[n-2]$$ to be included in $$f[n]$$. Thus, in total, we get $$f[n] = f[n-1] + f[n-2]$$.\n\nNow, let's look into the current approach. We'll try to understand the idea behind the approach by taking two simple examples. Firstly, we look at the case where the given number doesn't contain any consecutive 1's.Say, $$num = \\text{1010100}$$(7 bit number). Now, we'll see how we can find the numbers lesser than $$num$$ with no two consecutive 1's. We start off with the MSB of $$nums$$. If we fix a $$\\text{0}$$ at the MSB position, and find out the count of 6 bit numbers(corresponding to the 6 LSBs) with no two consecutive 1's, these 6-bit numbers will lie in the range $$\\textbf{0}\\text{000000} -> \\textbf{0}\\text{111111}$$. For finding this count we can make use of $$f[6]$$ which we'll have already calculated based on the discussion above. \n\nBut, even after doing this, all the numbers in the required range haven't been covered yet. Now, if we try to fix $$\\text{1}$$ at the MSB, the numbers considered will lie in the range $$\\textbf{1}\\text{000000} -> \\textbf{1}\\text{111111}$$. As we can see, this covers the numbers in the range $$\\textbf{1}\\text{000000} -> \\textbf{1}\\text{010100}$$, but it covers the numbers in the range beyond limit as well. Thus, we can't fix $$\\text{1}$$ at the MSB and consider all the 6-bit numbers at the LSBs. \n\nFor covering the pending range, we fix $$\\text{1}$$ at the MSB, and move forward to proceed with the second digit(counting from MSB). Now, since we've already got a $$\\text{0}$$ at this position, we can't substitute a $$\\text{1}$$ here, since doing so will lead to generation of numbers exceeding $$num$$. Thus, the only option left here is to substitute a $$\\text{0}$$ at the second position. But, if we do so, and consider the 5-bit numbers(at the 5 LSBs) with no two consecutive 1's, these new numbers will fall in the range $$\\textbf{10}\\text{00000} -> \\textbf{10}\\text{11111}$$. But, again we can observe that considering these numbers leads to exceeding the required range. Thus, we can't consider all the 5-bit numbers for the required count by fixing $$\\text{0}$$ at the second position. \n\nThus, now, we fix $$\\text{0}$$ at the second position and proceed further. Again, we encounter a $$\\text{1}$$ at the third position. Thus, as discussed above, we can fix a $$\\text{0}$$ at this position and find out the count of 4-bit consecutive numbers with no two consecutive 1's(by varying only the 4 LSB bits). We can obtain this value from $$f[4]$$. Thus, now the numbers in the range $$\\textbf{100}\\text{0000} -> \\textbf{100}\\text{1111}$$ have been covered up. \n\nAgain, as discussed above, now we fix a $$\\text{1}$$ at the third position, and proceed with the fourth bit. It is a $$\\text{0}$$. So, we need to fix it as such as per the above discussion, and proceed with the fifth bit. It is a $$\\text{1}$$. So, we fix a $$\\text{0}$$ here and consider all the numbers by varying the two LSBs for finding the required count of numbers in the range $$\\textbf{10101}\\text{00} -> \\textbf{10101}\\text{11}$$. Now, we proceed to the sixth bit, find a $$\\text{0}$$ there. So, we fix $$\\text{0}$$ at the sixth position and proceed to the seventh bit which is again $$\\text{0}$$. So, we fix a $$\\text{0}$$ at the seventh position as well.\n\nNow, we can see, that based on the above procedure, the numbers in the range $$\\textbf{1}\\text{000000} -> \\textbf{1}\\text{111111}$$, $$\\textbf{100}\\text{0000} -> \\textbf{100}\\text{1111}$$,  $$\\textbf{100}\\text{0000} -> \\textbf{100}\\text{1111}$$ have been considered and the counts for these ranges have been obtained as $$f[6]$$, $$f[4]$$ and $$f[2]$$ respectively. Now, only $$\\text{1010100}$$ is pending to be considered in the required count. Since, it doesn't contain any consecutive 1's, we add a 1 to the total count obtained till now to consider this number. Thus, the result returned is $$f[6] + f[4] + f[2] + 1$$.\n\n!?!../Documents/600_Non_Negative1.json:1000,563!?!\n\nNow, we look at the case, where $$num$$ contains some consecutive 1's. The idea will be the same as the last example, with the only exception taken when the two consecutive 1's are encountered. Let's say, $$num = \\text{1011010}$$(7 bit number). Now, as per the last discussion, we start with the MSB. We find a $$\\text{1}$$ at this position. Thus, we initially fix a $$\\text{0}$$ at this position to consider the numbers in the range $$\\textbf{0}\\text{000000} -> \\textbf{0}\\text{111111}$$, by varying the 6 LSB bits only. The count of the required numbers in this range is again given by $$f[6]$$.\n\nNow, we fix a $$\\text{1}$$ at the MSB and move on to the second bit. It is a $$\\text{0}$$, so we have no choice but to fix $$\\text{0}$$ at this position and to proceed with the third bit. It is a $$\\text{1}$$, so we fix a $$\\text{0}$$ here, considering the numbers in the range $$\\textbf{100}\\text{0000} -> \\textbf{100}\\text{1111}$$. This accounts for a factor of $$f[4]$$. Now, we fix a $$\\text{1}$$ at the third positon, and proceed with the fourth bit. It is a $$\\text{1}$$(consecutive to the previous $$\\text{1}$$). Now, initially we fix a $$\\text{0}$$ at the fourth position, considering the numbers in the range $$\\textbf{1010}\\text{000} -> \\textbf{1010}\\text{111}$$. This adds a factor of $$f[3]$$ to the required count. \n\nNow, we can see that till now the numbers in the range $$\\textbf{0}\\text{000000} -> \\textbf{0}\\text{111111}$$, $$\\textbf{100}\\text{0000} -> \\textbf{100}\\text{1111}$$, $$\\textbf{1010}\\text{000} -> \\textbf{1010}\\text{111}$$ have been considered. But, if we try to consider any number larger than $$\\text{1010111}$$, it leads to the presence of two consecutive 1's in the new number at the third and fourth position. Thus, all the valid numbers upto $$num$$ have been considered with this, giving a resultant count of $$f[6] + f[4] + f[3]$$.\n\n!?!../Documents/600_Non_Negative2.json:1000,563!?!\n\nThus, summarizing the above discussion, we can say that we start scanning the given number $$num$$ from its MSB. For every 1 encountered at the $$i^{th}$$ bit position(counting from 0 from LSB), we add a factor of $$f[i]$$ to the resultant count. For every 0 encountered, we don't add any factor. We also keep a track of the last bit checked. If we happen to find two consecutive 1's at any time, we add the factors for the positions of both the 1's and stop the traversal immediately. If we don't find any two consecutive 1's, we proceed till reaching the LSB and add an extra 1 to account for the given number $$num$$ as well, since the procedure discussed above considers numbers upto $$num$$ without including itself.\n \n<iframe src=\"https://leetcode.com/playground/NbrrZGdh/shared\" frameBorder=\"0\" name=\"NbrrZGdh\" width=\"100%\" height=\"462\"></iframe>\n**Complexity Analysis**\n\n* Time complexity : $$O(log_2(max\\_int)=32)$$. One loop to fill $$f$$ array and one loop to check all bits of $$num$$.\n\n* Space complexity : $$O(log_2(max\\_int)=32)$$. $$f$$ array of size 32 is used.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findIntegers(int num) {\n    StringBuilder bits = new StringBuilder();\n    for (; num > 0; num >>= 1)\n      bits.append(num & 1);\n\n    final int n = bits.length();\n    int[] zero = new int[n];\n    int[] one = new int[n];\n\n    zero[0] = 1;\n    one[0] = 1;\n\n    for (int i = 1; i < n; ++i) {\n      zero[i] = zero[i - 1] + one[i - 1];\n      one[i] = zero[i - 1];\n    }\n\n    int ans = zero[n - 1] + one[n - 1];\n\n    for (int i = n - 2; i >= 0; --i) {\n      // Numbers greater than num and <= 2^n - 1 are invalid\n      if (bits.charAt(i) == '1' && bits.charAt(i + 1) == '1')\n        break;\n      if (bits.charAt(i) == '0' && bits.charAt(i + 1) == '0')\n        ans -= one[i];\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findIntegers(int num) {\n    string bits;\n    for (; num; num >>= 1)\n      bits += to_string(num & 1);\n\n    const int n = bits.length();\n    vector<int> zero(n, 1);\n    vector<int> one(n, 1);\n\n    for (int i = 1; i < n; ++i) {\n      zero[i] = zero[i - 1] + one[i - 1];\n      one[i] = zero[i - 1];\n    }\n\n    int ans = zero[n - 1] + one[n - 1];\n\n    for (int i = n - 2; i >= 0; --i) {\n      // Numbers greater than num and <= 2^n - 1 are invalid\n      if (bits[i] == '1' && bits[i + 1] == '1')\n        break;\n      if (bits[i] == '0' && bits[i + 1] == '0')\n        ans -= one[i];\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/600.html",
    "category": "Algorithms",
    "acceptance_rate": 40.1974586508506,
    "topics": [
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 1566,
    "dislikes": 137,
    "similar_questions": "[{\"title\": \"House Robber\", \"titleSlug\": \"house-robber\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber II\", \"titleSlug\": \"house-robber-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ones and Zeroes\", \"titleSlug\": \"ones-and-zeroes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Generate Binary Strings Without Adjacent Zeros\", \"titleSlug\": \"generate-binary-strings-without-adjacent-zeros\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"44.3K\", \"totalSubmission\": \"110.1K\", \"totalAcceptedRaw\": 44257, \"totalSubmissionRaw\": 110099, \"acRate\": \"40.2%\"}",
    "title_pt": "Inteiros Não Negativos sem Uns Consecutivos",
    "description_pt": "<p>Dado um inteiro positivo <code>n</code>, retorne o número de inteiros no intervalo <code>[0, n]</code> cujas representações binárias <strong>não</strong> contêm uns consecutivos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong>\nAqui estão os inteiros não negativos &lt;= 5 com suas representações binárias correspondentes:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nEntre eles, apenas o inteiro 3 viola a regra (dois uns consecutivos) e os outros 5 satisfazem a regra. \n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2\n<strong>Saída:</strong> 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "601",
    "paidOnly": false,
    "title": "Human Traffic of Stadium",
    "titleSlug": "human-traffic-of-stadium",
    "url": "https://leetcode.com/problems/human-traffic-of-stadium",
    "description_url": "https://leetcode.com/problems/human-traffic-of-stadium/description/",
    "description": "<p>Table: <code>Stadium</code></p>\n\n<pre>\n+---------------+---------+\n| Column Name   | Type    |\n+---------------+---------+\n| id            | int     |\n| visit_date    | date    |\n| people        | int     |\n+---------------+---------+\nvisit_date is the column with unique values for this table.\nEach row of this table contains the visit date and visit id to the stadium with the number of people during the visit.\nAs the id increases, the date increases as well.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to display the records with three or more rows with <strong>consecutive</strong> <code>id</code>&#39;s, and the number of people is greater than or equal to 100 for each.</p>\n\n<p>Return the result table ordered by <code>visit_date</code> in <strong>ascending order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nStadium table:\n+------+------------+-----------+\n| id   | visit_date | people    |\n+------+------------+-----------+\n| 1    | 2017-01-01 | 10        |\n| 2    | 2017-01-02 | 109       |\n| 3    | 2017-01-03 | 150       |\n| 4    | 2017-01-04 | 99        |\n| 5    | 2017-01-05 | 145       |\n| 6    | 2017-01-06 | 1455      |\n| 7    | 2017-01-07 | 199       |\n| 8    | 2017-01-09 | 188       |\n+------+------------+-----------+\n<strong>Output:</strong> \n+------+------------+-----------+\n| id   | visit_date | people    |\n+------+------------+-----------+\n| 5    | 2017-01-05 | 145       |\n| 6    | 2017-01-06 | 1455      |\n| 7    | 2017-01-07 | 199       |\n| 8    | 2017-01-09 | 188       |\n+------+------------+-----------+\n<strong>Explanation:</strong> \nThe four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has &gt;= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7.\nThe rows with ids 2 and 3 are not included because we need at least three consecutive ids.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/human-traffic-of-stadium/solutions/",
    "solution": "​\n<!-- Don't delete this -->\n[TOC]\n​\n# Solution\n​\n---\n​\n## pandas\n​\nWe offer two ways to approach this problem of finding consecutive values. One way is to use the functions [`shift()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.shift.html) and [`diff()`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.diff.html) to compare the values between the current row and the previous rows. Another way, inspired by the idea of 'gaps and islands', is to find the islands (consecutive values) from all rows. You can learn more about this [concept](https://www.mssqltips.com/sqlservertutorial/9130/sql-server-window-functions-gaps-and-islands-problem/) if you are interested in this idea. \n\n<!-- h3 for approaches -->\n### Approach 1: Examine Previous Rows Using shift() and diff()\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nFor this approach, we find the consecutive `id`s by calculating 1) the differences between the current `id` and the last `id` and 2) the differences between the last `id` and the `id` before the last `id`. If both differences are equal to 1, we find the 3rd  `id` in the three consecutive `id`s.\n\nWe start with creating a new DataFrame to store only the records with `people` larger than or equal to 100 from the DataFrame `stadium` since we only need to find consecutive `id`s from these records. \n\n```python\ndf = stadium[stadium['people'] >= 100]\n```\n\nThe new DataFrame is as follows: \n\n| id | visit_date | people |\n| -- | ---------- | ------ |\n| 2  | 2017-01-02 | 109    |\n| 3  | 2017-01-03 | 150    |\n| 5  | 2017-01-05 | 145    |\n| 6  | 2017-01-06 | 1455   |\n| 7  | 2017-01-07 | 199    |\n| 8  | 2017-01-09 | 188    |\n\nNow we can start to identify the consecutive `id`s. For the difference between the current `id` and the `id` of the previous row, we can simply find the difference using `diff()`; for the difference between the `id` of the previous row and the `id` before the previous row, we can use both `diff()` and `shift(1)`. If both differences are equal to 1, the `id` of the current row is the third ID in the three consecutive `id`s, and the new column `flag` created will mark these rows that contain the valid third ID as `True`.\n\n```python\ndf['flag'] = ((df['id'].diff() == 1) & (df['id'].diff().shift(1) == 1))\n```\n\nHere is what the output looks like: \n\n| id | visit_date | people | flag  |\n| -- | ---------- | ------ | ----- |\n| 2  | 2017-01-02 | 109    | null  |\n| 3  | 2017-01-03 | 150    | null  |\n| 5  | 2017-01-05 | 145    | false |\n| 6  | 2017-01-06 | 1455   | false |\n| 7  | 2017-01-07 | 199    | true  |\n| 8  | 2017-01-09 | 188    | true  |\n\nSince the row with `flag` equal to `True` is always the 3rd `id` in any three or more consecutive `id`s group, we only need to figure out how to select not only the rows with `flag` equal to `True`, but also their previous two rows.\n\n```python\ndf = df[(df['flag'] == True)| (df['flag'].shift(-1) == True) | (df['flag'].shift(-2) == True)]\n```\n\nBelow are all the records with three or more consecutive `id`s.\n\n| id | visit_date | people | flag  |\n| -- | ---------- | ------ | ----- |\n| 5  | 2017-01-05 | 145    | false |\n| 6  | 2017-01-06 | 1455   | false |\n| 7  | 2017-01-07 | 199    | true  |\n| 8  | 2017-01-09 | 188    | true  |\n\n\nSo close! We want to clean the output as requested by the problem: we remove the column `flag` from the output, and order the result by the column `visit_date`. \n\n```python\nreturn df.loc[:, df.columns != 'flag'].sort_values(by='visit_date')\n```\n\n<!-- h4 for sections -->\n#### Implementation\n​​<iframe src=\"https://leetcode.com/playground/LdDpRuc4/shared\" frameBorder=\"0\" width=\"100%\" height=\"242\" name=\"LdDpRuc4\"></iframe>\n<!-- an empty line to separate approaches -->\n\n<!-- h3 for approaches -->\n### Approach 2: Finding the Islands\n\n<!-- h4 for sections -->\n#### Algorithm\n​<!-- Describe your approach to solving the problem. -->\nThe key to identifying the islands (consecutive values) from a column is to calculate the difference between the column (in this problem, it is the column `id`) and a new rank (looks like an index id) we append to all rows. Any islands will be some consecutive rows that share the same result from this calculation. If all `id`s are consecutive, the differences between this new rank and the `id` will be the same for all rows, in other words, all rows belong to this one island. If no `id`s are consecutive, every row will return a different value from this calculation, and no island is identified.\n\nTo begin with, we update the original DataFrame to get only the records with `people` larger than or equal to 100 since we only need to find consecutive `id`s from these records.\n\n```python\nstadium = stadium[stadium['people'] >= 100]\n```\n| id | visit_date | people |\n| -- | ---------- | ------ |\n| 2  | 2017-01-02 | 109    |\n| 3  | 2017-01-03 | 150    |\n| 5  | 2017-01-05 | 145    |\n| 6  | 2017-01-06 | 1455   |\n| 7  | 2017-01-07 | 199    |\n| 8  | 2017-01-09 | 188    |\n\nNow we can start to identify the islands (consecutive values). To do this, we first create our rank of the records and store it in a separate column `rnk` for future calculations. \n\n```python\nstadium['rnk'] = range(len(stadium))\n```\n| id | visit_date | people | rnk |\n| -- | ---------- | ------ | --- |\n| 2  | 2017-01-02 | 109    | 0   |\n| 3  | 2017-01-03 | 150    | 1   |\n| 5  | 2017-01-05 | 145    | 2   |\n| 6  | 2017-01-06 | 1455   | 3   |\n| 7  | 2017-01-07 | 199    | 4   |\n| 8  | 2017-01-09 | 188    | 5   |\n\nThen we calculate the difference between the column `rnk` and the original column `id`, and save this result in a new column `island`.\n\n```python\nstadium['island'] = stadium.id - stadium.rnk\n```\n\nWe can see from the output that two islands are discovered from the records (the islands are the rows sharing the same values in the new column `island`). \n\n| id | visit_date | people | rnk | island |\n| -- | ---------- | ------ | --- | ------ |\n| 2  | 2017-01-02 | 109    | 0   | 2      |\n| 3  | 2017-01-03 | 150    | 1   | 2      |\n| 5  | 2017-01-05 | 145    | 2   | 3      |\n| 6  | 2017-01-06 | 1455   | 3   | 3      |\n| 7  | 2017-01-07 | 199    | 4   | 3      |\n| 8  | 2017-01-09 | 188    | 5   | 3      |\n\nHowever, not all islands are qualified for this problem. We want to make sure the island contains three or more rows since we are looking for three or more consecutive `id`s. To get this count, we group the rows by the column `island` and count how many `id`s are contained in each group. We store this aggregated count along with each row in a separate column called `island_cnt`. \n\n```python\nstadium['island_cnt'] = stadium.groupby(['island'], as_index=False).id.transform('count')\n```\n\nThe output looks like this: \n\n| id | visit_date | people | rnk | island | island_cnt |\n| -- | ---------- | ------ | --- | ------ | ---------- |\n| 2  | 2017-01-02 | 109    | 0   | 2      | 2          |\n| 3  | 2017-01-03 | 150    | 1   | 2      | 2          |\n| 5  | 2017-01-05 | 145    | 2   | 3      | 4          |\n| 6  | 2017-01-06 | 1455   | 3   | 3      | 4          |\n| 7  | 2017-01-07 | 199    | 4   | 3      | 4          |\n| 8  | 2017-01-09 | 188    | 5   | 3      | 4          |\n\n​\nNow we can identify the qualified islands, which are records in an island and with a count (`island_cnt`) larger than or equal to 3. \n\n```python\nreturn stadium[stadium['island_cnt'] >= 3]\n```\n\nLast but not least, we select only the needed columns and sort the result by `visit_date` as the problem requested. We can add these steps to the previous step.\n\n```python\nreturn stadium[stadium['island_cnt'] >= 3][['id', 'visit_date', 'people']].sort_values(by='visit_date')\n```\n\n\n<!-- h4 for sections -->\n#### Implementation\n​<iframe src=\"https://leetcode.com/playground/E9TdkdEj/shared\" frameBorder=\"0\" width=\"100%\" height=\"242\" name=\"E9TdkdEj\"></iframe>\n\n---\n​\n​\n## Database\nWe provide three different ways to solve this problem of identifying consecutive values. If the problem doesn't require too many consecutive rows (say, 5?), we can create table aliases and manually compare the differences from the rows of each table alias. For better performance, or if the problem is looking for too many consecutive rows, we can use window functions `LEAD()` or `LAG()` to append values from the previous and next rows and calculate the differences between them. If you are interested in a more graceful way to approach this problem, you probably want to learn a bit more about the idea of ['gap and island'](https://www.mssqltips.com/sqlservertutorial/9130/sql-server-window-functions-gaps-and-islands-problem/), and we will also provide an approach using this concept.\n\nThere are some similar questions you can practice once you have mastered the methodologies: [180](https://leetcode.com/problems/consecutive-numbers/), [603](https://leetcode.com/problems/consecutive-available-seats/), [1454](https://leetcode.com/problems/active-users/)\n\n<!-- h3 for approaches -->\n### Approach 1: Using Self-Join\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nThe number of consecutive values we need to identify decides how many table aliases we need to create. For this problem, the number is three. Since we are only interested in the records with people greater than or equal to 100, we can also add the filter to all three table aliases in this step. \n\n```sql\nSELECT \n    *\nFROM \n    stadium AS a, stadium AS b, stadium AS c\nWHERE\n    a.people >= 100 AND b.people >= 100 AND c.people >= 100\n```\n​\nNow we can identify the consecutive `id`s by calculating the differences between `id`s from each table alias. \n\nIf the three `id`s are consecutive from table a, b, and c, which means the difference between the two `id`s are 1, we can add filters like below: \n\n```sql\nWHERE (a.id - b.id = 1 AND b.id - c.id = 1)\n```\n\nBut how can we select all three `id`s from three table aliases and put these `id`s into one column instead of multiple columns? A workaround is to put one table alias, in this approach we select table a, in all possible positions of the three consecutive `id`s. \n\nWhen a.`id` is the **minimum** `id` in the three consecutive `id`s (c.`id` > b.`id` > a.`id`):\n```sql\n(c.id - b.id = 1 AND b.id - a.id = 1)\n```\n\nWhen a.`id` is in the **middle** of the three consecutive `id`s (b.`id` > a.`id` > c.`id`):\n```sql\n(b.id - a.id = 1 AND a.id - c.id = 1)\n```\n\nNow we can just `SELECT` records from table a and `ORDER` the results by `visit_date` as requested. \n\n<!-- h4 for sections -->\n#### Implementation\n\n```mysql []\nSELECT \n    DISTINCT a.*\nFROM \n    stadium AS a, stadium AS b, stadium AS c\nWHERE\n     a.people >= 100 AND b.people >= 100 AND c.people >= 100\nAND \n    (\n       (a.id - b.id = 1 AND b.id - c.id = 1)\n    OR (c.id - b.id = 1 AND b.id - a.id = 1)\n    OR (b.id - a.id = 1 AND a.id - c.id = 1)\n    )\nORDER BY visit_date\n```\n\n<br>\n\n<!-- an empty line to separate approaches -->\n\n### Approach 2: Using Window Functions\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nFor this approach, we append the values from the previous and next rows by using `LEAD()` and `LAG()` and then compare the differences to find the consecutive values. We can also apply the filter to identify only the records with people greater than or equal to 100 in this step. The output will be stored in a CTE for future use.  \n\n```sql\nWITH base AS (\n        SELECT *,\n            LEAD(id, 1) OVER(ORDER BY id) AS next_id,\n            LEAD(id, 2) OVER(ORDER BY id) AS second_next_id,\n            LAG(id, 1) OVER(ORDER BY id) AS last_id,\n            LAG(id, 2) OVER(ORDER BY id) AS second_last_id\n        FROM stadium\n        WHERE people >= 100 \n        )\n```\n\nBelow is what the CTE `base` looks like. Notice the new `id` columns created by `LEAD()` and `LAG()` do not include the records that are filtered out, which is exactly what we are looking for. \n\n| id | visit_date | people | next_id | second_next_id | last_id | second_last_id |\n| -- | ---------- | ------ | ------- | -------------- | ------- | -------------- |\n| 2  | 2017-01-02 | 109    | 3       | 5              | null    | null           |\n| 3  | 2017-01-03 | 150    | 5       | 6              | 2       | null           |\n| 5  | 2017-01-05 | 145    | 6       | 7              | 3       | 2              |\n| 6  | 2017-01-06 | 1455   | 7       | 8              | 5       | 3              |\n\n\n\nNow we can start to identify the consecutive `id`s. Since we want to return all the records with three or more consecutive `id`s, we want to make sure the `id` from the current is in any of the possible positions within the three consecutive `id`s. \n\nWhen `id` is in the **middle** of the three consecutive `id`s and the order is `next_id` > `id` > `last_id`:\n```sql\nWHERE (next_id - id = 1 AND id - last_id = 1)\n```\n\nWhen `id` is the **minimum** `id` of the three consecutive `id`s and the order is `second_next_id` > `next_id` > `id`:\n```sql\nOR (second_next_id - next_id = 1 AND next_id - id = 1)\n```\n\nWhen `id` is the **maximum** `id` of the three consecutive `id`s and the order is `id` > `last_id` > `second_last_id`: \n```sql\nOR (id - last_id = 1 AND last_id - second_last_id = 1)\n```\n\nNow the only thing left us to do is to update the output by selecting the required columns and order the result by `visit_date` in the main query.\n\n```sql\nSELECT DISTINCT id, visit_date, people\nFROM base \nWHERE (next_id - id = 1 AND id - last_id = 1)\n    OR (second_next_id - next_id = 1 AND next_id - id = 1)\n    OR (id - last_id = 1 AND last_id - second_last_id = 1)\nORDER BY visit_date\n```\n\n<!-- h4 for sections -->\n#### Implementation\n\n```mysql []\nWITH base AS (\n        SELECT *,\n            LEAD(id, 1) OVER(ORDER BY id) AS next_id,\n            LEAD(id, 2) OVER(ORDER BY id) AS second_next_id,\n            LAG(id, 1) OVER(ORDER BY id) AS last_id,\n            LAG(id, 2) OVER(ORDER BY id) AS second_last_id\n        FROM stadium\n        WHERE people >= 100 \n        )\nSELECT DISTINCT id, visit_date, people\nFROM base \nWHERE (next_id - id = 1 AND id - last_id = 1)\n    OR (second_next_id - next_id = 1 AND next_id - id = 1)\n    OR (id - last_id = 1 AND last_id - second_last_id = 1)\nORDER BY visit_date\n```\n\n<br>\n\n<!-- an empty line to separate approaches -->\n\n### Approach 3: Finding the Islands\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nThe key to identifying the islands (consecutive values) from a column is to calculate the difference between the column (in this problem, it is the column `id`) and a new rank (looks like an index id) we append to all rows. Any islands will be the rows that share the same result from this calculation. If all `id`s are consecutive, the differences between this new rank and the `id` will be the same for all rows, in other words, all rows belong to this one island. If no `id`s are consecutive, every row will return a different value from this calculation, and no island is identified.\n\nFor this problem, we want to identify the islands (consecutive values) from all the records. To do this, we need to create a new rank for all the qualified records, which are the records of people greater than or equal to 100. Either `RANK()` or `ROW_NUMBER()` works for this purpose. \n\n```sql\nSELECT id, visit_date, people, RANK()OVER(ORDER BY id) AS rnk\nFROM Stadium\nWHERE people >= 100\n```\n\nNow we have a new column, `rnk`, in addition to the original `id`:\n\n| id | visit_date | people | rnk |\n| -- | ---------- | ------ | --- |\n| 2  | 2017-01-02 | 109    | 1   |\n| 3  | 2017-01-03 | 150    | 2   |\n| 5  | 2017-01-05 | 145    | 3   |\n\n​\nWith these new ranks for the records, we can identify the islands by calculating the differences between `id` and `rnk`. We store the result of this calculation in a new column called `island` and save the output in a CTE, `stadium with rnk`, for future use. \n\n```sql\nWITH stadium_with_rnk AS\n(\n    SELECT id, visit_date, people, rnk, (id - rnk) AS island\n    FROM (\n        SELECT id, visit_date, people, RANK() OVER(ORDER BY id) AS rnk\n        FROM Stadium\n        WHERE people >= 100) AS t0\n)\n```\n\nThe records sharing the same value in the column `island` are the ones with consecutive `id`s:\n\n| id | visit_date | people | rnk | island |\n| -- | ---------- | ------ | --- | ------ |\n| 2  | 2017-01-02 | 109    | 1   | 1      |\n| 3  | 2017-01-03 | 150    | 2   | 1      |\n| 5  | 2017-01-05 | 145    | 3   | 2      |\n| 6  | 2017-01-06 | 1455   | 4   | 2      |\n| 7  | 2017-01-07 | 199    | 5   | 2      |\n| 8  | 2017-01-09 | 188    | 6   | 2      |\n\n\nHowever, we only want islands with three or more consecutive `id`s. To identify these islands, we group the record by the column `island`, and filter the aggregated groups to get the qualified islands.  \n\n```sql\nSELECT island \nFROM stadium_with_rnk\nGROUP BY island\nHAVING COUNT(*) >= 3\n```\n\n| island |\n| ------ |\n| 2      |\n\nNow With the qualified islands identified, we can select all records associated with these islands. We put the previous step in a subquery and use it as a filter. In the main query, we only select the requested columns from the island and sort the result by `visit_date`. \n\n```sql\nSELECT id, visit_date, people \nFROM stadium_with_rnk\nWHERE island IN (SELECT island \n                 FROM stadium_with_rnk \n                 GROUP BY island \n                 HAVING COUNT(*) >= 3)\nORDER BY visit_date\n```\n\n<!-- h4 for sections -->\n\n#### Implementation\n\n```mysql []\nWITH stadium_with_rnk AS\n(\n    SELECT id, visit_date, people, rnk, (id - rnk) AS island\n    FROM (\n        SELECT id, visit_date, people, RANK() OVER(ORDER BY id) AS rnk\n        FROM Stadium\n        WHERE people >= 100) AS t0\n)\nSELECT id, visit_date, people \nFROM stadium_with_rnk\nWHERE island IN (SELECT island \n                 FROM stadium_with_rnk \n                 GROUP BY island \n                 HAVING COUNT(*) >= 3)\nORDER BY visit_date\n```\n<!-- an empty line to separate approaches -->\n<br>",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/601.html",
    "category": "Database",
    "acceptance_rate": 49.71350508918092,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 747,
    "dislikes": 572,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"129.2K\", \"totalSubmission\": \"259.9K\", \"totalAcceptedRaw\": 129188, \"totalSubmissionRaw\": 259865, \"acRate\": \"49.7%\"}",
    "title_pt": "Tráfego Humano do Estádio",
    "description_pt": "<p>Tabela: <code>Stadium</code></p>\n\n<pre>\n+---------------+---------+\n| Nome da Coluna | Tipo   |\n+---------------+---------+\n| id            | int     |\n| visit_date    | date    |\n| people        | int     |\n+---------------+---------+\nvisit_date é a coluna com valores únicos para esta tabela.\nCada linha desta tabela contém a data da visita e o id da visita ao estádio, juntamente com o número de pessoas durante a visita.\nÀ medida que o id aumenta, a data também aumenta.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para exibir os registros com três ou mais linhas com <strong>ids</strong> <code>consecutivos</code>, e o número de pessoas é maior ou igual a 100 em cada uma delas.</p>\n\n<p>Retorne a tabela de resultado ordenada por <code>visit_date</code> em <strong>ordem crescente</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Stadium:\n+------+------------+-----------+\n| id   | visit_date | people    |\n+------+------------+-----------+\n| 1    | 2017-01-01 | 10        |\n| 2    | 2017-01-02 | 109       |\n| 3    | 2017-01-03 | 150       |\n| 4    | 2017-01-04 | 99        |\n| 5    | 2017-01-05 | 145       |\n| 6    | 2017-01-06 | 1455      |\n| 7    | 2017-01-07 | 199       |\n| 8    | 2017-01-09 | 188       |\n+------+------------+-----------+\n<strong>Saída:</strong> \n+------+------------+-----------+\n| id   | visit_date | people    |\n+------+------------+-----------+\n| 5    | 2017-01-05 | 145       |\n| 6    | 2017-01-06 | 1455      |\n| 7    | 2017-01-07 | 199       |\n| 8    | 2017-01-09 | 188       |\n+------+------------+-----------+\n<strong>Explicação:</strong> \nAs quatro linhas com ids 5, 6, 7 e 8 têm ids consecutivos e cada uma delas tem >= 100 pessoas presentes. Observe que a linha 8 foi incluída mesmo que visit_date não tenha sido o dia seguinte à linha 7.\nAs linhas com ids 2 e 3 não estão incluídas porque precisamos de pelo menos três ids consecutivos.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "602",
    "paidOnly": false,
    "title": "Friend Requests II: Who Has the Most Friends",
    "titleSlug": "friend-requests-ii-who-has-the-most-friends",
    "url": "https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends",
    "description_url": "https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/",
    "description": "<p>Table: <code>RequestAccepted</code></p>\n\n<pre>\n+----------------+---------+\n| Column Name    | Type    |\n+----------------+---------+\n| requester_id   | int     |\n| accepter_id    | int     |\n| accept_date    | date    |\n+----------------+---------+\n(requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table.\nThis table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the people who have the most friends and the most friends number.</p>\n\n<p>The test cases are generated so that only one person has the most friends.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nRequestAccepted table:\n+--------------+-------------+-------------+\n| requester_id | accepter_id | accept_date |\n+--------------+-------------+-------------+\n| 1            | 2           | 2016/06/03  |\n| 1            | 3           | 2016/06/08  |\n| 2            | 3           | 2016/06/08  |\n| 3            | 4           | 2016/06/09  |\n+--------------+-------------+-------------+\n<strong>Output:</strong> \n+----+-----+\n| id | num |\n+----+-----+\n| 3  | 3   |\n+----+-----+\n<strong>Explanation:</strong> \nThe person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong> In the real world, multiple people could have the same most number of friends. Could you find all these people in this case?</p>\n",
    "solution_url": "https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/solutions/",
    "solution": "​\n<!-- Don't delete this -->\n[TOC]\n​\n# Solution\n​\n---\n​\n## pandas\n\n<!-- h3 for approaches -->\n### Approach: Combining DataFrames Using concat() and Finding the Top Values Using sort_values() and head()\n\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nSince one person can acquire a friend by either requesting or accepting a friend request, to get how many friends each person has, we can count how many times their id appeared in either the column `requester_id` or the column `accepter_id`. It's generally a good idea to combine the two columns into one for easier calculation. \n\nLet's start by combining the two columns. We can leverage the function `concat()` to combine DataFrames just like using `UNION/UNION ALL` in MySQL, or, in this case, combine only the columns. We add the function `to_frame()` to convert the result from a Series to a DataFrame. For later calculation, we also renamed the newly created column as `id`.\n\n```python\nvalues = pd.concat([request_accepted[\"requester_id\"], request_accepted[\"accepter_id\"]]).to_frame('id')\n```\n\nWe now have the two columns `requester_id` and `accepter_id` combined into one. \n\n| id |\n| -- |\n| 1  |\n| 1  |\n| 2  |\n| 3  |\n| 2  |\n| 3  |\n| 3  |\n| 4  |\n\nNow we only need to count how many times each `id` appeared in the list and identify the `id` with the maximum count. To do this, we can apply `count()` to `id` and group the result at the `id` level. We can leverage the function `agg()` to get the aggregate value and rename the result at the same time. To look for the maximum count, we sort the list by the count (the newly created column `num`) in descending order using the function `sort_values()` and passing the parameter `ascending=False` to the function. The `id` that has the most friends is now listed at the top, and we can select this record using the function `head()`.  \n\n```python\ndf = values.groupby('id', as_index=False).agg(num=('id', 'count')).sort_values('num', ascending=False).head(1)\n```\n\n<!-- h4 for sections -->\n#### Implementation\n​<iframe src=\"https://leetcode.com/playground/mLCXWMTb/shared\" frameBorder=\"0\" width=\"100%\" height=\"191\" name=\"mLCXWMTb\"></iframe>\n<!-- an empty line to separate approaches -->\n\n----\n​\n​\n## Database\n\n\n<!-- h3 for approaches -->\n### Approach 1: Combining Tables Using UNION ALL and Finding the Top Values Using ORDER BY + LIMIT\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\n\nSince one person can acquire a friend by either requesting or accepting a friend request, to get how many friends each person has, we can count how many times their id appeared in either the column `requester_id` or the column `accepter_id`. It's generally a good idea to combine the two columns into one for easier calculation. \n\nLet's start by combining the two columns. For this problem, it's important to use `UNION ALL` so all duplicate values are kept. Both columns are renamed as `id`, and we can put this step in a CTE for later usage. \n\n```sql\nWITH all_ids AS (\n   SELECT requester_id AS id \n   FROM RequestAccepted\n   UNION ALL\n   SELECT accepter_id AS id\n   FROM RequestAccepted)\n```\n\nNext, we can count how many times each `id` appeared in the list and identify the `id` with the maximum count. To do this, we can group the aggregate value `COUNT(id)` at the `id` level. To retain only the `id` that has the maximum counts, we can sort the result by the `COUNT(id)` in descending order and take only the first record using `LIMIT`. Last but not least, we rename the aggregate count to `num` for the final output. All of these steps can be achieved in the main query without creating any subqueries. \n\n\n```sql\nSELECT id, \n   COUNT(id) AS num\nFROM all_ids\nGROUP BY id\nORDER BY COUNT(id) DESC\nLIMIT 1\n```\n\n<!-- h4 for sections -->\n#### Implementation\n\n```mysql []\nWITH all_ids AS (\n   SELECT requester_id AS id \n   FROM RequestAccepted\n   UNION ALL\n   SELECT accepter_id AS id\n   FROM RequestAccepted)\nSELECT id, \n   COUNT(id) AS num\nFROM all_ids\nGROUP BY id\nORDER BY COUNT(id) DESC\nLIMIT 1\n```\n​\n<!-- an empty line to separate approaches -->\n\n\n### Approach 2: Combining Tables Using UNION ALL and Finding Top Values Using RANK()\n\n<!-- h4 for sections -->\n#### Algorithm\n\n<!-- Describe your approach to solving the problem. -->\nThe main difference between this approach and the first one is that this approach can include multiple `id`s if there is more than one person who has the most number of friends. Also, it's never a bad idea to use the window function.  \n\nSimilarly, we can start by combining the two columns into one. For this problem, it's important to use `UNION ALL` so all duplicate values are kept. Both columns are renamed as `id`, and we can put this step in a CTE for later usage. \n\n\n```sql\nWITH all_ids AS (\n   SELECT requester_id AS id \n   FROM RequestAccepted\n   UNION ALL\n   SELECT accepter_id AS id\n   FROM RequestAccepted)\n```\n\nIn the subquery, we can count how many times each `id` appeared in the list using `COUNT()` and `GROUP` the result at the `id` level. The calculated result is renamed to `num` as requested by the final output. Additionally, we can append a rank to the records per the aggregate count in descending order. \n\n```sql\n   (\n   SELECT id, \n      COUNT(id) AS num, \n      RANK () OVER(ORDER BY COUNT(id) DESC) AS rnk\n   FROM all_ids\n   GROUP BY id\n   )t0\n```\n\nNow we can select the top record, which is the `id` that has the maximum count (number of friends), in the main query. \n\n```sql\nSELECT id, num\nFROM \n   (\n   SELECT id, \n      COUNT(id) AS num, \n      RANK () OVER(ORDER BY COUNT(id) DESC) AS rnk\n   FROM all_ids\n   GROUP BY id\n   )t0\nWHERE rnk=1\n```\n\n<!-- h4 for sections -->\n#### Implementation\n\n```mysql []\nWITH all_ids AS (\n   SELECT requester_id AS id \n   FROM RequestAccepted\n   UNION ALL\n   SELECT accepter_id AS id\n   FROM RequestAccepted)\nSELECT id, num\nFROM \n   (\n   SELECT id, \n      COUNT(id) AS num, \n      RANK () OVER(ORDER BY COUNT(id) DESC) AS rnk\n   FROM all_ids\n   GROUP BY id\n   )t0\nWHERE rnk=1\n```\n----",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/602.html",
    "category": "Database",
    "acceptance_rate": 60.64270034905898,
    "topics": [
      "Database"
    ],
    "hints": [
      "Being friends is bidirectional. If you accept someone's adding friend request, both you and the other person will have one more friend."
    ],
    "likes": 789,
    "dislikes": 139,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"235.9K\", \"totalSubmission\": \"389K\", \"totalAcceptedRaw\": 235916, \"totalSubmissionRaw\": 389034, \"acRate\": \"60.6%\"}",
    "title_pt": "Pedidos de Amizade II: Quem Tem Mais Amigos",
    "description_pt": "<p>Tabela: <code>RequestAccepted</code></p>\n\n<pre>\n+----------------+---------+\n| Column Name    | Type    |\n+----------------+---------+\n| requester_id   | int     |\n| accepter_id    | int     |\n| accept_date    | date    |\n+----------------+---------+\n(requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table.\nThis table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar as pessoas que têm o maior número de amigos e a quantidade de amigos mais alta.</p>\n\n<p>Os casos de teste são gerados de forma que apenas uma pessoa tenha o maior número de amigos.</p>\n\n<p>O formato do resultado é mostrado no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nRequestAccepted table:\n+--------------+-------------+-------------+\n| requester_id | accepter_id | accept_date |\n+--------------+-------------+-------------+\n| 1            | 2           | 2016/06/03  |\n| 1            | 3           | 2016/06/08  |\n| 2            | 3           | 2016/06/08  |\n| 3            | 4           | 2016/06/09  |\n+--------------+-------------+-------------+\n<strong>Saída:</strong> \n+----+-----+\n| id | num |\n+----+-----+\n| 3  | 3   |\n+----+-----+\n<strong>Explicação:</strong> \nA pessoa com id 3 é amiga das pessoas 1, 2 e 4, então ela tem três amigos no total, o que é a maior quantidade entre todas as outras.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> No mundo real, várias pessoas poderiam ter a mesma maior quantidade de amigos. Você conseguiria encontrar todas essas pessoas neste caso?</p>",
    "hints_pt": [
      "- Dica 1: Ser amigos é bidirecional. Se você aceita a solicitação de amizade de alguém, tanto você quanto a outra pessoa terão um amigo a mais."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "605",
    "paidOnly": false,
    "title": "Can Place Flowers",
    "titleSlug": "can-place-flowers",
    "url": "https://leetcode.com/problems/can-place-flowers",
    "description_url": "https://leetcode.com/problems/can-place-flowers/description/",
    "description": "<p>You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in <strong>adjacent</strong> plots.</p>\n\n<p>Given an integer array <code>flowerbed</code> containing <code>0</code>&#39;s and <code>1</code>&#39;s, where <code>0</code> means empty and <code>1</code> means not empty, and an integer <code>n</code>, return <code>true</code>&nbsp;<em>if</em> <code>n</code> <em>new flowers can be planted in the</em> <code>flowerbed</code> <em>without violating the no-adjacent-flowers rule and</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 1\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> flowerbed = [1,0,0,0,1], n = 2\n<strong>Output:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>flowerbed[i]</code> is <code>0</code> or <code>1</code>.</li>\n\t<li>There are no two adjacent flowers in <code>flowerbed</code>.</li>\n\t<li><code>0 &lt;= n &lt;= flowerbed.length</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/can-place-flowers/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Single Scan [Accepted]\n\nThe solution is very simple. We can find out the extra maximum number of flowers, $$count$$, that can be planted for the given $$flowerbed$$ arrangement. To do so, we can traverse over all the elements of the $$flowerbed$$ and find out those elements which are 0(implying an empty position). For every such element, we check if its both adjacent positions are also empty. If so, we can plant a flower at the current position without violating the no-adjacent-flowers-rule. For the first and last elements, we need not check the previous and the next adjacent positions respectively.\n\nIf the $$count$$ obtained is greater than or equal to $$n$$, the required number of flowers to be planted, we can plant $$n$$ flowers in the empty spaces, otherwise not.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/UncMMEFa/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"UncMMEFa\"></iframe>\n\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n)$$. A single scan of the $$flowerbed$$ array of size $$n$$ is done.\n\n* Space complexity: $$O(1)$$. Constant extra space is used.\n\n---\n### Approach #2 Optimized [Accepted]\n\n**Algorithm**\n\nInstead of finding the maximum value of $$count$$ that can be obtained, as done in the last approach, we can stop the process of checking the positions for planting the flowers as soon as $$count$$ becomes equal to $$n$$. Doing this leads to an optimization of the first approach. If $$count$$ never becomes equal to $$n$$, $$n$$ flowers can't be planted at the empty positions.\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/RSPq2Ur6/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"RSPq2Ur6\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity: $$O(n)$$. A single scan of the $$flowerbed$$ array of size $$n$$ is done.\n\n* Space complexity: $$O(1)$$. Constant extra space is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:\n    for i, flower in enumerate(flowerbed):\n      if flower == 0 and (i == 0 or flowerbed[i - 1] == 0) and (i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):\n        flowerbed[i] = 1\n        n -= 1\n      if n <= 0:\n        return True\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canPlaceFlowers(int[] flowerbed, int n) {\n    if (n == 0)\n      return true;\n\n    for (int i = 0; i < flowerbed.length; ++i)\n      if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) &&\n          (i == flowerbed.length - 1 || flowerbed[i + 1] == 0)) {\n        flowerbed[i] = 1;\n        if (--n == 0)\n          return true;\n      }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canPlaceFlowers(vector<int>& flowerbed, int n) {\n    if (n == 0)\n      return true;\n\n    for (int i = 0; i < flowerbed.size(); ++i)\n      if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) &&\n          (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) {\n        flowerbed[i] = 1;\n        if (--n == 0)\n          return true;\n      }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/605.html",
    "category": "Algorithms",
    "acceptance_rate": 28.871093466097186,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 6996,
    "dislikes": 1270,
    "similar_questions": "[{\"title\": \"Teemo Attacking\", \"titleSlug\": \"teemo-attacking\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Asteroid Collision\", \"titleSlug\": \"asteroid-collision\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 1155965, \"totalSubmissionRaw\": 4003886, \"acRate\": \"28.9%\"}",
    "title_pt": "Pode Plantar Flores",
    "description_pt": "<p>Você tem um canteiro de flores longo no qual alguns dos canteiros estão plantados, e alguns não estão. No entanto, flores não podem ser plantadas em canteiros <strong>adjacentes</strong>.</p>\n\n<p>Dado um array inteiro <code>flowerbed</code> contendo <code>0</code>&#39;s e <code>1</code>&#39;s, onde <code>0</code> significa vazio e <code>1</code> significa não vazio, e um inteiro <code>n</code>, retorne <code>true</code>&nbsp;<em>se</em> <code>n</code> <em>novas flores puderem ser plantadas no</em> <code>flowerbed</code> <em>sem violar a regra de flores não adjacentes e</em> <code>false</code> <em>caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> flowerbed = [1,0,0,0,1], n = 1\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> flowerbed = [1,0,0,0,1], n = 2\n<strong>Saída:</strong> false\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= flowerbed.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>flowerbed[i]</code> é <code>0</code> ou <code>1</code>.</li>\n\t<li>Não há duas flores adjacentes em <code>flowerbed</code>.</li>\n\t<li><code>0 &lt;= n &lt;= flowerbed.length</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "606",
    "paidOnly": false,
    "title": "Construct String from Binary Tree",
    "titleSlug": "construct-string-from-binary-tree",
    "url": "https://leetcode.com/problems/construct-string-from-binary-tree",
    "description_url": "https://leetcode.com/problems/construct-string-from-binary-tree/description/",
    "description": "<p>Given the <code>root</code> node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:</p>\n\n<ul>\n\t<li>\n\t<p><strong>Node Representation</strong>: Each node in the tree should be represented by its integer value.</p>\n\t</li>\n\t<li>\n\t<p><strong>Parentheses for Children</strong>: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:</p>\n\n\t<ul>\n\t\t<li>If a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node&#39;s value.</li>\n\t\t<li>If a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.</li>\n\t</ul>\n\t</li>\n\t<li>\n\t<p><strong>Omitting Empty Parentheses</strong>: Any empty parentheses pairs (i.e., <code>()</code>) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.</p>\n\n\t<p>In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree&#39;s structure accurately.</p>\n\t</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg\" style=\"padding: 10px; background: #fff; border-radius: .5rem;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4]\n<strong>Output:</strong> &quot;1(2(4))(3)&quot;\n<strong>Explanation:</strong> Originally, it needs to be &quot;1(2(4)())(3()())&quot;, but you need to omit all the empty parenthesis pairs. And it will be &quot;1(2(4))(3)&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg\" style=\"padding: 10px; background: #fff; border-radius: .5rem;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,null,4]\n<strong>Output:</strong> &quot;1(2()(4))(3)&quot;\n<strong>Explanation:</strong> Almost the same as the first example, except the <code>()</code> after <code>2</code> is necessary to indicate the absence of a left child for <code>2</code> and the presence of a right child.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/construct-string-from-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def tree2str(self, t: Optional[TreeNode]) -> str:\n    def dfs(root: Optional[TreeNode]) -> str:\n      if not root:\n        return ''\n      if root.right:\n        return str(root.val) + '(' + dfs(root.left) + ')(' + dfs(root.right) + ')'\n      if root.left:\n        return str(root.val) + '(' + dfs(root.left) + ')'\n      return str(root.val)\n    return dfs(t)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String tree2str(TreeNode t) {\n    return dfs(t);\n  }\n\n  private String dfs(TreeNode root) {\n    if (root == null)\n      return \"\";\n    if (root.right != null)\n      return root.val + \"(\" + dfs(root.left) + \")(\" + dfs(root.right) + \")\";\n    if (root.left != null)\n      return root.val + \"(\" + dfs(root.left) + \")\";\n    return root.val + \"\";\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string tree2str(TreeNode* t) {\n    return dfs(t);\n  }\n\n private:\n  string dfs(TreeNode* root) {\n    if (root == nullptr)\n      return \"\";\n\n    const string& rootStr = to_string(root->val);\n    if (root->right)\n      return rootStr + \"(\" + dfs(root->left) + \")(\" + dfs(root->right) + \")\";\n    if (root->left)\n      return rootStr + \"(\" + dfs(root->left) + \")\";\n    return rootStr + \"\";\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/606.html",
    "category": "Algorithms",
    "acceptance_rate": 70.02919529812931,
    "topics": [
      "String",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 128,
    "dislikes": 55,
    "similar_questions": "[{\"title\": \"Construct Binary Tree from String\", \"titleSlug\": \"construct-binary-tree-from-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Duplicate Subtrees\", \"titleSlug\": \"find-duplicate-subtrees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"338.4K\", \"totalSubmission\": \"483.3K\", \"totalAcceptedRaw\": 338449, \"totalSubmissionRaw\": 483297, \"acRate\": \"70.0%\"}",
    "title_pt": "Construir String a partir de uma Árvore Binária",
    "description_pt": "<p>Dado o nó <code>root</code> de uma árvore binária, sua tarefa é criar uma representação em string da árvore seguindo um conjunto específico de regras de formatação. A representação deve ser baseada em uma travessia em preorder da árvore binária e precisa obedecer às seguintes diretrizes:</p>\n\n<ul>\n\t<li>\n\t<p><strong>Representação do Nó</strong>: Cada nó da árvore deve ser representado por seu valor inteiro.</p>\n\t</li>\n\t<li>\n\t<p><strong>Parênteses para os Filhos</strong>: Se um nó tiver pelo menos um filho (à esquerda ou à direita), seus filhos devem ser representados dentro de parênteses. Especificamente:</p>\n\n\t<ul>\n\t\t<li>Se um nó tiver um filho à esquerda, o valor do filho à esquerda deve ser colocado entre parênteses imediatamente após o valor do nó.</li>\n\t\t<li>Se um nó tiver um filho à direita, o valor do filho à direita também deve ser colocado entre parênteses. Os parênteses do filho à direita devem vir depois dos parênteses do filho à esquerda.</li>\n\t</ul>\n\t</li>\n\t<li>\n\t<p><strong>Omissão de Parênteses Vazios</strong>: Quaisquer pares de parênteses vazios (isto é, <code>()</code>) devem ser omitidos da representação final em string da árvore, com uma exceção específica: quando um nó tiver um filho à direita, mas nenhum filho à esquerda. Nesses casos, você deve incluir um par de parênteses vazio para indicar a ausência do filho à esquerda. Isso garante que o mapeamento um-para-um entre a representação em string e a estrutura original da árvore binária seja mantido.</p>\n\n\t<p>Em resumo, pares de parênteses vazios devem ser omitidos quando um nó tiver apenas um filho à esquerda ou nenhum filho. No entanto, quando um nó tiver um filho à direita, mas nenhum filho à esquerda, um par de parênteses vazio deve preceder a representação do filho à direita para refletir com precisão a estrutura da árvore.</p>\n\t</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg\" style=\"padding: 10px; background: #fff; border-radius: .5rem;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4]\n<strong>Saída:</strong> &quot;1(2(4))(3)&quot;\n<strong>Explicação:</strong> Originalmente, precisa ser &quot;1(2(4)())(3()())&quot;, mas você precisa omitir todos os pares de parênteses vazios. E então será &quot;1(2(4))(3)&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg\" style=\"padding: 10px; background: #fff; border-radius: .5rem;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,null,4]\n<strong>Saída:</strong> &quot;1(2()(4))(3)&quot;\n<strong>Explicação:</strong> Quase o mesmo que o primeiro exemplo, exceto que o <code>()</code> após <code>2</code> é necessário para indicar a ausência de um filho à esquerda de <code>2</code> e a presença de um filho à direita.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "607",
    "paidOnly": false,
    "title": "Sales Person",
    "titleSlug": "sales-person",
    "url": "https://leetcode.com/problems/sales-person",
    "description_url": "https://leetcode.com/problems/sales-person/description/",
    "description": "<p>Table: <code>SalesPerson</code></p>\n\n<pre>\n+-----------------+---------+\n| Column Name     | Type    |\n+-----------------+---------+\n| sales_id        | int     |\n| name            | varchar |\n| salary          | int     |\n| commission_rate | int     |\n| hire_date       | date    |\n+-----------------+---------+\nsales_id is the primary key (column with unique values) for this table.\nEach row of this table indicates the name and the ID of a salesperson alongside their salary, commission rate, and hire date.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Company</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| com_id      | int     |\n| name        | varchar |\n| city        | varchar |\n+-------------+---------+\ncom_id is the primary key (column with unique values) for this table.\nEach row of this table indicates the name and the ID of a company and the city in which the company is located.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Table: <code>Orders</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| order_id    | int  |\n| order_date  | date |\n| com_id      | int  |\n| sales_id    | int  |\n| amount      | int  |\n+-------------+------+\norder_id is the primary key (column with unique values) for this table.\ncom_id is a foreign key (reference column) to com_id from the Company table.\nsales_id is a foreign key (reference column) to sales_id from the SalesPerson table.\nEach row of this table contains information about one order. This includes the ID of the company, the ID of the salesperson, the date of the order, and the amount paid.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to find the names of all the salespersons who did not have any orders related to the company with the name <strong>&quot;RED&quot;</strong>.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nSalesPerson table:\n+----------+------+--------+-----------------+------------+\n| sales_id | name | salary | commission_rate | hire_date  |\n+----------+------+--------+-----------------+------------+\n| 1        | John | 100000 | 6               | 4/1/2006   |\n| 2        | Amy  | 12000  | 5               | 5/1/2010   |\n| 3        | Mark | 65000  | 12              | 12/25/2008 |\n| 4        | Pam  | 25000  | 25              | 1/1/2005   |\n| 5        | Alex | 5000   | 10              | 2/3/2007   |\n+----------+------+--------+-----------------+------------+\nCompany table:\n+--------+--------+----------+\n| com_id | name   | city     |\n+--------+--------+----------+\n| 1      | RED    | Boston   |\n| 2      | ORANGE | New York |\n| 3      | YELLOW | Boston   |\n| 4      | GREEN  | Austin   |\n+--------+--------+----------+\nOrders table:\n+----------+------------+--------+----------+--------+\n| order_id | order_date | com_id | sales_id | amount |\n+----------+------------+--------+----------+--------+\n| 1        | 1/1/2014   | 3      | 4        | 10000  |\n| 2        | 2/1/2014   | 4      | 5        | 5000   |\n| 3        | 3/1/2014   | 1      | 1        | 50000  |\n| 4        | 4/1/2014   | 1      | 4        | 25000  |\n+----------+------------+--------+----------+--------+\n<strong>Output:</strong> \n+------+\n| name |\n+------+\n| Amy  |\n| Mark |\n| Alex |\n+------+\n<strong>Explanation:</strong> \nAccording to orders 3 and 4 in the Orders table, it is easy to tell that only salesperson John and Pam have sales to company RED, so we report all the other names in the table salesperson.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/sales-person/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/607.html",
    "category": "Database",
    "acceptance_rate": 65.88428979044237,
    "topics": [
      "Database"
    ],
    "hints": [
      "You need to query who sold to company 'RED' first, then output the sales person who is not in the first query result."
    ],
    "likes": 1271,
    "dislikes": 105,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"278.9K\", \"totalSubmission\": \"423.4K\", \"totalAcceptedRaw\": 278933, \"totalSubmissionRaw\": 423368, \"acRate\": \"65.9%\"}",
    "title_pt": "Pessoa de Vendas",
    "description_pt": "<p>Tabela: <code>SalesPerson</code></p>\n\n<pre>\n+-----------------+---------+\n| Column Name     | Type    |\n+-----------------+---------+\n| sales_id        | int     |\n| name            | varchar |\n| salary          | int     |\n| commission_rate | int     |\n| hire_date       | date    |\n+-----------------+---------+\nsales_id é a chave primária (coluna com valores únicos) para esta tabela.\nCada linha desta tabela indica o nome e o ID de um vendedor, juntamente com seu salário, taxa de comissão e data de contratação.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Company</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| com_id      | int     |\n| name        | varchar |\n| city        | varchar |\n+-------------+---------+\ncom_id é a chave primária (coluna com valores únicos) para esta tabela.\nCada linha desta tabela indica o nome e o ID de uma empresa e a cidade em que a empresa está localizada.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Tabela: <code>Orders</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| order_id    | int  |\n| order_date  | date |\n| com_id      | int  |\n| sales_id    | int  |\n| amount      | int  |\n+-------------+------+\norder_id é a chave primária (coluna com valores únicos) para esta tabela.\ncom_id é uma chave estrangeira (coluna de referência) para com_id da tabela Company.\nsales_id é uma chave estrangeira (coluna de referência) para sales_id da tabela SalesPerson.\nCada linha desta tabela contém informações sobre um pedido. Isso inclui o ID da empresa, o ID do vendedor, a data do pedido e o valor pago.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para encontrar os nomes de todos os vendedores que não tiveram nenhum pedido relacionado à empresa com o nome <strong>&quot;RED&quot;</strong>.</p>\n\n<p>Retorne a tabela de resultados em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado é mostrado no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nSalesPerson table:\n+----------+------+--------+-----------------+------------+\n| sales_id | name | salary | commission_rate | hire_date  |\n+----------+------+--------+-----------------+------------+\n| 1        | John | 100000 | 6               | 4/1/2006   |\n| 2        | Amy  | 12000  | 5               | 5/1/2010   |\n| 3        | Mark | 65000  | 12              | 12/25/2008 |\n| 4        | Pam  | 25000  | 25              | 1/1/2005   |\n| 5        | Alex | 5000   | 10              | 2/3/2007   |\n+----------+------+--------+-----------------+------------+\nCompany table:\n+--------+--------+----------+\n| com_id | name   | city     |\n+--------+--------+----------+\n| 1      | RED    | Boston   |\n| 2      | ORANGE | New York |\n| 3      | YELLOW | Boston   |\n| 4      | GREEN  | Austin   |\n+--------+--------+----------+\nOrders table:\n+----------+------------+--------+----------+--------+\n| order_id | order_date | com_id | sales_id | amount |\n+----------+------------+--------+----------+--------+\n| 1        | 1/1/2014   | 3      | 4        | 10000  |\n| 2        | 2/1/2014   | 4      | 5        | 5000   |\n| 3        | 3/1/2014   | 1      | 1        | 50000  |\n| 4        | 4/1/2014   | 1      | 4        | 25000  |\n+----------+------------+--------+----------+--------+\n<strong>Saída:</strong> \n+------+\n| name |\n+------+\n| Amy  |\n| Mark |\n| Alex |\n+------+\n<strong>Explicação:</strong> \nDe acordo com os pedidos 3 e 4 na tabela Orders, é fácil perceber que apenas o vendedor John e Pam têm vendas para a empresa RED, então reportamos todos os outros nomes na tabela SalesPerson.\n</pre>",
    "hints_pt": [
      "- Dica 1: Você precisa consultar primeiro quem vendeu para a empresa 'RED'; depois, retorne o vendedor que não está no resultado da primeira consulta."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "608",
    "paidOnly": false,
    "title": "Tree Node",
    "titleSlug": "tree-node",
    "url": "https://leetcode.com/problems/tree-node",
    "description_url": "https://leetcode.com/problems/tree-node/description/",
    "description": "<p>Table: <code>Tree</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| p_id        | int  |\n+-------------+------+\nid is the column with unique values for this table.\nEach row of this table contains information about the id of a node and the id of its parent node in a tree.\nThe given structure is always a valid tree.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Each node in the tree can be one of three types:</p>\n\n<ul>\n\t<li><strong>&quot;Leaf&quot;</strong>: if the node is a leaf node.</li>\n\t<li><strong>&quot;Root&quot;</strong>: if the node is the root of the tree.</li>\n\t<li><strong>&quot;Inner&quot;</strong>: If the node is neither a leaf node nor a root node.</li>\n</ul>\n\n<p>Write a solution to report the type of each node in the tree.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/10/22/tree1.jpg\" style=\"width: 304px; height: 224px;\" />\n<pre>\n<strong>Input:</strong> \nTree table:\n+----+------+\n| id | p_id |\n+----+------+\n| 1  | null |\n| 2  | 1    |\n| 3  | 1    |\n| 4  | 2    |\n| 5  | 2    |\n+----+------+\n<strong>Output:</strong> \n+----+-------+\n| id | type  |\n+----+-------+\n| 1  | Root  |\n| 2  | Inner |\n| 3  | Leaf  |\n| 4  | Leaf  |\n| 5  | Leaf  |\n+----+-------+\n<strong>Explanation:</strong> \nNode 1 is the root node because its parent node is null and it has child nodes 2 and 3.\nNode 2 is an inner node because it has parent node 1 and child node 4 and 5.\nNodes 3, 4, and 5 are leaf nodes because they have parent nodes and they do not have child nodes.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/10/22/tree2.jpg\" style=\"width: 64px; height: 65px;\" />\n<pre>\n<strong>Input:</strong> \nTree table:\n+----+------+\n| id | p_id |\n+----+------+\n| 1  | null |\n+----+------+\n<strong>Output:</strong> \n+----+-------+\n| id | type  |\n+----+-------+\n| 1  | Root  |\n+----+-------+\n<strong>Explanation:</strong> If there is only one node on the tree, you only need to output its root attributes.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as <a href=\"https://leetcode.com/problems/binary-tree-nodes/description/\" target=\"_blank\"> 3054: Binary Tree Nodes.</a></p>\n",
    "solution_url": "https://leetcode.com/problems/tree-node/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/608.html",
    "category": "Database",
    "acceptance_rate": 73.74558575157377,
    "topics": [
      "Database"
    ],
    "hints": [
      "You can judge the node type by querying whether the node's id shows up in p_id column and whether the node's p_id is null."
    ],
    "likes": 1293,
    "dislikes": 128,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"192.1K\", \"totalSubmission\": \"260.5K\", \"totalAcceptedRaw\": 192121, \"totalSubmissionRaw\": 260519, \"acRate\": \"73.7%\"}",
    "title_pt": "Nó da Árvore",
    "description_pt": "<p>Tabela: <code>Tree</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id          | int  |\n| p_id        | int  |\n+-------------+------+\nid is the column with unique values for this table.\nEach row of this table contains information about the id of a node and the id of its parent node in a tree.\nThe given structure is always a valid tree.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Cada nó na árvore pode ser um dos três tipos:</p>\n\n<ul>\n\t<li><strong>&quot;Leaf&quot;</strong>: se o nó for um nó folha.</li>\n\t<li><strong>&quot;Root&quot;</strong>: se o nó for a raiz da árvore.</li>\n\t<li><strong>&quot;Inner&quot;</strong>: se o nó não for nem um nó folha nem um nó raiz.</li>\n</ul>\n\n<p>Escreva uma solução para informar o tipo de cada nó na árvore.</p>\n\n<p>Retorne a tabela resultante em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/10/22/tree1.jpg\" style=\"width: 304px; height: 224px;\" />\n<pre>\n<strong>Entrada:</strong> \nTabela Tree:\n+----+------+\n| id | p_id |\n+----+------+\n| 1  | null |\n| 2  | 1    |\n| 3  | 1    |\n| 4  | 2    |\n| 5  | 2    |\n+----+------+\n<strong>Saída:</strong> \n+----+-------+\n| id | type  |\n+----+-------+\n| 1  | Root  |\n| 2  | Inner |\n| 3  | Leaf  |\n| 4  | Leaf  |\n| 5  | Leaf  |\n+----+-------+\n<strong>Explicação:</strong> \nO nó 1 é o nó raiz porque seu nó pai é null e ele tem os nós filhos 2 e 3.\nO nó 2 é um nó interno porque ele tem nó pai 1 e nós filhos 4 e 5.\nOs nós 3, 4 e 5 são nós folha porque eles têm nós pai e não têm nós filhos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/10/22/tree2.jpg\" style=\"width: 64px; height: 65px;\" />\n<pre>\n<strong>Entrada:</strong> \nTabela Tree:\n+----+------+\n| id | p_id |\n+----+------+\n| 1  | null |\n+----+------+\n<strong>Saída:</strong> \n+----+-------+\n| id | type  |\n+----+-------+\n| 1  | Root  |\n+----+-------+\n<strong>Explicação:</strong> Se houver apenas um nó na árvore, você só precisa retornar seus atributos de raiz.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que <a href=\"https://leetcode.com/problems/binary-tree-nodes/description/\" target=\"_blank\"> 3054: Binary Tree Nodes.</a></p>",
    "hints_pt": [
      "- Dica 1: Você pode julgar o tipo do nó consultando se o id do nó aparece na coluna p_id e se o p_id do nó é null."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "609",
    "paidOnly": false,
    "title": "Find Duplicate File in System",
    "titleSlug": "find-duplicate-file-in-system",
    "url": "https://leetcode.com/problems/find-duplicate-file-in-system",
    "description_url": "https://leetcode.com/problems/find-duplicate-file-in-system/description/",
    "description": "<p>Given a list <code>paths</code> of directory info, including the directory path, and all the files with contents in this directory, return <em>all the duplicate files in the file system in terms of their paths</em>. You may return the answer in <strong>any order</strong>.</p>\n\n<p>A group of duplicate files consists of at least two files that have the same content.</p>\n\n<p>A single directory info string in the input list has the following format:</p>\n\n<ul>\n\t<li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li>\n</ul>\n\n<p>It means there are <code>n</code> files <code>(f1.txt, f2.txt ... fn.txt)</code> with content <code>(f1_content, f2_content ... fn_content)</code> respectively in the directory &quot;<code>root/d1/d2/.../dm&quot;</code>. Note that <code>n &gt;= 1</code> and <code>m &gt;= 0</code>. If <code>m = 0</code>, it means the directory is just the root directory.</p>\n\n<p>The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:</p>\n\n<ul>\n\t<li><code>&quot;directory_path/file_name.txt&quot;</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\n<strong>Output:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\n<strong>Output:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= paths[i].length &lt;= 3000</code></li>\n\t<li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>paths[i]</code> consist of English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>\n\t<li>You may assume no files or directories share the same name in the same directory.</li>\n\t<li>You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow up:</strong></p>\n\n<ul>\n\t<li>Imagine you are given a real file system, how will you search files? DFS or BFS?</li>\n\t<li>If the file content is very large (GB level), how will you modify your solution?</li>\n\t<li>If you can only read the file by 1kb each time, how will you modify your solution?</li>\n\t<li>What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?</li>\n\t<li>How to make sure the duplicated files you find are not false positive?</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-duplicate-file-in-system/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Brute Force [Time Limit Exceeded]\n\n**Algorithm**\n\nFor the brute force solution, firstly we obtain the directory paths, the filenames and file contents separately by appropriately splitting the elements of the $$paths$$ list. While doing so, we keep on creating a $$list$$ which contains the full path of every file along with the contents of the file. The $$list$$ contains data in the form $$[ [file_1\\_full\\_path, file_1\\_contents], [file_2\\_full\\_path, file_2\\_contents]..., [file_n\\_full\\_path, file_n\\_contents] ]$$.\n\nOnce this is done, we iterate over this $$list$$. For every element $$i$$ chosen from the list, we iterate over the whole $$list$$ to find another element $$j$$ whose file contents are the same as the $$i^{th}$$ element. For every such element found, we put the $$j^{th}$$ element's file path in a temporary list $$l$$ and we also mark the $$j^{th}$$ element as visited so that this element isn't considered again in the future. Thus, when we reach the end of the array for every $$i^{th}$$ element, we obtain a list of file paths in $$l$$, which have the same contents as the file corresponding to the $$i^{th}$$ element. If this list isn't empty, it indicates that there exists content duplicate to the $$i^{th}$$ element. Thus, we also need to put the $$i^{th}$$ element's file path in the $$l$$. \n\nAt the end of each iteration, we put this list $$l$$ obtained in the resultant list $$res$$ and reset the list $$l$$ for finding the duplicates of the next element.\n\n<iframe src=\"https://leetcode.com/playground/P5yYSqFy/shared\" frameBorder=\"0\" name=\"P5yYSqFy\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n*x + f^2*s)$$. Creation of $$list$$ will take $$O(n*x)$$, where n is the number of directories and x is the average string length. Every file is compared with every other file. Let $$f$$ files are there with average size of $$s$$, then files comparision will take $$O(f^2*s)$$, equals can take $$O(s)$$. Here, Worst case will be when all files are unique.\n\n* Space complexity : $$O(n*x)$$. Size of lists $$res$$ and $$list$$ can grow upto $$n*x$$.\n\n---\n### Approach #2 Using HashMap [Accepted]\n\nIn this approach, firstly we obtain the directory paths, the file names and their contents separately by appropriately splitting each string in the given $$paths$$ list. In order to find the files with duplicate contents, we make use of a HashMap $$map$$, which stores the data in the form $$(contents, list\\_of\\_file\\_paths\\_with\\_this\\_content)$$. Thus, for every file's contents, we check if the same content already exist in the hashmap. If so, we add the current file's path to the list of files corresponding to the current contents. Otherwise, we create a new entry in the $$map$$, with the current contents as the key and the value being a list with only one entry(the current file's path).\n\nAt the end, we find out the contents corresponding to which atleast two file paths exist. We obtain the resultant list $$res$$, which is a list of lists containing these file paths corresponding to the same contents.\n\nThe following animation illustrates the process for a clearer understanding.\n\n!?!../Documents/609_Find_Duplicate.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/9pU24YeR/shared\" frameBorder=\"0\" name=\"9pU24YeR\" width=\"100%\" height=\"428\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n*x)$$. $$n$$ strings of average length $$x$$ is parsed.\n\n* Space complexity : $$O(n*x)$$. $$map$$ and $$res$$ size grows upto $$n*x$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n    contentToPathFiles = defaultdict(list)\n\n    for path in paths:\n      words = path.split(' ')\n      rootPath = words[0]  # \"root/d1/d2/.../dm\"\n      for fileAndContent in words[1:]:  # \"fn.txt(fn_content)\"\n        l = fileAndContent.find('(')\n        r = fileAndContent.find(')')\n        # \"fn.txt\"\n        file = fileAndContent[:l]\n        # \"fn_content\"\n        content = fileAndContent[l + 1:r]\n        # \"root/d1/d2/.../dm/fn.txt\"\n        filePath = rootPath + '/' + file\n        contentToPathFiles[content].append(filePath)\n\n    return [filePath for filePath in contentToPathFiles.values() if len(filePath) > 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> findDuplicate(String[] paths) {\n    List<List<String>> ans = new ArrayList<>();\n    Map<String, List<String>> contentToFilePaths = new HashMap<>();\n\n    for (final String path : paths) {\n      final String[] words = path.split(\" \");\n      final String rootPath = words[0]; // \"root/d1/d2/.../dm\"\n      for (int i = 1; i < words.length; ++i) {\n        final String fileAndContent = words[i]; // \"fn.txt(fn_content)\"\n        final int l = fileAndContent.indexOf('(');\n        final int r = fileAndContent.indexOf(')');\n        // \"fn.txt\"\n        final String file = fileAndContent.substring(0, l);\n        // \"fn_content\"\n        final String content = fileAndContent.substring(l + 1, r);\n        // \"root/d1/d2/.../dm/fn.txt\"\n        final String filePath = rootPath + '/' + file;\n        contentToFilePaths.putIfAbsent(content, new ArrayList<>());\n        contentToFilePaths.get(content).add(filePath);\n      }\n    }\n\n    for (List<String> filePaths : contentToFilePaths.values())\n      if (filePaths.size() > 1)\n        ans.add(filePaths);\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> findDuplicate(vector<string>& paths) {\n    vector<vector<string>> ans;\n    unordered_map<string, vector<string>> contentToFilePaths;\n\n    for (const string& path : paths) {\n      istringstream iss(path);\n      string rootPath;\n      iss >> rootPath;  // \"root/d1/d2/.../dm\"\n\n      string fileAndContent;\n      while (iss >> fileAndContent) {  // \"fn.txt(fn_content)\"\n        const int l = fileAndContent.find('(');\n        const int r = fileAndContent.find(')');\n        // \"fn.txt\"\n        const string file = fileAndContent.substr(0, l);\n        // \"fn_content\"\n        const string content = fileAndContent.substr(l + 1, r - l - 1);\n        // \"root/d1/d2/.../dm/fn.txt\"\n        const string filePath = rootPath + '/' + file;\n        contentToFilePaths[content].push_back(filePath);\n      }\n    }\n\n    for (const auto& [_, filePaths] : contentToFilePaths)\n      if (filePaths.size() > 1)\n        ans.push_back(filePaths);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/609.html",
    "category": "Algorithms",
    "acceptance_rate": 67.57464291231572,
    "topics": [
      "Array",
      "Hash Table",
      "String"
    ],
    "hints": [],
    "likes": 1533,
    "dislikes": 1653,
    "similar_questions": "[{\"title\": \"Delete Duplicate Folders in System\", \"titleSlug\": \"delete-duplicate-folders-in-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"161.8K\", \"totalSubmission\": \"239.5K\", \"totalAcceptedRaw\": 161846, \"totalSubmissionRaw\": 239507, \"acRate\": \"67.6%\"}",
    "title_pt": "Encontrar Arquivos Duplicados no Sistema",
    "description_pt": "<p>Dada uma lista <code>paths</code> de informações de diretório, incluindo o caminho do diretório e todos os arquivos com conteúdo neste diretório, retorne <em>todos os arquivos duplicados no sistema de arquivos em termos de seus caminhos</em>. Você pode retornar a resposta em <strong>qualquer ordem</strong>.</p>\n\n<p>Um grupo de arquivos duplicados consiste de pelo menos dois arquivos que têm o mesmo conteúdo.</p>\n\n<p>Uma única string de informação de diretório na lista de entrada tem o seguinte formato:</p>\n\n<ul>\n\t<li><code>&quot;root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)&quot;</code></li>\n</ul>\n\n<p>Isso significa que há <code>n</code> arquivos <code>(f1.txt, f2.txt ... fn.txt)</code> com conteúdo <code>(f1_content, f2_content ... fn_content)</code> respectivamente no diretório &quot;<code>root/d1/d2/.../dm&quot;</code>. Observe que <code>n &gt;= 1</code> e <code>m &gt;= 0</code>. Se <code>m = 0</code>, isso significa que o diretório é apenas o diretório raiz.</p>\n\n<p>A saída é uma lista de grupos de caminhos de arquivos duplicados. Para cada grupo, ele contém todos os caminhos dos arquivos que têm o mesmo conteúdo. Um caminho de arquivo é uma string que tem o seguinte formato:</p>\n\n<ul>\n\t<li><code>&quot;directory_path/file_name.txt&quot;</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\n<strong>Saída:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\n<strong>Saída:</strong> [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= paths.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= paths[i].length &lt;= 3000</code></li>\n\t<li><code>1 &lt;= sum(paths[i].length) &lt;= 5 * 10<sup>5</sup></code></li>\n\t<li><code>paths[i]</code> consistem de letras ইংl? No. de English letters, digits, <code>&#39;/&#39;</code>, <code>&#39;.&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>\n\t<li>Você pode assumir que nenhum arquivo ou diretório compartilha o mesmo nome no mesmo diretório.</li>\n\t<li>Você pode assumir que cada informação de diretório fornecida representa um diretório único. Um único espaço em branco separa o caminho do diretório e as informações do arquivo.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong></p>\n\n<ul>\n\t<li>Imagine que você recebeu um sistema de arquivos real; como você procuraria arquivos? DFS ou BFS?</li>\n\t<li>Se o conteúdo do arquivo for muito grande (nível de GB), como você modificaria sua solução?</li>\n\t<li>Se você só puder ler o arquivo 1kb por vez, como você modificaria sua solução?</li>\n\t<li>Qual é a complexidade de tempo da sua solução modificada? Qual é a parte que consome mais tempo e a parte que consome mais memória? Como otimizar?</li>\n\t<li>Como garantir que os arquivos duplicados que você encontrar não sejam falso positivo?</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "610",
    "paidOnly": false,
    "title": "Triangle Judgement",
    "titleSlug": "triangle-judgement",
    "url": "https://leetcode.com/problems/triangle-judgement",
    "description_url": "https://leetcode.com/problems/triangle-judgement/description/",
    "description": "<p>Table: <code>Triangle</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| x           | int  |\n| y           | int  |\n| z           | int  |\n+-------------+------+\nIn SQL, (x, y, z) is the primary key column for this table.\nEach row of this table contains the lengths of three line segments.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Report for every three line segments whether they can form a triangle.</p>\n\n<p>Return the result table in <strong>any order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nTriangle table:\n+----+----+----+\n| x  | y  | z  |\n+----+----+----+\n| 13 | 15 | 30 |\n| 10 | 20 | 15 |\n+----+----+----+\n<strong>Output:</strong> \n+----+----+----+----------+\n| x  | y  | z  | triangle |\n+----+----+----+----------+\n| 13 | 15 | 30 | No       |\n| 10 | 20 | 15 | Yes      |\n+----+----+----+----------+\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/triangle-judgement/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/610.html",
    "category": "Database",
    "acceptance_rate": 73.55678651609337,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 707,
    "dislikes": 209,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"326K\", \"totalSubmission\": \"443.2K\", \"totalAcceptedRaw\": 325998, \"totalSubmissionRaw\": 443192, \"acRate\": \"73.6%\"}",
    "title_pt": "Julgamento de Triângulo",
    "description_pt": "<p>Tabela: <code>Triangle</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| x           | int  |\n| y           | int  |\n| z           | int  |\n+-------------+------+\nEm SQL, (x, y, z) é a coluna de chave primária desta tabela.\nCada linha desta tabela contém os comprimentos de três segmentos de reta.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Informe, para cada trio de segmentos de reta, se eles podem formar um triângulo.</p>\n\n<p>Retorne a tabela de resultado em <strong>qualquer ordem</strong>.</p>\n\n<p>O formato do&nbsp;resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTriangle table:\n+----+----+----+\n| x  | y  | z  |\n+----+----+----+\n| 13 | 15 | 30 |\n| 10 | 20 | 15 |\n+----+----+----+\n<strong>Saída:</strong> \n+----+----+----+----------+\n| x  | y  | z  | triangle |\n+----+----+----+----------+\n| 13 | 15 | 30 | No       |\n| 10 | 20 | 15 | Yes      |\n+----+----+----+----------+\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "611",
    "paidOnly": false,
    "title": "Valid Triangle Number",
    "titleSlug": "valid-triangle-number",
    "url": "https://leetcode.com/problems/valid-triangle-number",
    "description_url": "https://leetcode.com/problems/valid-triangle-number/description/",
    "description": "<p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,2,3,4]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,2,3,4]\n<strong>Output:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-triangle-number/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Brute Force\n\nThe condition for the triplets $$(a, b, c)$$ representing the lengths of the sides of a triangle, to form a valid triangle, is that the sum of any two sides should always be greater than the third side alone. i.e. $$a + b > c$$, $$b + c > a$$, $$a + c > b$$. \n\nThe simplest method to check this is to consider every possible triplet in the given $$nums$$ array and checking if the triplet satisfies the three inequalities mentioned above. Thus, we can keep a track of the $$count$$ of the number of triplets satisfying these inequalities. When all the triplets have been considered, the $$count$$ gives the required result.\n\n> **Caution:** The brute force approach is included here because it is an intuitive way to approach this problem. However, when there are $$10^3$$ numbers, the if statement will be checked approximately $$10^9$$ times. Thus, this approach will result in TLE. In the following approaches we will discuss ways to optimize our solution. \n\n<iframe src=\"https://leetcode.com/playground/K5p9fUjs/shared\" frameBorder=\"0\" width=\"100%\" height=\"344\" name=\"K5p9fUjs\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^3)$$. Three nested loops are there to check every triplet.\n\n* Space complexity : $$O(1)$$. Constant space is used.\n<br>\n<br>\n\n---\n### Approach 2: Using Binary Search\n\n**Algorithm**\n\nIf we sort the given $$nums$$ array once, we can solve the given problem in a better way. This is because, if we consider a triplet $$(a, b, c)$$ such that $$a &leq; b &leq; c$$, we need not check all the three inequalities for checking the validity of the triangle formed by them. But, only one condition $$a + b > c$$ would suffice. This happens because $$c &geq; b$$ and $$c &geq; a$$. Thus, adding any number to $$c$$ will always produce a sum which is greater than either $$a$$ or $$b$$ considered alone. Thus, the inequalities $$c + a > b$$ and $$c + b > a$$ are satisfied implicitly by virtue of the  property $$a < b < c$$.\n\nFrom this, we get the idea that we can sort the given $$nums$$ array. Then, for every pair $$(nums[i], nums[j])$$ considered starting from the beginning of the array, such that $$j > i$$(leading to $$nums[j] &geq; nums[i]$$), we can find out the count of elements $$nums[k]$$($$k > j$$), which satisfy the inequality $$nums[k] > nums[i] + nums[j]$$. We can do so for every pair $$(i, j)$$ considered and get the required result.\n\nWe can also observe that, since we've sorted the $$nums$$ array, as we traverse towards the right for choosing the index $$k$$(for number $$nums[k]$$), the value of $$nums[k]$$ could increase or remain the same(doesn't decrease relative to the previous value). Thus, there will exist a right limit on the value of index $$k$$, such that the elements satisfy $$nums[k] > nums[i] + nums[j]$$. Any elements beyond this value of $$k$$ won't satisfy this inequality as well, which is obvious.\n\nThus, if we are able to find this right limit value of $$k$$(indicating the element just greater than $$nums[i] + nums[j]$$), we can conclude that all the elements in $$nums$$ array in the range $$(j+1, k-1)$$(both included) satisfy the required inequality. Thus, the $$count$$ of elements satisfying the inequality will be given by $$(k-1) - (j+1) + 1 = k - j - 1$$.\n\nSince the $$nums$$ array has been sorted now, we can make use of Binary Search to find this right limit of $$k$$. The following animation shows how Binary Search can be used to find the right limit for a simple example.\n\n!?!../Documents/Valid_Triangle_Binary.json:1000,563!?!\n\nAnother point to be observed is that once we find a right limit index $$k_{(i,j)}$$ for a particular pair $$(i, j)$$ chosen, when we choose a higher value of $$j$$ for the same value of $$i$$, we need not start searching for the right limit $$k_{(i,j+1)}$$ from the index $$j+2$$. Instead, we can start off from the index $$k_{(i,j)}$$ directly where we left off for the last $$j$$ chosen. \n\nThis holds correct because when we choose a higher value of $$j$$(higher or equal $$nums[j]$$ than the previous one), all the $$nums[k]$$, such that $$k < k_{(i,j)}$$ will obviously satisfy $$nums[i] + nums[j] > nums[k]$$ for the new value of $$j$$ chosen.\n\nBy taking advantage of this observation, we can limit the range of Binary Search for $$k$$ to shorter values for increasing values of $$j$$ considered while choosing the pairs $$(i, j)$$.\n\n<iframe src=\"https://leetcode.com/playground/jSUCbmrc/shared\" frameBorder=\"0\" width=\"100%\" height=\"463\" name=\"jSUCbmrc\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2 \\log n)$$. In worst case inner loop will take $$n\\log n$$ (binary search applied $$n$$ times).\n\n* Space complexity : $$O(\\log n)$$. Sorting takes $$O(\\log n)$$ space.\n<br>\n<br>\n\n---\n### Approach 3: Linear Scan\n\n**Algorithm**\n\nAs discussed in the last approach, once we sort the given $$nums$$ array, we need to find the right limit of the index $$k$$ for a pair of indices $$(i, j)$$ chosen to find the $$count$$ of elements satisfying $$nums[i] + nums[j] > nums[k]$$ for the triplet $$(nums[i], nums[j], nums[k])$$ to form a valid triangle. \n\nWe can find this right limit by simply traversing the index $$k$$'s values starting from the index $$k=j+1$$ for a pair $$(i, j)$$ chosen and stopping at the first value of $$k$$ not satisfying the above inequality. Again, the $$count$$ of elements $$nums[k]$$ satisfying $$nums[i] + nums[j] > nums[k]$$ for the pair of indices $$(i, j)$$ chosen is given by $$k - j - 1$$ as discussed in the last approach.\n\nFurther, as discussed in the last approach, when we choose a higher value of index $$j$$ for a particular $$i$$ chosen, we need not start from the index $$j + 1$$. Instead, we can start off directly from the value of $$k$$ where we left for the last index $$j$$. This helps to save redundant computations.\n\nThe following animation depicts the process:\n\n!?!../Documents/Valid_Triangle_Linear.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/HT9jpv3e/shared\" frameBorder=\"0\" width=\"100%\" height=\"310\" name=\"HT9jpv3e\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. Loop of $$k$$ and $$j$$ will be executed $$O(n^2)$$ times in total, because, we do not reinitialize the value of $$k$$ for a new value of $$j$$ chosen(for the same $$i$$). Thus the complexity will be $$O(n \\log n + n^2)=O(n^2)$$.\n\n* Space complexity : $$O(\\log n)$$. Sorting takes $$O(\\log n)$$ space.\n<br>\n<br>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def triangleNumber(self, nums: List[int]) -> int:\n    ans = 0\n\n    nums.sort()\n\n    for k in range(len(nums) - 1, 1, -1):\n      i = 0\n      j = k - 1\n      while i < j:\n        if nums[i] + nums[j] > nums[k]:\n          ans += j - i\n          j -= 1\n        else:\n          i += 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int triangleNumber(int[] nums) {\n    if (nums.length < 3)\n      return 0;\n\n    int ans = 0;\n\n    Arrays.sort(nums);\n\n    for (int k = nums.length - 1; k > 1; --k) {\n      int i = 0;\n      int j = k - 1;\n      while (i < j)\n        if (nums[i] + nums[j] > nums[k]) {\n          // (nums[i], nums[j], nums[k])\n          // (nums[i + 1], nums[j], nums[k])\n          // ...\n          // (nums[j - 1], nums[j], nums[k])\n          ans += j - i;\n          --j;\n        } else {\n          ++i;\n        }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int triangleNumber(vector<int>& nums) {\n    if (nums.size() < 3)\n      return 0;\n\n    int ans = 0;\n\n    sort(begin(nums), end(nums));\n\n    for (int k = nums.size() - 1; k > 1; --k) {\n      int i = 0;\n      int j = k - 1;\n      while (i < j)\n        if (nums[i] + nums[j] > nums[k]) {\n          // (nums[i], nums[j], nums[k])\n          // (nums[i + 1], nums[j], nums[k])\n          // ...\n          // (nums[j - 1], nums[j], nums[k])\n          ans += j - i;\n          --j;\n        } else {\n          ++i;\n        }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/611.html",
    "category": "Algorithms",
    "acceptance_rate": 52.20335610686051,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 3917,
    "dislikes": 225,
    "similar_questions": "[{\"title\": \"3Sum Smaller\", \"titleSlug\": \"3sum-smaller\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Polygon With the Largest Perimeter\", \"titleSlug\": \"find-polygon-with-the-largest-perimeter\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"225.6K\", \"totalSubmission\": \"432.2K\", \"totalAcceptedRaw\": 225637, \"totalSubmissionRaw\": 432227, \"acRate\": \"52.2%\"}",
    "title_pt": "Número Válido de Triângulos",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, retorne <em>o número de trincas escolhidas do array que podem formar triângulos se as tomarmos como comprimentos dos lados de um triângulo</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,2,3,4]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> As combinações válidas são: \n2,3,4 (usando o primeiro 2)\n2,3,4 (usando o segundo 2)\n2,2,3\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,2,3,4]\n<strong>Saída:</strong> 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "617",
    "paidOnly": false,
    "title": "Merge Two Binary Trees",
    "titleSlug": "merge-two-binary-trees",
    "url": "https://leetcode.com/problems/merge-two-binary-trees",
    "description_url": "https://leetcode.com/problems/merge-two-binary-trees/description/",
    "description": "<p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p>\n\n<p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p>\n\n<p>Return <em>the merged tree</em>.</p>\n\n<p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/merge.jpg\" style=\"width: 600px; height: 163px;\" />\n<pre>\n<strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\n<strong>Output:</strong> [3,4,5,5,4,null,7]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root1 = [1], root2 = [1,2]\n<strong>Output:</strong> [2,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/merge-two-binary-trees/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Using Recursion [Accepted]\n\nWe can traverse both the given trees in a preorder fashion. At every step, we check if the current node exists(isn't null) for both the trees. If so, we add the values in the current nodes of both the trees and update the value in the current node of the first tree to reflect this sum obtained. At every step, we also call the original function `mergeTrees()` with the left children and then with the right children of the current nodes of the two trees. If at any step, one of these children happens to be null, we return the child of the other tree(representing the corresponding child subtree) to be added as a child subtree to the calling parent node in the first tree. At the end, the first tree will represent the required resultant merged binary tree.\n\nThe following animation illustrates the process.\n\n!?!../Documents/617_Merge_Trees_Recursion.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/d9nZDPEJ/shared\" frameBorder=\"0\" name=\"d9nZDPEJ\" width=\"100%\" height=\"428\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(m)$$. A total of $$m$$ nodes need to be traversed. Here, $$m$$ represents the minimum number of nodes from the two given trees.\n\n* Space complexity : $$O(m)$$. The depth of the recursion tree can go upto $$m$$ in the case of a skewed tree. In average case, depth will be $$O(logm)$$.\n\n---\n### Approach #2 Iterative Method [Accepted]\n\n**Algorithm**\n\nIn the current approach, we again traverse the two trees, but this time we make use of a $$stack$$ to do so instead of making use of recursion. Each entry in the $$stack$$ stores data in the form $$[node_{tree1}, node_{tree2}]$$. Here, $$node_{tree1}$$ and $$node_{tree2}$$ are the nodes of the first tree and the second tree respectively.\n\nWe start off by pushing the root nodes of both the trees onto the $$stack$$. Then, at every step, we remove a node pair from the top of the stack. For every node pair removed, we add the values corresponding to the two nodes and update the value of the corresponding node in the first tree. Then, if the left child of the first tree exists, we push the left child(pair) of both the trees onto the stack. If the left child of the first tree doesn't exist, we append the left child(subtree) of the second tree to the current node of the first tree. We do the same for the right child pair as well. \n\nIf, at any step, both the current nodes are null, we continue with popping the next nodes from the $$stack$$.\n\nThe following animation depicts the process.\n\n!?!../Documents/617_Merge_Trees_Stack.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/v2TK7i2x/shared\" frameBorder=\"0\" name=\"v2TK7i2x\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. We traverse over a total of $$n$$ nodes. Here, $$n$$ refers to the smaller of the number of nodes in the two trees.\n\n* Space complexity : $$O(n)$$. The depth of stack can grow upto $$n$$ in case of a skewed tree.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n    if not root1 and not root2:\n      return None\n    val = (root1.val if root1 else 0) + (root2.val if root2 else 0)\n    root = TreeNode(val)\n    root.left = self.mergeTrees(root1.left if root1 else None,\n                                root2.left if root2 else None)\n    root.right = self.mergeTrees(root1.right if root1 else None,\n                                 root2.right if root2 else None)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {\n    if (root1 == null && root2 == null)\n      return null;\n    final int val = (root1 == null ? 0 : root1.val) + (root2 == null ? 0 : root2.val);\n    TreeNode root = new TreeNode(val);\n    root.left = mergeTrees(root1 == null ? null : root1.left, root2 == null ? null : root2.left);\n    root.right = mergeTrees(root1 == null ? null : root1.right, root2 == null ? null : root2.right);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {\n    if (root1 == nullptr && root2 == nullptr)\n      return nullptr;\n    const int val = (root1 == nullptr ? 0 : root1->val) +\n                    (root2 == nullptr ? 0 : root2->val);\n    TreeNode* root = new TreeNode(val);\n    root->left = mergeTrees(root1 == nullptr ? nullptr : root1->left,\n                            root2 == nullptr ? nullptr : root2->left);\n    root->right = mergeTrees(root1 == nullptr ? nullptr : root1->right,\n                             root2 == nullptr ? nullptr : root2->right);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/617.html",
    "category": "Algorithms",
    "acceptance_rate": 78.6657438822492,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 8928,
    "dislikes": 312,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"837.7K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 837704, \"totalSubmissionRaw\": 1064891, \"acRate\": \"78.7%\"}",
    "title_pt": "Fundir Duas Árvores Binárias",
    "description_pt": "<p>Você recebe duas árvores binárias <code>root1</code> e <code>root2</code>.</p>\n\n<p>Imagine que, quando você coloca uma delas para cobrir a outra, alguns nós das duas árvores ficam sobrepostos enquanto outros não. Você precisa fundir as duas árvores em uma nova árvore binária. A regra de fusão é que, se dois nós se sobrepuserem, então some os valores dos nós para obter o novo valor do nó fundido. Caso contrário, o nó não nulo será usado como o nó da nova árvore.</p>\n\n<p>Retorne <em>a árvore fundida</em>.</p>\n\n<p><strong>Nota:</strong> O processo de fusão deve começar pelas raízes de ambas as árvores.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/02/05/merge.jpg\" style=\"width: 600px; height: 163px;\" />\n<pre>\n<strong>Entrada:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\n<strong>Saída:</strong> [3,4,5,5,4,null,7]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root1 = [1], root2 = [1,2]\n<strong>Saída:</strong> [2,2]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós em ambas as árvores está no intervalo <code>[0, 2000]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "619",
    "paidOnly": false,
    "title": "Biggest Single Number",
    "titleSlug": "biggest-single-number",
    "url": "https://leetcode.com/problems/biggest-single-number",
    "description_url": "https://leetcode.com/problems/biggest-single-number/description/",
    "description": "<p>Table: <code>MyNumbers</code></p>\n\n<pre>\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| num         | int  |\n+-------------+------+\nThis table may contain duplicates (In other words, there is no primary key for this table in SQL).\nEach row of this table contains an integer.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>A <strong>single number</strong> is a number that appeared only once in the <code>MyNumbers</code> table.</p>\n\n<p>Find the largest <strong>single number</strong>. If there is no <strong>single number</strong>, report <code>null</code>.</p>\n\n<p>The result format is in the following example.</p>\n<ptable> </ptable>\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8   |\n| 8   |\n| 3   |\n| 3   |\n| 1   |\n| 4   |\n| 5   |\n| 6   |\n+-----+\n<strong>Output:</strong> \n+-----+\n| num |\n+-----+\n| 6   |\n+-----+\n<strong>Explanation:</strong> The single numbers are 1, 4, 5, and 6.\nSince 6 is the largest single number, we return it.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8   |\n| 8   |\n| 7   |\n| 7   |\n| 3   |\n| 3   |\n| 3   |\n+-----+\n<strong>Output:</strong> \n+------+\n| num  |\n+------+\n| null |\n+------+\n<strong>Explanation:</strong> There are no single numbers in the input table so we return null.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/biggest-single-number/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/619.html",
    "category": "Database",
    "acceptance_rate": 69.33583175652487,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 787,
    "dislikes": 192,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"377.8K\", \"totalSubmission\": \"544.9K\", \"totalAcceptedRaw\": 377791, \"totalSubmissionRaw\": 544871, \"acRate\": \"69.3%\"}",
    "title_pt": "Maior Número Único",
    "description_pt": "<p>Tabela: <code>MyNumbers</code></p>\n\n<pre>\n+-------------+------+\n| Nome da Coluna | Tipo |\n+-------------+------+\n| num         | int  |\n+-------------+------+\nEsta tabela pode conter duplicatas (Em outras palavras, não há chave primária para esta tabela em SQL).\nCada linha desta tabela contém um inteiro.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Um <strong>número único</strong> é um número que apareceu apenas uma vez na tabela <code>MyNumbers</code>.</p>\n\n<p>Encontre o maior <strong>número único</strong>. Se não houver <strong>número único</strong>, informe <code>null</code>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n<ptable> </ptable>\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8   |\n| 8   |\n| 3   |\n| 3   |\n| 1   |\n| 4   |\n| 5   |\n| 6   |\n+-----+\n<strong>Saída:</strong> \n+-----+\n| num |\n+-----+\n| 6   |\n+-----+\n<strong>Explicação:</strong> Os números únicos são 1, 4, 5 e 6.\nComo 6 é o maior número único, nós o retornamos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8   |\n| 8   |\n| 7   |\n| 7   |\n| 3   |\n| 3   |\n| 3   |\n+-----+\n<strong>Saída:</strong> \n+------+\n| num  |\n+------+\n| null |\n+------+\n<strong>Explicação:</strong> Não há números únicos na tabela de entrada, então retornamos null.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "620",
    "paidOnly": false,
    "title": "Not Boring Movies",
    "titleSlug": "not-boring-movies",
    "url": "https://leetcode.com/problems/not-boring-movies",
    "description_url": "https://leetcode.com/problems/not-boring-movies/description/",
    "description": "<p>Table: <code>Cinema</code></p>\n\n<pre>\n+----------------+----------+\n| Column Name    | Type     |\n+----------------+----------+\n| id             | int      |\n| movie          | varchar  |\n| description    | varchar  |\n| rating         | float    |\n+----------------+----------+\nid is the primary key (column with unique values) for this table.\nEach row contains information about the name of a movie, its genre, and its rating.\nrating is a 2 decimal places float in the range [0, 10]\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to report the movies with an odd-numbered ID and a description that is not <code>&quot;boring&quot;</code>.</p>\n\n<p>Return the result table ordered by <code>rating</code> <strong>in descending order</strong>.</p>\n\n<p>The&nbsp;result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nCinema table:\n+----+------------+-------------+--------+\n| id | movie      | description | rating |\n+----+------------+-------------+--------+\n| 1  | War        | great 3D    | 8.9    |\n| 2  | Science    | fiction     | 8.5    |\n| 3  | irish      | boring      | 6.2    |\n| 4  | Ice song   | Fantacy     | 8.6    |\n| 5  | House card | Interesting | 9.1    |\n+----+------------+-------------+--------+\n<strong>Output:</strong> \n+----+------------+-------------+--------+\n| id | movie      | description | rating |\n+----+------------+-------------+--------+\n| 5  | House card | Interesting | 9.1    |\n| 1  | War        | great 3D    | 8.9    |\n+----+------------+-------------+--------+\n<strong>Explanation:</strong> \nWe have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/not-boring-movies/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/620.html",
    "category": "Database",
    "acceptance_rate": 74.89661524551124,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1298,
    "dislikes": 549,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"798.5K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 798514, \"totalSubmissionRaw\": 1066152, \"acRate\": \"74.9%\"}",
    "title_pt": "Filmes Não Entediantes",
    "description_pt": "<p>Tabela: <code>Cinema</code></p>\n\n<pre>\n+----------------+----------+\n| Nome da Coluna | Tipo     |\n+----------------+----------+\n| id             | int      |\n| movie          | varchar  |\n| description    | varchar  |\n| rating         | float    |\n+----------------+----------+\nid é a chave primária (column with unique values) para esta tabela.\nCada linha contém informações sobre o nome de um filme, seu gênero e sua avaliação.\nrating é um float com 2 casas decimais no intervalo [0, 10]\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para reportar os filmes com um ID ímpar e uma descrição que não seja <code>&quot;boring&quot;</code>.</p>\n\n<p>Retorne a tabela resultado ordenada por <code>rating</code> <strong>em ordem decrescente</strong>.</p>\n\n<p>O formato do resultado está no seguinte exemplo.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nCinema table:\n+----+------------+-------------+--------+\n| id | movie      | description | rating |\n+----+------------+-------------+--------+\n| 1  | War        | great 3D    | 8.9    |\n| 2  | Science    | fiction     | 8.5    |\n| 3  | irish      | boring      | 6.2    |\n| 4  | Ice song   | Fantacy     | 8.6    |\n| 5  | House card | Interesting | 9.1    |\n+----+------------+-------------+--------+\n<strong>Saída:</strong> \n+----+------------+-------------+--------+\n| id | movie      | description | rating |\n+----+------------+-------------+--------+\n| 5  | House card | Interesting | 9.1    |\n| 1  | War        | great 3D    | 8.9    |\n+----+------------+-------------+--------+\n<strong>Explicação:</strong> \nTemos três filmes com IDs ímpares: 1, 3 e 5. O filme com ID = 3 é entediante, então não o incluímos na resposta.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "621",
    "paidOnly": false,
    "title": "Task Scheduler",
    "titleSlug": "task-scheduler",
    "url": "https://leetcode.com/problems/task-scheduler",
    "description_url": "https://leetcode.com/problems/task-scheduler/description/",
    "description": "<p>You are given an array of CPU <code>tasks</code>, each labeled with a letter from A to Z, and a number <code>n</code>. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there&#39;s a constraint: there has to be a gap of <strong>at least</strong> <code>n</code> intervals between two tasks with the same label.</p>\n\n<p>Return the <strong>minimum</strong> number of CPU intervals required to complete all tasks.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Input:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\" style=\"\nfont-family: Menlo,sans-serif;\nfont-size: 0.85rem;\n\">8</span></p>\n\n<p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p>\n\n<p>After completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3<sup>rd</sup> interval, neither A nor B can be done, so you idle. By the 4<sup>th</sup> interval, you can do A again as 2 intervals have passed.</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Input:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">6</span></p>\n\n<p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p>\n\n<p>With a cooling interval of 1, you can repeat a task after just one other task.</p>\n</div>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Input:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">10</span></p>\n\n<p><strong>Explanation:</strong> A possible sequence is: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p>\n\n<p>There are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>tasks[i]</code> is an uppercase English letter.</li>\n\t<li><code>0 &lt;= n &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/task-scheduler/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given characters, which are tasks to be scheduled in the CPU. The objective is to find the minimum time required to complete all tasks while including a cooldown period between two identical tasks. The cooldown period is represented by a non-negative integer `n`. During each unit of time, the CPU can either complete a task or stay idle. The goal is to optimize the schedule to minimize the total time required to process all the tasks.\n\n**Key Observations:**\n1. Tasks represented by the same character are considered identical.\n2. Repeated tasks should be at least `n` intervals apart from each other because of the cooling time.\n3. You can put the idle time effectively in between two repetative tasks to schedule them.\n\nCheckout the below visual of example 1 from the problem description:\n\n![overview](../Figures/621_fix/overiew.png)\n\nThe result is 8 intervals, which is calculated by tasks + idle time (6 + 2). The problem involves finding how much idle time is required to complete the tasks.\n\n\nAll approaches use a greedy strategy, meaning decisions are made step by step, focusing on what seems best in the moment to reach the overall best solution. To show that this type of approach works well, let's use some illustrations. We can prove its effectiveness by showing what happens if we assume the opposite and reach a contradiction. \n\nUsing proof by contradiction, we can demonstrate that selecting the task with the lowest frequency increases idle time for the scheduler, thereby failing to maximize efficiency. Conversely, choosing tasks with higher frequencies maximizes efficiency.\n\n![contradiction](../Figures/621_fix/contradiction.png)\n\nThe Greedy approach optimizes efficiency by prioritizing tasks based on their frequency, thereby reducing intervals and minimizing idle time for the scheduler. This strategy ultimately leads to the maximization of overall efficiency. \n\n![greedy_works](../Figures/621_fix/greedy_works.png)\n\n> After finishing this problem, take a shot at [Task Scheduler II](https://leetcode.com/problems/task-scheduler-ii/) for a deeper understanding of recognizing patterns.\n\n---\n\n### Approach 1: Using Priority Queue / Max Heap\n\n#### Intuition\n\nTo count the occurrences of each task while prioritizing those with the highest frequency, we use a frequency map and a max heap (priority queue).\n\nIn each iteration, a cycle of length `n + 1` is considered, signifying the time needed to execute tasks without violating the cooling period constraint. For instance, if there are 2 tasks (`A`) and `n = 2`, the iterations required would be `A-Idle-Idle-A` (`n + 1` iterations before picking a new task `A`).\n\nDuring each iteration:\n- Tasks with the highest frequency are popped from the max heap. In the case of frequency ties, any tied task can be chosen.\n- The chosen task's frequency is reduced by 1. If remaining occurrences exist, they are added to a temporary array.\n- This process continues until the cycle is completed.\n\nAfter completing the cycle:\n- The temporary array is used to rebuild the heap with updated frequencies of tasks encountered during the cycle. This ensures that updated frequencies are preserved when tasks are popped from the heap.\n\nPost-cycle processing:\n- A counter (`time`) is incremented by the actual number of tasks processed in the current cycle (`taskCount`).\n- If the heap is not empty, extra idle `time` (`n + 1`) is added to account for the cooling period (n cycles + 1 extra idle time).\n- If the heap is empty, only the remaining tasks in the cycle need consideration (`taskCount`).\n\nThis process is repeated until the heap is empty. The `time` variable is incremented by the actual number of tasks processed in each cycle, with adjustments for idle time when required.\n\n##### For a better understanding of the intuition let us view an example:\n\nGiven a task list (e.g., `['A', 'A', 'A', 'B', 'B', 'B']`) and a cooldown period `n` (e.g., 2), we aim to minimize the idle time during task execution.\n\n1. Create a frequency map (`freq`) to track task occurrences: `{'A': 3, 'B': 3}`.\n2. Initialize a max heap (`pq`) with frequencies: `[3, 3]`.\n3. Define the cycle length as `n + 1` (e.g., `2 + 1 = 3`) to avoid violating the cooldown idle period.\n\n##### Cycle Repetition:\n\nRepeat cycles until the heap is empty:\n\n- In the first cycle, choose 'A' and 'B', resulting in `[2, 2]`.\n- Rebuild heap: `[2, 2]`, and increment time: 2 tasks processed + cooldown idle.\n- In the second cycle, choose 'A' and 'B' again, resulting in `[1, 1]`.\n- Rebuild heap: `[1, 1]`, and increment time: 2 tasks processed + cooldown idle.\n- Continue cycles until the heap is empty.\n\nThe accumulated time spent on tasks and idle periods gives the final result: `3 + 3 + 2 = 8` (A-B-IDLE-A-B-IDLE-A-B).\n\n\nThe following is an illustration demonstrating the above max heap example:\n\n![maxheap](../Figures/621_fix/maxheap.png)\n\n\n#### Algorithm\n\n- Initialize an array `freq` of size 26 to store the frequency of each task.\n- Iterate through the `tasks` array and update the frequency of each task in the `freq` array.\n- Create a priority queue `pq` and insert the frequencies of the tasks into the queue.\n- Initialize a variable `time` to keep track of the total time taken.\n- While the priority queue is not empty, repeat the following steps:\n  - Initialize a variable `cycle` to `n + 1`, which represents the cooling interval plus one (for the current task).\n  - Initialize an empty array `store` to store frequencies of tasks that still need to be processed.\n  - Initialize a variable `taskCount` to keep track of the number of tasks processed in the current cycle.\n  - While `cycle` is greater than 0 and the priority queue is not empty, repeat the following steps:\n    - Decrement `cycle`.\n    - Pop the top element (`task` frequency) from the priority queue.\n    - If the popped frequency is greater than 1, decrement it by 1 and store it in the `store` array.\n    - Increment `taskCount` as it keeps track of the number of tasks processed in the current cycle.\n  - After processing tasks in the cycle, restore the updated frequencies (stored in the `store` array) back to the priority queue.\n  - Update the `time` by adding either `taskCount` (if the priority queue is empty) or `n + 1` (cooling interval) to the total time.\n- Finally, return the total `time`.\n\n#### Implementation\n\n> Note: In Python 3, frequencies are stored as negative values to simulate a max-heap behavior.\n\n<iframe src=\"https://leetcode.com/playground/oKCEwjEZ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"oKCEwjEZ\"></iframe>\n\n#### Complexity Analysis\n\nLet the number of tasks be $N$. Let $k$ be the size of the priority queue. $k$ can, at maximum, be 26 because the priority queue stores the frequency of each distinct task, which is represented by the letters A to Z. \n\n* Time complexity: $O(N)$\n\n    In the worst case, all tasks must be processed, and each task might be inserted and extracted from the priority queue. The priority queue operations (insertion and extraction) have a time complexity of $O(\\log k)$ each. Therefore, the overall time complexity is $O(N \\cdot \\log k)$. Since $k$ is at maximum 26, $\\log k$ is a constant term. We can simplify the time complexity to $O(N)$. This is a linear time complexity with a high constant factor.\n\n* Space complexity: $O(26)$ = $O(1)$\n\n    The space complexity is mainly determined by the frequency array and the priority queue. The frequency array has a constant size of 26, and the priority queue can have a maximum size of 26 when all distinct tasks are present. Therefore, the overall space complexity is $O(1)$ or $O(26)$, which is considered constant.\n\n\n---\n\n### Approach 2: Filling the Slots and Sorting\n\n#### Intuition\n\nWe need to find the minimum time required to complete all tasks given the constraint that at least `n` units of time must elapse between two identical tasks. To minimize the time, we should first consider scheduling the most frequent tasks so that they are separated by `n` units of time. Then, we can fill the idle slots with the remaining tasks.\n\n##### Example:\n\nConsider the task list `['A', 'A', 'A', 'B', 'B', 'B']` with `n = 2`.\n\n1. Calculate the frequency array: `[3, 3, 0, ..., 0]`, as 'A' appears 3 times and 'B' appears 3 times.\n2. Sort the frequency array in ascending order: `[0, 0, ..., 3, 3]`.\n3. Calculate `maxFreq` as `freq[25] - 1`. In this case, `maxFreq = 3 - 1 = 2`.\n4. Calculate the number of idle slots: `idleSlots = maxFreq * n = 2 * 2 = 4`.\n5. The loop starts from the second highest frequency (index 24 in the sorted array) and goes down to the lowest frequency. This ensures that the highest frequency task's idle slots are considered only once, as it was accounted for when calculating `maxFreq` in the earlier step.\n6. In each iteration, subtract the minimum of `maxFreq` and the current frequency from `idleSlots`. For the first iteration, subtract `min(2, 2) = 2` from `idleSlots`, resulting in `idleSlots = 4 - 2 = 2`.\n7. If `idleSlots > 0`, add the remaining idle slots to the total number of tasks. In this example, there are 2 idle slots, so the final result is obtained by adding these idle slots (2) to the total number of tasks (6).\n8. Thus, the minimum time required to complete all tasks, considering the cooldown period, is `8`.\n\n#### Algorithm\n\n- Create a `freq` array of size 26 to keep track of the count of each task.\n- Iterate through the `tasks` array and update the frequency array with the frequency of each task.\n- Sort the frequency array in non-decreasing order (ascending order = smallest to largest). This is done to process tasks with higher frequencies first.\n- Calculate the maximum frequency of the most frequent task. Subtract 1 because we want to find the number of intervals, not the number of occurrences.\n- Calculate the number of `idleSlots` that will be required by multiplying the maximum frequency by the cooldown period.\n- Iterate over the frequency array from the second highest frequency to the lowest frequency.\n    - Subtract the minimum of the maximum frequency and the current frequency from the `idleSlots`.\n- If there are any `idleSlots` left, add them to the total number of tasks and return this as the answer. Otherwise, return the total number of tasks.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/efNxdsdC/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"efNxdsdC\"></iframe>\n\n#### Complexity Analysis\n\nLet the number of tasks be $N$. There are up to 26 distinct tasks because the tasks are represented by the letters A to Z.\n\n* Time complexity: $O(N)$\n\n    The time complexity of the algorithm is $O(26 \\log 26 + N)$, where $26 \\log 26$ is the time complexity of sorting the frequency array, and $N$ is the length of the input task list, which is the dominating term. \n\n* Space complexity: $O(26) = O(1)$\n\n    The frequency array has a size of $26$.\n    \n    Note that some extra space is used when we sort arrays in place. The space complexity of the sorting algorithm depends on the programming language.\n    - In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has $O(N)$ additional space.\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log N )$ for sorting array.\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worse-case space complexity of $O( \\log N )$.\n    \n    We sort the frequency array, which has a size of $26$. The space used for sorting takes $O(26)$ or $O(\\log 26)$, which is constant, so the space complexity of the algorithm is $O(26)$, which is constant, i.e. $O(1)$.\n\n---\n\n\n### Approach 3: Greedy Approach\n\n#### Intuition\n\nThe key is to determine the required number of idle intervals. Let's start by exploring how to arrange tasks. It is apparent that a \"greedy arrangement\" works well: always arrange tasks with the highest frequency first. The goal is to arrange tasks with the highest frequency first, ensuring that they are separated by at least `n` units of time.\n\n##### Step 1: Task Arrangement\n\nFor instance, if tasks are `[\"A\",\"A\",\"A\",\"B\",\"B\",\"C\"]` with `n = 2`, the initial arrangement would be:\n\nA _ _ A _ _ A      (\"_\" denotes empty slots)\n\nThe same approach can be applied to arrange B. The final schedule would look like this:\n\nA B _ A B _ A\n\nAfter arranging B tasks, we have 2 empty slots, but only one task remains. We can place task C and IDLE time in those slots. \n\nA B C A B _ A\n\nThe final schedule could be:\n\nA B C A B IDLE A\n\n##### Step 2: Calculate Idle Intervals\n\nNow that we have a method for arranging tasks, the next step is to calculate the total number of idle intervals required. The solution to the problem is the sum of idle intervals and the number of tasks.\n\nConsider the same example of tasks: `[\"A\",\"A\",\"A\",\"B\",\"B\",\"C\"]` with `n = 2`. After arranging A, we get:\nA _ _ A _ _ A\n\nObserve that A separates the empty slots into `(count(A) - 1)` = 2 parts, each with a length of `n`. A has the highest frequency, so it requires more idle intervals than any other task.\n\nTo calculate parts, empty slots, and available tasks:\n1. Find the number of parts separated by A: `partCount = count(A) - 1`.\n2. Determine the number of empty slots: `emptySlots = partCount * n`.\n3. Identify the number of tasks to be placed into those slots: `availableTasks = tasks.length - count(A)`.\n\nIf `emptySlots > availableTasks`, indicating insufficient tasks to fill all empty slots, the remaining slots are filled with idle intervals: `idles = max(0, emptySlots - availableTasks)`.\n\n\n##### Special Case:\n\nA special case arises when there is more than one task with the highest frequency. For instance, with `[\"A\",\"A\",\"A\",\"B\",\"B\",\"B\",\"C\",\"C\",\"D\"]` and `n = 3`, arranging A results in:\nA _ _ _ A _ _ _ A \n\nWhen arranging B, it becomes evident that each B must follow each A. Considering \"A B\" as a special task \"X,\" the arrangement becomes:\nX _ _ X _ _ X\n\nIn this case, the calculations for parts, empty slots, and available tasks are adjusted:\n- `partCount = count(A) - 1`\n- `emptySlots = partCount * (n - (count of tasks with the highest frequency - 1))`\n- `availableTasks = tasks.length - count(A) * count of tasks with the highest frequency`\n\nIf `emptySlots` is negative, it means there are already enough tasks to make the \"distance\" between the same tasks longer than `n`, and no idle intervals are needed. In this case, `idles = max(0, emptySlots - availableTasks)` provides the time it takes to complete the tasks.\n\nThe final result is then calculated as `result = tasks.length + idles`.\n\n\nThe visuals below provide an illustration of a general case where all tasks have different frequencies.\n\n![greedy_ex1](../Figures/621_fix/greedy_ex1.png)\n\n\nThe visuals below illustrate a special case where more than one task occurs with the highest frequency.\n\n![greedy_ex2](../Figures/621_fix/greedy_ex2.png)\n\n#### Algorithm\n\n- Initialize a `counter` array of size 26 to store the frequency of each task and variables `maximum` and `maxCount` to track the maximum frequency and the number of tasks with that frequency.\n- Traverse through the `tasks` and update the `counter` array. If the frequency of a task is equal to the current maximum frequency, increment `maxCount`. If the frequency is greater than the current maximum frequency, update `maximum` and set `maxCount` to 1.\n- Calculate the number of `emptySlots` by multiplying `partCount` `(maximum - 1)` and `partLength` `(n - (maxCount - 1))`.\n- Calculate the number of `availableTasks` by subtracting the product of `maximum` and `maxCount` from the total number of tasks.\n- Calculate the number of `idles` periods needed by taking the maximum of 0 and the difference between the number of `emptySlots` and the number of `availableTasks`.\n- Return the total time required by adding the number of tasks to the number of `idles` periods.\n\n#### Implementation\n\n> **Note:** A more concise way of calculating the return value is `max(tasks.length, (n + 1) * (max-1) + maxCount)`. We have used the below method instead for the sake of readability.\n\n<iframe src=\"https://leetcode.com/playground/mzF9Fek8/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"mzF9Fek8\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of tasks.\n\n* Time complexity: $O(N)$\n\n    To obtain count(A) and the count of tasks with the highest frequency, we iterate through the inputs, calculating counts for each distinct character. This process has a time complexity of $O(N)$. All other operations have a time complexity of $O(1)$, resulting in an overall time complexity of $O(N)$\n\n* Space complexity: $O(26)$ = $O(1)$\n\n    The array `count` is size $26$ because the tasks are represented by the letters A to Z. No data structures that vary with input size are used, resulting in an overall space complexity of $O(1)$.\n\n---\n\n### Approach 4: Using Math Formula\n\n#### Intuition\n\nEach occurrence of task X takes one CPU cycle. There are `(maxCountX - 1)` scheduled occurrences, and between each two consecutive occurrences, there are at least `N` CPU cycles.\n\nTherefore, the total CPU cycles can be calculated as follows:\n\n$Total CPU cycles = (maxCountX - 1) \\cdot (N + 1)$ \n\n**Where:**\n- `(maxCountX - 1)` represents the number of occurrences of X scheduled, excluding the last one. We exclude the last occurrence of the repeated task in this term because it doesn't need additional cycles between it and the next task; it's the last task from all the repeated tasks of the same character.\n- `(N + 1)` represents the CPU cycles required for each occurrence of `maxCountX`. The element `maxCountX` itself takes one CPU cycle, and there are at least `N` additional cycles between each two consecutive occurrences.\n\nFor example, given tasks `[\"A\",\"A\",\"A\",\"B\",\"B\", \"B\", \"C\"]` and `n = 3`:\n- `countA = 3`, `countB = 3`, `countC = 1`.\n- `maxCount = max(countA, countB, countC) = 3`.\n- Scheduling `maxCount-1` occurrences: `Total CPU cycles = (maxCount - 1) * (n + 1) = 8`.\n- Scheduling the final round: `Ans = Total CPU cycles + 1`, as the last task from all the repeated tasks of the same character is left out, and that task doesn't need `N + 1` cycles to get completed.\n\nIf there are multiple elements with a frequency equal to `maxCount`, add 1 cycle each: `Ans += numberOfMaxFrequencyElements = 8 + 2 = 10`.\n\nThe following illustration provides a clearer insight into the underlying approach:\n\n![math_approach](../Figures/621_fix/math_approach.png)\n\n#### Algorithm\n\n- Initialize a frequency array `freq` with all elements set to 0 and a variable `maxCount` to 0.\n- Iterate through the `tasks` array and update the frequency of each task in the `freq` array. Update `maxCount` with the maximum frequency encountered.\n- Calculate the total time needed for execution by multiplying `(maxCount - 1)` with `(n + 1)`.\n- Iterate through the `freq` array, and if the frequency of a task is equal to `maxCount`, increment the total time by 1.\n- Return the maximum of the total time needed and the length of the tasks array.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/o7LsmR8n/shared\" frameBorder=\"0\" width=\"100%\" height=\"480\" name=\"o7LsmR8n\"></iframe>\n\n#### Complexity Analysis\n\nLet $N$ be the number of tasks.\n\n* Time complexity: $O(N)$\n\n    The loop iterating over the tasks array has a time complexity of $O(N)$. The loop iterating over the `freq` array has a time complexity proportional to the number of unique tasks, which is at most $26$ because the tasks are represented by the letters A to Z. Therefore, the overall time complexity is $O(N + 26)$, which simplifies to $O(N)$.\n\n* Space complexity: $O(26)$ = $O(1)$\n\n    The `freq` array can store at most $26$ unique tasks, resulting in $O(26)$ space complexity. Other variables used in the algorithm have constant space requirements. Therefore, the overall space complexity is $O(1)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def leastInterval(self, tasks: List[str], n: int) -> int:\n    count = Counter(tasks)\n    maxFreq = max(count.values())\n    # Put the most frequent task in the slot first\n    maxFreqTaskOccupy = (maxFreq - 1) * (n + 1)\n    # Get # Of tasks with same frequency as maxFreq,\n    # we'll append them after maxFreqTaskOccupy\n    nMaxFreq = sum(value == maxFreq for value in count.values())\n    # Max(\n    #   the most frequent task is frequent enough to force some idle slots,\n    #   the most frequent task is not frequent enough to force idle slots\n    # )\n    return max(maxFreqTaskOccupy + nMaxFreq, len(tasks))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int leastInterval(char[] tasks, int n) {\n    int[] count = new int[26];\n\n    for (final char task : tasks)\n      ++count[task - 'A'];\n\n    final int maxFreq = Arrays.stream(count).max().getAsInt();\n    // Put the most frequent task in the slot first\n    final int maxFreqTaskOccupy = (maxFreq - 1) * (n + 1);\n    // Get # of tasks with same frequency as maxFreq,\n    // we'll append them after maxFreqTaskOccupy\n    final int nMaxFreq = (int) Arrays.stream(count).filter(c -> c == maxFreq).count();\n    // Max(\n    //   the most frequent task is frequent enough to force some idle slots,\n    //   the most frequent task is not frequent enough to force idle slots\n    // )\n    return Math.max(maxFreqTaskOccupy + nMaxFreq, tasks.length);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int leastInterval(vector<char>& tasks, int n) {\n    if (n == 0)\n      return tasks.size();\n\n    vector<int> count(26);\n\n    for (const char task : tasks)\n      ++count[task - 'A'];\n\n    const int maxFreq = *max_element(begin(count), end(count));\n    // Put the most frequent task in the slot first\n    const int maxFreqTaskOccupy = (maxFreq - 1) * (n + 1);\n    // Get # of tasks with same frequency as maxFreq,\n    // we'll append them after maxFreqTaskOccupy\n    const int nMaxFreq = std::count(begin(count), end(count), maxFreq);\n    // Max(\n    //   the most frequent task is frequent enough to force some idle slots,\n    //   the most frequent task is not frequent enough to force idle slots\n    // )\n    return max(maxFreqTaskOccupy + nMaxFreq, static_cast<int>(tasks.size()));\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/621.html",
    "category": "Algorithms",
    "acceptance_rate": 61.354410055244756,
    "topics": [
      "Array",
      "Hash Table",
      "Greedy",
      "Sorting",
      "Heap (Priority Queue)",
      "Counting"
    ],
    "hints": [
      "There are many different solutions for this problem, including a greedy algorithm.",
      "For every cycle, find the most frequent letter that can be placed in this cycle. After placing, decrease the frequency of that letter by one.",
      "Use Priority Queue."
    ],
    "likes": 11072,
    "dislikes": 2143,
    "similar_questions": "[{\"title\": \"Rearrange String k Distance Apart\", \"titleSlug\": \"rearrange-string-k-distance-apart\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Reorganize String\", \"titleSlug\": \"reorganize-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Weeks for Which You Can Work\", \"titleSlug\": \"maximum-number-of-weeks-for-which-you-can-work\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum Time to Finish All Jobs II\", \"titleSlug\": \"find-minimum-time-to-finish-all-jobs-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Task Scheduler II\", \"titleSlug\": \"task-scheduler-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"789.1K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 789074, \"totalSubmissionRaw\": 1286093, \"acRate\": \"61.4%\"}",
    "title_pt": "Escalonador de Tarefas",
    "description_pt": "<p>Você recebe um array de tarefas da CPU <code>tasks</code>, cada uma rotulada com uma letra de A a Z, e um número <code>n</code>. Cada intervalo da CPU pode ficar ocioso ou permitir a conclusão de uma tarefa. As tarefas podem ser concluídas em qualquer ordem, mas há uma restrição: deve haver um intervalo de <strong>pelo menos</strong> <code>n</code> entre duas tarefas com o mesmo rótulo.</p>\n\n<p>Retorne o número <strong>mínimo</strong> de intervalos da CPU necessários para concluir todas as tarefas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Entrada:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;,&quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 2</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\" style=\"\nfont-family: Menlo,sans-serif;\nfont-size: 0.85rem;\n\">8</span></p>\n\n<p><strong>Explicação:</strong> Uma sequência possível é: A -&gt; B -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; A -&gt; B.</p>\n\n<p>Depois de concluir a tarefa A, você deve esperar dois intervalos antes de fazer A novamente. O mesmo se aplica à tarefa B. No 3<sup>º</sup> intervalo, nem A nem B podem ser executadas, então você fica ocioso. No 4<sup>º</sup> intervalo, você pode fazer A novamente, pois 2 intervalos já se passaram.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Entrada:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;C&quot;,&quot;A&quot;,&quot;B&quot;,&quot;D&quot;,&quot;B&quot;], n = 1</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">6</span></p>\n\n<p><strong>Explicação:</strong> Uma sequência possível é: A -&gt; B -&gt; C -&gt; D -&gt; A -&gt; B.</p>\n\n<p>Com um intervalo de resfriamento de 1, você pode repetir uma tarefa após apenas outra tarefa.</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<div class=\"example-block\" style=\"\n    border-color: var(--border-tertiary);\n    border-left-width: 2px;\n    color: var(--text-secondary);\n    font-size: .875rem;\n    margin-bottom: 1rem;\n    margin-top: 1rem;\n    overflow: visible;\n    padding-left: 1rem;\n\">\n<p><strong>Entrada:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">tasks = [&quot;A&quot;,&quot;A&quot;,&quot;A&quot;, &quot;B&quot;,&quot;B&quot;,&quot;B&quot;], n = 3</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\" style=\"\n    font-family: Menlo,sans-serif;\n    font-size: 0.85rem;\n\">10</span></p>\n\n<p><strong>Explicação:</strong> Uma sequência possível é: A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B -&gt; idle -&gt; idle -&gt; A -&gt; B.</p>\n\n<p>Há apenas dois tipos de tarefas, A e B, que precisam ser separadas por 3 intervalos. Isso leva à ociosidade duas vezes entre as repetições dessas tarefas.</p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= tasks.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>tasks[i]</code> é uma letra maiúscula do alfabeto inglês.</li>\n\t<li><code>0 &lt;= n &lt;= 100</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Existem muitas soluções diferentes para este problema, incluindo um algoritmo ganancioso.",
      "- Dica 2: Para cada ciclo, encontre a letra mais frequente que pode ser colocada neste ciclo. Após colocá-la, diminua a frequência dessa letra em um.",
      "- Dica 3: Use uma Priority Queue."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "622",
    "paidOnly": false,
    "title": "Design Circular Queue",
    "titleSlug": "design-circular-queue",
    "url": "https://leetcode.com/problems/design-circular-queue",
    "description_url": "https://leetcode.com/problems/design-circular-queue/description/",
    "description": "<p>Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called &quot;Ring Buffer&quot;.</p>\n\n<p>One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.</p>\n\n<p>Implement the <code>MyCircularQueue</code> class:</p>\n\n<ul>\n\t<li><code>MyCircularQueue(k)</code> Initializes the object with the size of the queue to be <code>k</code>.</li>\n\t<li><code>int Front()</code> Gets the front item from the queue. If the queue is empty, return <code>-1</code>.</li>\n\t<li><code>int Rear()</code> Gets the last item from the queue. If the queue is empty, return <code>-1</code>.</li>\n\t<li><code>boolean enQueue(int value)</code> Inserts an element into the circular queue. Return <code>true</code> if the operation is successful.</li>\n\t<li><code>boolean deQueue()</code> Deletes an element from the circular queue. Return <code>true</code> if the operation is successful.</li>\n\t<li><code>boolean isEmpty()</code> Checks whether the circular queue is empty or not.</li>\n\t<li><code>boolean isFull()</code> Checks whether the circular queue is full or not.</li>\n</ul>\n\n<p>You must solve the problem without using the built-in queue data structure in your programming language.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\n<strong>Output</strong>\n[null, true, true, true, false, 3, true, true, true, 4]\n\n<strong>Explanation</strong>\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear();     // return 3\nmyCircularQueue.isFull();   // return True\nmyCircularQueue.deQueue();  // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear();     // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 1000</code></li>\n\t<li><code>0 &lt;= value &lt;= 1000</code></li>\n\t<li>At most <code>3000</code> calls will be made to&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>,&nbsp;<code>isEmpty</code>, and&nbsp;<code>isFull</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-circular-queue/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass MyCircularQueue {\n  /** Initialize your data structure here. Set the size of the queue to be k. */\n  public MyCircularQueue(int k) {\n    this.k = k;\n    this.q = new int[k];\n    this.rear = k - 1;\n  }\n\n  /** Insert an element into the circular queue. Return true if the operation is successful. */\n  public boolean enQueue(int value) {\n    if (isFull())\n      return false;\n\n    rear = ++rear % k;\n    q[rear] = value;\n    ++size;\n    return true;\n  }\n\n  /** Delete an element from the circular queue. Return true if the operation is successful. */\n  public boolean deQueue() {\n    if (isEmpty())\n      return false;\n\n    front = ++front % k;\n    --size;\n    return true;\n  }\n\n  /** Get the front item from the queue. */\n  public int Front() {\n    return isEmpty() ? -1 : q[front];\n  }\n\n  /** Get the last item from the queue. */\n  public int Rear() {\n    return isEmpty() ? -1 : q[rear];\n  }\n\n  /** Checks whether the circular queue is empty or not. */\n  public boolean isEmpty() {\n    return size == 0;\n  }\n\n  /** Checks whether the circular queue is full or not. */\n  public boolean isFull() {\n    return size == k;\n  }\n\n  private final int k;\n  private int[] q;\n  private int size = 0;\n  private int front = 0;\n  private int rear;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyCircularQueue {\n public:\n  /** Initialize your data structure here. Set the size of the queue to be k. */\n  MyCircularQueue(int k) : k(k), q(k), rear(k - 1) {}\n\n  /** Insert an element into the circular queue. Return true if the operation is\n   * successful. */\n  bool enQueue(int value) {\n    if (isFull())\n      return false;\n\n    rear = ++rear % k;\n    q[rear] = value;\n    ++size;\n    return true;\n  }\n\n  /** Delete an element from the circular queue. Return true if the operation is\n   * successful. */\n  bool deQueue() {\n    if (isEmpty())\n      return false;\n\n    front = ++front % k;\n    --size;\n    return true;\n  }\n\n  /** Get the front item from the queue. */\n  int Front() {\n    return isEmpty() ? -1 : q[front];\n  }\n\n  /** Get the last item from the queue. */\n  int Rear() {\n    return isEmpty() ? -1 : q[rear];\n  }\n\n  /** Checks whether the circular queue is empty or not. */\n  bool isEmpty() {\n    return size == 0;\n  }\n\n  /** Checks whether the circular queue is full or not. */\n  bool isFull() {\n    return size == k;\n  }\n\n private:\n  const int k;\n  vector<int> q;\n  int size = 0;\n  int front = 0;\n  int rear;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/622.html",
    "category": "Algorithms",
    "acceptance_rate": 52.49536294004017,
    "topics": [
      "Array",
      "Linked List",
      "Design",
      "Queue"
    ],
    "hints": [],
    "likes": 3674,
    "dislikes": 319,
    "similar_questions": "[{\"title\": \"Design Circular Deque\", \"titleSlug\": \"design-circular-deque\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design Front Middle Back Queue\", \"titleSlug\": \"design-front-middle-back-queue\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"382.4K\", \"totalSubmission\": \"728.4K\", \"totalAcceptedRaw\": 382356, \"totalSubmissionRaw\": 728365, \"acRate\": \"52.5%\"}",
    "title_pt": "Projetar Fila Circular",
    "description_pt": "<p>Projete sua implementação da fila circular. A fila circular é uma estrutura de dados linear na qual as operações são realizadas com base no princípio FIFO (First In First Out), e a última posição é conectada de volta à primeira posição para formar um círculo. Ela também é chamada de &quot;Ring Buffer&quot;.</p>\n\n<p>Um dos benefícios da fila circular é que podemos fazer uso dos espaços na frente da fila. Em uma fila normal, quando a fila fica cheia, não podemos inserir o próximo elemento mesmo que haja um espaço na frente da fila. Mas usando a fila circular, podemos usar esse espaço para armazenar novos valores.</p>\n\n<p>Implemente a classe <code>MyCircularQueue</code>:</p>\n\n<ul>\n\t<li><code>MyCircularQueue(k)</code> Inicializa o objeto com o tamanho da fila igual a <code>k</code>.</li>\n\t<li><code>int Front()</code> Obtém o item da frente da fila. Se a fila estiver vazia, retorne <code>-1</code>.</li>\n\t<li><code>int Rear()</code> Obtém o último item da fila. Se a fila estiver vazia, retorne <code>-1</code>.</li>\n\t<li><code>boolean enQueue(int value)</code> Insere um elemento na fila circular. Retorne <code>true</code> se a operação for bem-sucedida.</li>\n\t<li><code>boolean deQueue()</code> Exclui um elemento da fila circular. Retorne <code>true</code> se a operação for bem-sucedida.</li>\n\t<li><code>boolean isEmpty()</code> Verifica se a fila circular está vazia ou não.</li>\n\t<li><code>boolean isFull()</code> Verifica se a fila circular está cheia ou não.</li>\n</ul>\n\n<p>Você deve resolver o problema sem usar a estrutura de dados de fila embutida na sua linguagem de programação.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyCircularQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;, &quot;isFull&quot;, &quot;deQueue&quot;, &quot;enQueue&quot;, &quot;Rear&quot;]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\n<strong>Saída</strong>\n[null, true, true, true, false, 3, true, true, true, 4]\n\n<strong>Explicação</strong>\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear();     // return 3\nmyCircularQueue.isFull();   // return True\nmyCircularQueue.deQueue();  // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear();     // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 1000</code></li>\n\t<li><code>0 &lt;= value &lt;= 1000</code></li>\n\t<li>No máximo <code>3000</code> chamadas serão feitas para&nbsp;<code>enQueue</code>, <code>deQueue</code>,&nbsp;<code>Front</code>,&nbsp;<code>Rear</code>, <code>isEmpty</code> e&nbsp;<code>isFull</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "623",
    "paidOnly": false,
    "title": "Add One Row to Tree",
    "titleSlug": "add-one-row-to-tree",
    "url": "https://leetcode.com/problems/add-one-row-to-tree",
    "description_url": "https://leetcode.com/problems/add-one-row-to-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p>\n\n<p>Note that the <code>root</code> node is at depth <code>1</code>.</p>\n\n<p>The adding rule is:</p>\n\n<ul>\n\t<li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>&#39;s left subtree root and right subtree root.</li>\n\t<li><code>cur</code>&#39;s original left subtree should be the left subtree of the new left subtree root.</li>\n\t<li><code>cur</code>&#39;s original right subtree should be the right subtree of the new right subtree root.</li>\n\t<li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root&#39;s left subtree.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg\" style=\"width: 500px; height: 231px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2\n<strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg\" style=\"width: 500px; height: 277px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3\n<strong>Output:</strong> [4,2,null,1,1,3,null,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= depth &lt;= the depth of tree + 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/add-one-row-to-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode addOneRow(TreeNode root, int v, int d) {\n    if (d == 1) {\n      TreeNode newRoot = new TreeNode(v);\n      newRoot.left = root;\n      return newRoot;\n    }\n\n    int depth = 0;\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      ++depth;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode node = q.poll();\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n        if (depth == d - 1) {\n          TreeNode cachedLeft = node.left;\n          TreeNode cachedRight = node.right;\n          node.left = new TreeNode(v);\n          node.right = new TreeNode(v);\n          node.left.left = cachedLeft;\n          node.right.right = cachedRight;\n        }\n      }\n      if (depth == d - 1)\n        break;\n    }\n\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* addOneRow(TreeNode* root, int v, int d) {\n    if (d == 1) {\n      TreeNode* newRoot = new TreeNode(v);\n      newRoot->left = root;\n      return newRoot;\n    }\n\n    int depth = 0;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      ++depth;\n      for (int sz = q.size(); sz > 0; --sz) {\n        TreeNode* node = q.front();\n        q.pop();\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n        if (depth == d - 1) {\n          TreeNode* cachedLeft = node->left;\n          TreeNode* cachedRight = node->right;\n          node->left = new TreeNode(v);\n          node->right = new TreeNode(v);\n          node->left->left = cachedLeft;\n          node->right->right = cachedRight;\n        }\n      }\n      if (depth == d - 1)\n        break;\n    }\n\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/623.html",
    "category": "Algorithms",
    "acceptance_rate": 64.04450058728365,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 3608,
    "dislikes": 270,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"289K\", \"totalSubmission\": \"451.2K\", \"totalAcceptedRaw\": 288988, \"totalSubmissionRaw\": 451230, \"acRate\": \"64.0%\"}",
    "title_pt": "Adicionar uma Linha à Árvore",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária e dois inteiros <code>val</code> e <code>depth</code>, adicione uma linha de nós com valor <code>val</code> na profundidade dada <code>depth</code>.</p>\n\n<p>Observe que o nó <code>root</code> está na profundidade <code>1</code>.</p>\n\n<p>A regra de adição é:</p>\n\n<ul>\n\t<li>Dado o inteiro <code>depth</code>, para cada nó da árvore não nulo <code>cur</code> na profundidade <code>depth - 1</code>, crie dois nós da árvore com valor <code>val</code> como a raiz da subárvore esquerda de <code>cur</code> e a raiz da subárvore direita de <code>cur</code>.</li>\n\t<li>A subárvore esquerda original de <code>cur</code> deve ser a subárvore esquerda da nova raiz da subárvore esquerda.</li>\n\t<li>A subárvore direita original de <code>cur</code> deve ser a subárvore direita da nova raiz da subárvore direita.</li>\n\t<li>Se <code>depth == 1</code>, isso significa que não existe nenhuma profundidade <code>depth - 1</code> de fato; então, crie um nó da árvore com valor <code>val</code> como a nova raiz de toda a árvore original, e a árvore original será a subárvore esquerda da nova raiz.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg\" style=\"width: 500px; height: 231px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2\n<strong>Saída:</strong> [4,1,1,2,null,null,6,3,1,5]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg\" style=\"width: 500px; height: 277px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,null,3,1], val = 1, depth = 3\n<strong>Saída:</strong> [4,2,null,1,1,3,null,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li>A profundidade da árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= depth &lt;= the depth of tree + 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "624",
    "paidOnly": false,
    "title": "Maximum Distance in Arrays",
    "titleSlug": "maximum-distance-in-arrays",
    "url": "https://leetcode.com/problems/maximum-distance-in-arrays",
    "description_url": "https://leetcode.com/problems/maximum-distance-in-arrays/description/",
    "description": "<p>You are given <code>m</code> <code>arrays</code>, where each array is sorted in <strong>ascending order</strong>.</p>\n\n<p>You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers <code>a</code> and <code>b</code> to be their absolute difference <code>|a - b|</code>.</p>\n\n<p>Return <em>the maximum distance</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> arrays = [[1,2,3],[4,5],[1,2,3]]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> arrays = [[1],[1]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == arrays.length</code></li>\n\t<li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= arrays[i].length &lt;= 500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>arrays[i]</code> is sorted in <strong>ascending order</strong>.</li>\n\t<li>There will be at most <code>10<sup>5</sup></code> integers in all the arrays.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-distance-in-arrays/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxDistance(self, arrays: List[List[int]]) -> int:\n    ans = 0\n    mini = 10000\n    maxi = -10000\n\n    for A in arrays:\n      ans = max(ans, A[-1] - mini, maxi - A[0])\n      mini = min(mini, A[0])\n      maxi = max(maxi, A[-1])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxDistance(List<List<Integer>> arrays) {\n    int ans = 0;\n    int min = 10000;\n    int max = -10000;\n\n    for (List<Integer> A : arrays) {\n      ans = Math.max(ans, Math.max(A.get(A.size() - 1) - min, max - A.get(0)));\n      min = Math.min(min, A.get(0));\n      max = Math.max(max, A.get(A.size() - 1));\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxDistance(vector<vector<int>>& arrays) {\n    int ans = 0;\n    int min = 10000;\n    int max = -10000;\n\n    for (const vector<int>& A : arrays) {\n      ans = std::max({ans, A.back() - min, max - A.front()});\n      min = std::min(min, A.front());\n      max = std::max(max, A.back());\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/624.html",
    "category": "Algorithms",
    "acceptance_rate": 45.60506264345484,
    "topics": [
      "Array",
      "Greedy"
    ],
    "hints": [],
    "likes": 1457,
    "dislikes": 117,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"189K\", \"totalSubmission\": \"414.3K\", \"totalAcceptedRaw\": 188955, \"totalSubmissionRaw\": 414329, \"acRate\": \"45.6%\"}",
    "title_pt": "Maior Distância em Arrays",
    "description_pt": "<p>Você recebe <code>m</code> <code>arrays</code>, em que cada array está ordenado em <strong>ordem crescente</strong>.</p>\n\n<p>Você pode escolher dois inteiros de dois arrays diferentes (cada array escolhe um) e calcular a distância. Definimos a distância entre dois inteiros <code>a</code> e <code>b</code> como sua diferença absoluta <code>|a - b|</code>.</p>\n\n<p>Retorne a <em>máxima distância</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> arrays = [[1,2,3],[4,5],[1,2,3]]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Uma maneira de atingir a distância máxima 4 é escolher 1 no primeiro ou terceiro array e escolher 5 no segundo array.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> arrays = [[1],[1]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == arrays.length</code></li>\n\t<li><code>2 &lt;= m &lt;= 10<sup>5</sup></code></li>\n\t<li><code>1 &lt;= arrays[i].length &lt;= 500</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= arrays[i][j] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>arrays[i]</code> está ordenado em <strong>ordem crescente</strong>.</li>\n\t<li>Haverá no máximo <code>10<sup>5</sup></code> inteiros em todos os arrays.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "626",
    "paidOnly": false,
    "title": "Exchange Seats",
    "titleSlug": "exchange-seats",
    "url": "https://leetcode.com/problems/exchange-seats",
    "description_url": "https://leetcode.com/problems/exchange-seats/description/",
    "description": "<p>Table: <code>Seat</code></p>\n\n<pre>\n+-------------+---------+\n| Column Name | Type    |\n+-------------+---------+\n| id          | int     |\n| student     | varchar |\n+-------------+---------+\nid is the primary key (unique value) column for this table.\nEach row of this table indicates the name and the ID of a student.\nThe ID sequence always starts from 1 and increments continuously.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.</p>\n\n<p>Return the result table ordered by <code>id</code> <strong>in ascending order</strong>.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nSeat table:\n+----+---------+\n| id | student |\n+----+---------+\n| 1  | Abbot   |\n| 2  | Doris   |\n| 3  | Emerson |\n| 4  | Green   |\n| 5  | Jeames  |\n+----+---------+\n<strong>Output:</strong> \n+----+---------+\n| id | student |\n+----+---------+\n| 1  | Doris   |\n| 2  | Abbot   |\n| 3  | Green   |\n| 4  | Emerson |\n| 5  | Jeames  |\n+----+---------+\n<strong>Explanation:</strong> \nNote that if the number of students is odd, there is no need to change the last one&#39;s seat.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/exchange-seats/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/626.html",
    "category": "Database",
    "acceptance_rate": 72.51224836492094,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1658,
    "dislikes": 605,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"338.5K\", \"totalSubmission\": \"466.8K\", \"totalAcceptedRaw\": 338480, \"totalSubmissionRaw\": 466792, \"acRate\": \"72.5%\"}",
    "title_pt": "Trocar Assentos",
    "description_pt": "<p>Tabela: <code>Seat</code></p>\n\n<pre>\n+-------------+---------+\n| Nome da Coluna | Tipo    |\n+-------------+---------+\n| id          | int     |\n| student     | varchar |\n+-------------+---------+\nid is the primary key (unique value) column for this table.\nEach row of this table indicates the name and the ID of a student.\nThe ID sequence always starts from 1 and increments continuously.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para trocar o seat id de cada dois estudantes consecutivos. Se o número de estudantes for ímpar, o id do último estudante não é trocado.</p>\n\n<p>Retorne a tabela resultante ordenada por <code>id</code> <strong>em ordem crescente</strong>.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Seat:\n+----+---------+\n| id | student |\n+----+---------+\n| 1  | Abbot   |\n| 2  | Doris   |\n| 3  | Emerson |\n| 4  | Green   |\n| 5  | Jeames  |\n+----+---------+\n<strong>Saída:</strong> \n+----+---------+\n| id | student |\n+----+---------+\n| 1  | Doris   |\n| 2  | Abbot   |\n| 3  | Green   |\n| 4  | Emerson |\n| 5  | Jeames  |\n+----+---------+\n<strong>Explicação:</strong> \nObserve que, se o número de estudantes for ímpar, não há necessidade de alterar o assento do último.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "627",
    "paidOnly": false,
    "title": "Swap Salary",
    "titleSlug": "swap-salary",
    "url": "https://leetcode.com/problems/swap-salary",
    "description_url": "https://leetcode.com/problems/swap-salary/description/",
    "description": "<p>Table: <code>Salary</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| id          | int      |\n| name        | varchar  |\n| sex         | ENUM     |\n| salary      | int      |\n+-------------+----------+\nid is the primary key (column with unique values) for this table.\nThe sex column is ENUM (category) value of type (&#39;m&#39;, &#39;f&#39;).\nThe table contains information about an employee.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Write a solution to swap all <code>&#39;f&#39;</code> and <code>&#39;m&#39;</code> values (i.e., change all <code>&#39;f&#39;</code> values to <code>&#39;m&#39;</code> and vice versa) with a <strong>single update statement</strong> and no intermediate temporary tables.</p>\n\n<p>Note that you must write a single update statement, <strong>do not</strong> write any select statement for this problem.</p>\n\n<p>The result format is in the following example.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> \nSalary table:\n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1  | A    | m   | 2500   |\n| 2  | B    | f   | 1500   |\n| 3  | C    | m   | 5500   |\n| 4  | D    | f   | 500    |\n+----+------+-----+--------+\n<strong>Output:</strong> \n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1  | A    | f   | 2500   |\n| 2  | B    | m   | 1500   |\n| 3  | C    | f   | 5500   |\n| 4  | D    | m   | 500    |\n+----+------+-----+--------+\n<strong>Explanation:</strong> \n(1, A) and (3, C) were changed from &#39;m&#39; to &#39;f&#39;.\n(2, B) and (4, D) were changed from &#39;f&#39; to &#39;m&#39;.\n</pre>\n",
    "solution_url": "https://leetcode.com/problems/swap-salary/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/627.html",
    "category": "Database",
    "acceptance_rate": 83.9642582801591,
    "topics": [
      "Database"
    ],
    "hints": [],
    "likes": 1791,
    "dislikes": 567,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"466.7K\", \"totalSubmission\": \"555.9K\", \"totalAcceptedRaw\": 466737, \"totalSubmissionRaw\": 555876, \"acRate\": \"84.0%\"}",
    "title_pt": "Trocar Salário",
    "description_pt": "<p>Tabela: <code>Salary</code></p>\n\n<pre>\n+-------------+----------+\n| Column Name | Type     |\n+-------------+----------+\n| id          | int      |\n| name        | varchar  |\n| sex         | ENUM     |\n| salary      | int      |\n+-------------+----------+\nid é a chave primária (coluna com valores únicos) desta tabela.\nA coluna sex é um valor ENUM (categoria) do tipo (&#39;m&#39;, &#39;f&#39;).\nA tabela contém informações sobre um funcionário.\n</pre>\n\n<p>&nbsp;</p>\n\n<p>Escreva uma solução para trocar todos os valores <code>&#39;f&#39;</code> e <code>&#39;m&#39;</code> (isto é, alterar todos os valores <code>&#39;f&#39;</code> para <code>&#39;m&#39;</code> e vice-versa) com uma <strong>única instrução update</strong> e sem tabelas temporárias intermediárias.</p>\n\n<p>Observe que você deve escrever uma única instrução update; <strong>não</strong> escreva nenhuma instrução select para este problema.</p>\n\n<p>O formato do resultado está no exemplo a seguir.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> \nTabela Salary:\n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1  | A    | m   | 2500   |\n| 2  | B    | f   | 1500   |\n| 3  | C    | m   | 5500   |\n| 4  | D    | f   | 500    |\n+----+------+-----+--------+\n<strong>Saída:</strong> \n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1  | A    | f   | 2500   |\n| 2  | B    | m   | 1500   |\n| 3  | C    | f   | 5500   |\n| 4  | D    | m   | 500    |\n+----+------+-----+--------+\n<strong>Explicação:</strong> \n(1, A) e (3, C) foram alterados de &#39;m&#39; para &#39;f&#39;.\n(2, B) e (4, D) foram alterados de &#39;f&#39; para &#39;m&#39;.\n</pre>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "628",
    "paidOnly": false,
    "title": "Maximum Product of Three Numbers",
    "titleSlug": "maximum-product-of-three-numbers",
    "url": "https://leetcode.com/problems/maximum-product-of-three-numbers",
    "description_url": "https://leetcode.com/problems/maximum-product-of-three-numbers/description/",
    "description": "<p>Given an integer array <code>nums</code>, <em>find three numbers whose product is maximum and return the maximum product</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> 6\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,3,4]\n<strong>Output:</strong> 24\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> nums = [-1,-2,-3]\n<strong>Output:</strong> -6\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-product-of-three-numbers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maximumProduct(self, nums: List[int]) -> int:\n    nums.sort()\n    return max(nums[-1] * nums[0] * nums[1],\n               nums[-1] * nums[-2] * nums[-3])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maximumProduct(int[] nums) {\n    final int n = nums.length;\n    Arrays.sort(nums);\n    return Math.max(nums[n - 1] * nums[0] * nums[1], nums[n - 1] * nums[n - 2] * nums[n - 3]);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maximumProduct(vector<int>& nums) {\n    const int n = nums.size();\n    sort(begin(nums), end(nums));\n    return max(nums[n - 1] * nums[0] * nums[1],\n               nums[n - 1] * nums[n - 2] * nums[n - 3]);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/628.html",
    "category": "Algorithms",
    "acceptance_rate": 45.267785976911014,
    "topics": [
      "Array",
      "Math",
      "Sorting"
    ],
    "hints": [],
    "likes": 4374,
    "dislikes": 700,
    "similar_questions": "[{\"title\": \"Maximum Product Subarray\", \"titleSlug\": \"maximum-product-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"404.9K\", \"totalSubmission\": \"894.5K\", \"totalAcceptedRaw\": 404938, \"totalSubmissionRaw\": 894539, \"acRate\": \"45.3%\"}",
    "title_pt": "Produto Máximo de Três Números",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, <em>encontre três números cujo produto seja máximo e retorne o produto máximo</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> 6\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,3,4]\n<strong>Saída:</strong> 24\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> nums = [-1,-2,-3]\n<strong>Saída:</strong> -6\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= nums.length &lt;=&nbsp;10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "629",
    "paidOnly": false,
    "title": "K Inverse Pairs Array",
    "titleSlug": "k-inverse-pairs-array",
    "url": "https://leetcode.com/problems/k-inverse-pairs-array",
    "description_url": "https://leetcode.com/problems/k-inverse-pairs-array/description/",
    "description": "<p>For an integer array <code>nums</code>, an <strong>inverse pair</strong> is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p>\n\n<p>Given two integers n and k, return the number of different arrays consisting of numbers from <code>1</code> to <code>n</code> such that there are exactly <code>k</code> <strong>inverse pairs</strong>. Since the answer can be huge, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, k = 0\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, k = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/k-inverse-pairs-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def kInversePairs(self, n: int, k: int) -> int:\n    kMod = 1_000_000_007\n    # dp[i][j] := # Of permutations of numbers 1..i with j inverse pairs\n    dp = [[0] * (k + 1) for _ in range(n + 1)]\n\n    # If there's no inverse pair, the permutation is unique '123..i'\n    for i in range(n + 1):\n      dp[i][0] = 1\n\n    for i in range(1, n + 1):\n      for j in range(1, k + 1):\n        dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod\n        if j - i >= 0:\n          dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod\n\n    return dp[n][k]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int kInversePairs(int n, int k) {\n    final int kMod = 1_000_000_007;\n    // dp[i][j] := # of permutations of numbers 1..i with j inverse pairs\n    int[][] dp = new int[n + 1][k + 1];\n\n    // If there's no inverse pair, the permutation is unique \"123..i\"\n    for (int i = 0; i <= n; ++i)\n      dp[i][0] = 1;\n\n    for (int i = 1; i <= n; ++i)\n      for (int j = 1; j <= k; ++j) {\n        dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod;\n        if (j - i >= 0)\n          dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod;\n      }\n\n    return dp[n][k];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int kInversePairs(int n, int k) {\n    constexpr int kMod = 1'000'000'007;\n    // dp[i][j] := # of permutations of numbers 1..i with j inverse pairs\n    vector<vector<int>> dp(n + 1, vector<int>(k + 1));\n\n    // If there's no inverse pair, the permutation is unique \"123..i\"\n    for (int i = 0; i <= n; ++i)\n      dp[i][0] = 1;\n\n    for (int i = 1; i <= n; ++i)\n      for (int j = 1; j <= k; ++j) {\n        dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % kMod;\n        if (j - i >= 0)\n          dp[i][j] = (dp[i][j] - dp[i - 1][j - i] + kMod) % kMod;\n      }\n\n    return dp[n][k];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/629.html",
    "category": "Algorithms",
    "acceptance_rate": 49.08992447536181,
    "topics": [
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 2723,
    "dislikes": 329,
    "similar_questions": "[{\"title\": \"Count the Number of Inversions\", \"titleSlug\": \"count-the-number-of-inversions\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"135.1K\", \"totalSubmission\": \"275.1K\", \"totalAcceptedRaw\": 135067, \"totalSubmissionRaw\": 275140, \"acRate\": \"49.1%\"}",
    "title_pt": "Array de K Pares Inversos",
    "description_pt": "<p>Para um array de inteiros <code>nums</code>, um <strong>par inverso</strong> é um par de inteiros <code>[i, j]</code> em que <code>0 &lt;= i &lt; j &lt; nums.length</code> e <code>nums[i] &gt; nums[j]</code>.</p>\n\n<p>Dados dois inteiros n e k, retorne o número de arrays diferentes consistindo de números de <code>1</code> a <code>n</code> tal que existam exatamente <code>k</code> <strong>pares inversos</strong>. Como a resposta pode ser enorme, retorne-a <strong>módulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, k = 0\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> Apenas o array [1,2,3], que consiste em números de 1 a 3, tem exatamente 0 pares inversos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, k = 1\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> O array [1,3,2] e [2,1,3] têm exatamente 1 par inverso.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "630",
    "paidOnly": false,
    "title": "Course Schedule III",
    "titleSlug": "course-schedule-iii",
    "url": "https://leetcode.com/problems/course-schedule-iii",
    "description_url": "https://leetcode.com/problems/course-schedule-iii/description/",
    "description": "<p>There are <code>n</code> different online courses numbered from <code>1</code> to <code>n</code>. You are given an array <code>courses</code> where <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indicate that the <code>i<sup>th</sup></code> course should be taken <b>continuously</b> for <code>duration<sub>i</sub></code> days and must be finished before or on <code>lastDay<sub>i</sub></code>.</p>\n\n<p>You will start on the <code>1<sup>st</sup></code> day and you cannot take two or more courses simultaneously.</p>\n\n<p>Return <em>the maximum number of courses that you can take</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\n<strong>Output:</strong> 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1<sup>st</sup> course, it costs 100 days so you will finish it on the 100<sup>th</sup> day, and ready to take the next course on the 101<sup>st</sup> day.\nSecond, take the 3<sup>rd</sup> course, it costs 1000 days so you will finish it on the 1100<sup>th</sup> day, and ready to take the next course on the 1101<sup>st</sup> day. \nThird, take the 2<sup>nd</sup> course, it costs 200 days so you will finish it on the 1300<sup>th</sup> day. \nThe 4<sup>th</sup> course cannot be taken now, since you will finish it on the 3300<sup>th</sup> day, which exceeds the closed date.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> courses = [[1,2]]\n<strong>Output:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> courses = [[3,2],[4,3]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/course-schedule-iii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def scheduleCourse(self, courses: List[List[int]]) -> int:\n    time = 0\n    maxHeap = []\n\n    for duration, lastDay in sorted(courses, key=lambda x: x[1]):\n      heapq.heappush(maxHeap, -duration)\n      time += duration\n      # If current course could not be taken, check if it's able to swap with a\n      # Previously taken course with larger duration, to increase the time\n      # Available to take upcoming courses\n      if time > lastDay:\n        time += heapq.heappop(maxHeap)\n\n    return len(maxHeap)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int scheduleCourse(int[][] courses) {\n    int time = 0;\n    Arrays.sort(courses, (a, b) -> (a[1] - b[1]));\n    Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);\n\n    for (int[] c : courses) {\n      final int duration = c[0];\n      final int lastDay = c[1];\n      maxHeap.offer(duration);\n      time += c[0];\n      // If current course could not be taken, check if it's able to swap with a\n      // Previously taken course with larger duration, to increase the time\n      // Available to take upcoming courses\n      if (time > lastDay)\n        time -= maxHeap.poll();\n    }\n\n    return maxHeap.size();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int scheduleCourse(vector<vector<int>>& courses) {\n    int time = 0;\n    sort(begin(courses), end(courses),\n         [](const auto& a, const auto& b) { return a[1] < b[1]; });\n    priority_queue<int> maxHeap;\n\n    for (const vector<int>& c : courses) {\n      const int duration = c[0];\n      const int lastDay = c[1];\n      maxHeap.push(duration);\n      time += c[0];\n      // If current course could not be taken, check if it's able to swap with a\n      // Previously taken course with larger duration, to increase the time\n      // Available to take upcoming courses\n      if (time > lastDay)\n        time -= maxHeap.top(), maxHeap.pop();\n    }\n\n    return maxHeap.size();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/630.html",
    "category": "Algorithms",
    "acceptance_rate": 40.59526313022449,
    "topics": [
      "Array",
      "Greedy",
      "Sorting",
      "Heap (Priority Queue)"
    ],
    "hints": [
      "During iteration, say I want to add the current course, currentTotalTime being total time of all courses taken till now, but adding the current course might exceed my deadline or it doesn’t.</br></br>\r\n\r\n1. If it doesn’t, then I have added one new course. Increment the currentTotalTime with duration of current course.",
      "2. If it exceeds deadline, I can swap current course with current courses that has biggest duration.</br>\r\n* No harm done and I might have just reduced the currentTotalTime, right? </br>\r\n* What preprocessing do I need to do on my course processing order so that this swap is always legal?"
    ],
    "likes": 3884,
    "dislikes": 102,
    "similar_questions": "[{\"title\": \"Course Schedule\", \"titleSlug\": \"course-schedule\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Course Schedule II\", \"titleSlug\": \"course-schedule-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Parallel Courses III\", \"titleSlug\": \"parallel-courses-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"123.5K\", \"totalSubmission\": \"304.3K\", \"totalAcceptedRaw\": 123546, \"totalSubmissionRaw\": 304336, \"acRate\": \"40.6%\"}",
    "title_pt": "Cronograma de Cursos III",
    "description_pt": "<p>Há <code>n</code> cursos online diferentes numerados de <code>1</code> a <code>n</code>. Você recebe um array <code>courses</code> onde <code>courses[i] = [duration<sub>i</sub>, lastDay<sub>i</sub>]</code> indica que o <code>i<sup>ésimo</sup></code> curso deve ser feito <b>continuamente</b> por <code>duration<sub>i</sub></code> dias e deve ser concluído antes ou no <code>lastDay<sub>i</sub></code>.</p>\n\n<p>Você começará no <code>1<sup>º</sup></code> dia e não pode fazer dois ou mais cursos simultaneamente.</p>\n\n<p>Retorne <em>o número máximo de cursos que você pode fazer</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\n<strong>Saída:</strong> 3\nExplicação: \nHá ao todo 4 cursos, mas você pode fazer no máximo 3 cursos:\nPrimeiro, faça o 1<sup>º</sup> curso, ele leva 100 dias então você o concluirá no 100<sup>º</sup> dia, e estará pronto para fazer o próximo curso no 101<sup>º</sup> dia.\nSegundo, faça o 3<sup>º</sup> curso, ele leva 1000 dias então você o concluirá no 1100<sup>º</sup> dia, e estará pronto para fazer o próximo curso no 1101<sup>º</sup> dia. \nTerceiro, faça o 2<sup>º</sup> curso, ele leva 200 dias então você o concluirá no 1300<sup>º</sup> dia. \nO 4<sup>º</sup> curso não pode ser feito agora, já que você o concluirá no 3300<sup>º</sup> dia, o que excede a data de encerramento.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> courses = [[1,2]]\n<strong>Saída:</strong> 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> courses = [[3,2],[4,3]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= courses.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= duration<sub>i</sub>, lastDay<sub>i</sub> &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Durante a iteração, suponha que eu quero adicionar o curso atual, currentTotalTime sendo o tempo total de todos os cursos feitos até agora, mas adicionar o curso atual pode exceder meu prazo ou não.</br></br>\n\n1. Se não exceder, então eu adicionei um novo curso. Incremente currentTotalTime com a duração do curso atual.",
      "- Dica 2: 2. Se exceder o prazo, eu posso trocar o curso atual pelo curso atual que tem a maior duração.</br>\n* Não há problema nisso e eu talvez tenha acabado de reduzir currentTotalTime, certo? </br>\n* Que pré-processamento eu preciso fazer na minha ordem de processamento dos cursos para que essa troca seja sempre válida?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "632",
    "paidOnly": false,
    "title": "Smallest Range Covering Elements from K Lists",
    "titleSlug": "smallest-range-covering-elements-from-k-lists",
    "url": "https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists",
    "description_url": "https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/description/",
    "description": "<p>You have <code>k</code> lists of sorted integers in <strong>non-decreasing&nbsp;order</strong>. Find the <b>smallest</b> range that includes at least one number from each of the <code>k</code> lists.</p>\n\n<p>We define the range <code>[a, b]</code> is smaller than range <code>[c, d]</code> if <code>b - a &lt; d - c</code> <strong>or</strong> <code>a &lt; c</code> if <code>b - a == d - c</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\n<strong>Output:</strong> [20,24]\n<strong>Explanation: </strong>\nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]]\n<strong>Output:</strong> [1,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>nums.length == k</code></li>\n\t<li><code>1 &lt;= k &lt;= 3500</code></li>\n\t<li><code>1 &lt;= nums[i].length &lt;= 50</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums[i]</code>&nbsp;is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nWe have several lists of sorted integers, and the goal is to find the smallest range that includes at least one number from each list. The range should be as tight as possible, meaning the difference between the smallest and largest number in the range should be minimal.\n\nWe need to compare the two ranges by looking at their lengths first. If two ranges have the same size, we choose the one that starts earlier.\n\nFor example, given the lists:\n\n- List 1: `[4, 10, 15, 24, 26]`\n- List 2: `[0, 9, 12, 20]`\n- List 3: `[5, 18, 22, 30]`\n\nThe smallest range that includes at least one number from each list is `[20, 24]`.\n\nThis range works because it contains `24` from List 1, `20` from List 2, and `22` from List 3.\n\nRemember, the key is that each list is already sorted. We can approach the problem by maintaining a structure that includes one number from each list and using something to track the smallest elements across the lists, adjusting the answer as we explore larger numbers.\n\n---\n\n### Approach 1: Optimal Brute Force\n\n#### Intuition\n\nWe need to find the smallest range that contains at least one number from each of the `k` sorted lists. At first glance, a simple brute force solution comes to mind, i.e., checking every combination of elements from the lists to find the smallest range. However, that would involve too many comparisons and will lead to TLE. Instead, we can refine this process into something more manageable.\n\nAt any moment, we need to select one number from each list. So, to find the smallest range, we need to minimize the difference between the largest and smallest numbers chosen at each step. The important point here is that, at any time, our range is defined by the smallest number chosen and the largest number chosen.\n\nSo we need to select the smallest number among the current numbers picked from each list and move forward by choosing the next number from the same list that gave us this smallest number. This makes sense because moving forward in any other list would only increase the range, which we want to avoid. We repeat this process of updating the smallest number and checking if the new range is smaller than our previously found range. If it is, we update the range.\n\nWe continue this until we reach the end of one of the lists because, at that point, it’s no longer possible to select a number from each list.\n\n#### Algorithm\n\n- Initialize `k` to the number of lists in `nums` and create an array `indices` to keep track of the current index of each list, initializing all to `0`.\n- Initialize an array `range` to store the smallest range, starting with `{0, INT_MAX}`.\n\n- Enter an infinite loop:\n  - Initialize `curMin` to `INT_MAX`, `curMax` to `INT_MIN`, and `minListIndex` to `0`.\n  \n  - Iterate over each list to find the current minimum and maximum values:\n    - For each list `i`, retrieve the current element using `indices[i]`.\n    - Update `curMin` if the current element is less than `curMin`, and set `minListIndex` to `i`.\n    - Update `curMax` if the current element is greater than `curMax`.\n\n  - After checking all lists, if the difference `curMax - curMin` is smaller than the current range (`range[1] - range[0]`), update `range` to `{curMin, curMax}`.\n\n  - Move to the next element in the list that had the minimum value by incrementing `indices[minListIndex]`.\n    - If the updated index equals the size of `nums[minListIndex]`, break the loop (all elements have been processed).\n\n- Return the smallest range stored in `range`.\n\n#### Implementation\n\n> Note: Due to Python's relatively slower execution speed, the optimal brute-force solution will lead to a Time Limit Exceeded (TLE) error when using Python3. However, this same solution will perform adequately in other programming languages.\n\n<iframe src=\"https://leetcode.com/playground/3NS7uzRD/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3NS7uzRD\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the total number of elements across all lists and $k$ be the number of lists.\n\n- Time complexity: $O(n \\cdot k)$\n\n    In each iteration of the `while (true)` loop, we traverse all $k$ lists to find the current minimum and maximum. This takes $O(k)$ time.\n    \n    The loop continues until at least one of the lists is fully traversed. In the worst case, every element from every list is visited, and the total number of elements across all lists is $n$. Therefore, the loop runs $O(n)$ times.\n\n    Overall, the time complexity becomes $O(n \\cdot k)$.\n\n- Space complexity: $O(k)$\n  \n    The space complexity is dominated by the `indices` and `range` arrays, both of which have size proportional to $k$, the number of lists.\n    \n    The `indices` array stores the current index of each list, so it takes $O(k)$ space.\n\n    The `range` array also stores two integers, so it takes $O(1)$ space.\n\n    Hence, the overall space complexity is $O(k)$.\n\n---\n\n### Approach 2: Priority Queue (Heap)\n\n#### Intuition\n\nWe can build on the idea of always keeping track of the smallest element, but we can make this process more efficient. Instead of scanning all the lists to find the smallest element at every step, we use a min-heap to manage the selection of the smallest element in logarithmic time.\n\nWe start by inserting the first element from each list into the heap. The heap gives us quick access to the smallest element among the current numbers we have selected. Along with this, we also keep track of the largest number among the selected elements because our range depends on both the smallest and largest values.\n\nThe strategy is simple: at each step, we extract the smallest element from the heap (the root of the heap), which corresponds to the current smallest number. This number forms the lower bound of our current range. To continue, we replace this smallest number with the next number from the same list and add it to the heap. After updating the heap, we again check the current range between the smallest element (from the heap) and the largest element (which we track separately). If this new range is smaller than the previous best range, we update it.\n\nWe repeat this process until we can no longer add numbers from one of the lists to the heap.\n\n#### Algorithm\n\n- Initialize a priority queue `pq` to store tuples of the form (value, list_index, element_index) for the smallest elements.\n- Initialize `maxVal` to the minimum integer, `rangeStart` to 0, and `rangeEnd` to the maximum integer.\n\n- Insert the first element from each list into the min-heap:\n  - For each list in `nums`, push the first element into `pq` along with its indices.\n  - Update `maxVal` to be the maximum of itself and the newly inserted element.\n\n- Continue processing while the size of the priority queue equals the number of lists:\n  - Extract the smallest element `minVal` from `pq`, and get its corresponding indices.\n  - Update the smallest range:\n    - If the difference between `maxVal` and `minVal` is smaller than the current range (`rangeEnd - rangeStart`), update `rangeStart` to `minVal` and `rangeEnd` to `maxVal`.\n\n  - If there is a next element in the same list (check using `col + 1`):\n    - Retrieve the next value from the same list.\n    - Push this next value into `pq` along with its indices.\n    - Update `maxVal` to be the maximum of itself and the next value.\n\n- Return an array containing `rangeStart` and `rangeEnd`, which represents the smallest range covering at least one number from each of the `k` lists.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/TVxDPgAT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"TVxDPgAT\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the total number of elements across all lists and $k$ be the number of lists.\n\n- Time complexity: $O(n \\log k)$\n\n    The initial loop that inserts the first element from each list into the priority queue runs in $O(k)$. The while loop continues until we have exhausted one of the lists in the priority queue. Each iteration of the loop involves:\n    - Extracting the minimum element from the priority queue, which takes $O(\\log k)$.\n    - Inserting a new element from the same list into the priority queue, which also takes $O(\\log k)$.\n\n    In the worst case, we will process all $n$ elements, leading to a total complexity of $O(n \\log k)$.\n\n- Space complexity: $O(k)$\n\n    The priority queue can hold at most $k$ elements at any time, corresponding to the first elements of each of the $k$ lists. Thus, the space complexity is $O(k)$. Additionally, the space for storing the output range (two integers) is negligible and does not contribute to the overall complexity.\n\n---\n\n### Approach 3: Two Pointer\n\n#### Intuition\n\nSince we need a range that includes one number from each of the `k` lists, we can think of this as a subarray problem. However, the numbers are spread across multiple lists. To simplify, we can combine all the lists into a single sorted list of numbers. When merging, we also keep track of which list each number came from, since the problem requires at least one number from each original list in the final range.\n\nOnce we have the merged list, the problem becomes finding the smallest range (or subarray) in this list that contains at least one element from each of the original `k` lists. This is a common scenario for a sliding window or two-pointer approach: we want to expand and shrink the window (subarray) dynamically to find the minimum range that meets the criteria.\n\nThe right pointer will expand the window by moving forward in the merged list, and the left pointer will shrink the window once we know the window contains at least one element from each list. \n\nAs the right pointer moves through the merged list, we need to ensure that the current subarray includes at least one number from each list. So we keep track of how many lists are \"covered\" by the current subarray (i.e., how many of the `k` lists have at least one number in the current window).\n\nOnce all lists are covered, the window between the left and right pointers represents a valid range. We then check if this range is the smallest we've found so far.\n\nAfter finding a valid range, we need to shrink the window (move the left pointer forward) to see if we can make the range even smaller while still keeping one number from each list in the subarray. As we move the left pointer forward, we check if we lose coverage from any list. If we do, we stop shrinking and start expanding the window again by moving the right pointer.\n\nWe will continue this until we can no longer expand the window (i.e., the right pointer reaches the end of the merged list). By this point, we have explored all possible ranges, and the smallest valid range is our final answer.\n\n</br>\n\nThe algorithm is visualized below:\n\n!?!../Documents/632/twopointer.json:1005,565!?!\n\n#### Algorithm\n\n- Initialize an empty array `merged` to store pairs of numbers and their respective list indices.\n\n- Merge all lists into `merged`:\n  - For each list in `nums`, iterate through its numbers and add each number along with its list index to `merged`.\n\n- Sort the `merged` array to facilitate the two-pointer technique.\n\n- Initialize a frequency map `freq` to keep track of how many times each list is represented in the current window.\n- Set the `left` pointer to `0`, `count` to `0`, and initialize `rangeStart` to `0` and `rangeEnd` to `INT_MAX`.\n\n- Use a `right` pointer to iterate through the `merged` array:\n  - Increment the count for the list index in `freq` for `merged[right]`.\n  - If the count for this list index becomes `1`, increment `count` (indicating a new list is represented).\n\n- When all lists are represented (i.e., `count == nums.size()`):\n  - Calculate the current range as `curRange = merged[right].first - merged[left].first`.\n  - If `curRange` is smaller than the previously found range (`rangeEnd - rangeStart`):\n    - Update `rangeStart` and `rangeEnd` to the current numbers.\n\n  - Decrement the frequency count for the leftmost number (i.e., `merged[left]`).\n  - If this list index's frequency becomes `0`, decrement `count` (indicating that a list is no longer represented).\n  - Move the `left` pointer to the right to attempt shrinking the window.\n\n- After completing the iteration, return the smallest range as a array containing `rangeStart` and `rangeEnd`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/M44X3Nwg/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"M44X3Nwg\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the total number of elements across all lists and $k$ be the number of lists.\n\n- Time complexity: $O(n \\log n)$\n\n    The first nested loop iterates over $k$ lists, and for each list, it iterates through its elements. In the worst case, this requires $O(n)$ time since we are processing all elements once. \n\n    After merging, we sort the `merged` array which contains $n$ elements. Sorting has a time complexity of $O(n \\log n)$.\n\n    The two-pointer approach iterates through the `merged` list once (with the right pointer) and may also move the left pointer forward multiple times. In total, each pointer will traverse the `merged` list at most $n$ times.\n\n    Combining these steps, the overall time complexity is: $O(n \\log n)$\n\n- Space complexity: $O(n)$ \n\n    We create a `merged` array to hold $n$ elements, which requires $O(n)$ space.\n\n    We use an unordered map (`freq`) that can potentially store $k$ elements (one for each list). Thus, this requires $O(k)$ space.\n\n    Some extra space is used when we sort an array. The space complexity of the sorting algorithm ($S$) depends on the programming language.\n    - In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has a space complexity of $O(n)$.\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worst-case space complexity of $O( \\log n )$.\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$.\n\n    Combining these, the overall space complexity is: $O(n)$ \n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def smallestRange(self, nums: List[List[int]]) -> List[int]:\n    minHeap = [(row[0], i, 0) for i, row in enumerate(nums)]\n    heapq.heapify(minHeap)\n\n    maxRange = max(row[0] for row in nums)\n    minRange = heapq.nsmallest(1, minHeap)[0][0]\n    ans = [minRange, maxRange]\n\n    while len(minHeap) == len(nums):\n      num, r, c = heapq.heappop(minHeap)\n      if c + 1 < len(nums[r]):\n        heapq.heappush(minHeap, (nums[r][c + 1], r, c + 1))\n        maxRange = max(maxRange, nums[r][c + 1])\n        minRange = heapq.nsmallest(1, minHeap)[0][0]\n        if maxRange - minRange < ans[1] - ans[0]:\n          ans[0], ans[1] = minRange, maxRange\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int i;\n  public int j;\n  public int num; // nums[i][j]\n  public T(int i, int j, int num) {\n    this.i = i;\n    this.j = j;\n    this.num = num;\n  }\n}\n\nclass Solution {\n  public int[] smallestRange(List<List<Integer>> nums) {\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.num - b.num);\n    int min = Integer.MAX_VALUE;\n    int max = Integer.MIN_VALUE;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      final int num = nums.get(i).get(0);\n      minHeap.offer(new T(i, 0, num));\n      min = Math.min(min, num);\n      max = Math.max(max, num);\n    }\n\n    int minRange = min;\n    int maxRange = max;\n\n    while (minHeap.size() == nums.size()) {\n      final int i = minHeap.peek().i;\n      final int j = minHeap.poll().j;\n      if (j + 1 < nums.get(i).size()) {\n        minHeap.offer(new T(i, j + 1, nums.get(i).get(j + 1)));\n        max = Math.max(max, nums.get(i).get(j + 1));\n        min = minHeap.peek().num;\n      }\n      if (max - min < maxRange - minRange) {\n        minRange = min;\n        maxRange = max;\n      }\n    }\n\n    return new int[] {minRange, maxRange};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int i;\n  int j;\n  int num;  // nums[i][j]\n  T(int i, int j, int num) : i(i), j(j), num(num) {}\n};\n\nclass Solution {\n public:\n  vector<int> smallestRange(vector<vector<int>>& nums) {\n    auto compare = [&](const T& a, const T& b) { return a.num > b.num; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n    int mini = INT_MAX;\n    int maxi = INT_MIN;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const int num = nums[i][0];\n      minHeap.emplace(i, 0, num);\n      mini = min(mini, num);\n      maxi = max(maxi, num);\n    }\n\n    int minRange = mini;\n    int maxRange = maxi;\n\n    while (minHeap.size() == nums.size()) {\n      const auto [i, j, _] = minHeap.top();\n      minHeap.pop();\n      if (j + 1 < nums[i].size()) {\n        minHeap.emplace(i, j + 1, nums[i][j + 1]);\n        maxi = max(maxi, nums[i][j + 1]);\n        mini = minHeap.top().num;\n        if (maxi - mini < maxRange - minRange) {\n          minRange = mini;\n          maxRange = maxi;\n        }\n      }\n    }\n\n    return {minRange, maxRange};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/632.html",
    "category": "Algorithms",
    "acceptance_rate": 69.7366546198785,
    "topics": [
      "Array",
      "Hash Table",
      "Greedy",
      "Sliding Window",
      "Sorting",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 4193,
    "dislikes": 95,
    "similar_questions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"215.3K\", \"totalSubmission\": \"308.8K\", \"totalAcceptedRaw\": 215342, \"totalSubmissionRaw\": 308794, \"acRate\": \"69.7%\"}",
    "title_pt": "Menor Intervalo que Cobre Elementos de K Listas",
    "description_pt": "<p>Você tem <code>k</code> listas de inteiros ordenados em <strong>ordem não decrescente&nbsp;</strong>. Encontre o <b>menor</b> intervalo que inclua pelo menos um número de cada uma das <code>k</code> listas.</p>\n\n<p>Definimos que o intervalo <code>[a, b]</code> é menor do que o intervalo <code>[c, d]</code> se <code>b - a &lt; d - c</code> <strong>ou</strong> <code>a &lt; c</code> se <code>b - a == d - c</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\n<strong>Saída:</strong> [20,24]\n<strong>Explicação: </strong>\nLista 1: [4, 10, 15, 24,26], 24 está no intervalo [20,24].\nLista 2: [0, 9, 12, 20], 20 está no intervalo [20,24].\nLista 3: [5, 18, 22, 30], 22 está no intervalo [20,24].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [[1,2,3],[1,2,3],[1,2,3]]\n<strong>Saída:</strong> [1,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>nums.length == k</code></li>\n\t<li><code>1 &lt;= k &lt;= 3500</code></li>\n\t<li><code>1 &lt;= nums[i].length &lt;= 50</code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i][j] &lt;= 10<sup>5</sup></code></li>\n\t<li><code>nums[i]</code>&nbsp;está ordenado em <strong>ordem não decrescente</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "633",
    "paidOnly": false,
    "title": "Sum of Square Numbers",
    "titleSlug": "sum-of-square-numbers",
    "url": "https://leetcode.com/problems/sum-of-square-numbers",
    "description_url": "https://leetcode.com/problems/sum-of-square-numbers/description/",
    "description": "<p>Given a non-negative integer <code>c</code>, decide whether there&#39;re two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> c = 5\n<strong>Output:</strong> true\n<strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> c = 3\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/sum-of-square-numbers/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach 1: Brute Force\n\nThe simplest solution would be to consider every possible combination of integers $a$ and $b$ and check if the sum of their squares equals $c$. Now, both $a$ and $b$ can lie within the range $(0,\\sqrt{c})$. Thus, we need to check for the values of $a$ and $b$ in this range only.\n\n<iframe src=\"https://leetcode.com/playground/bun3d8ez/shared\" frameBorder=\"0\" width=\"100%\" height=\"242\" name=\"bun3d8ez\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $O(c)$. \n\n    Two loops up to $\\sqrt{c}$. Here, $c$ refers to the given integer (sum of squares).\n\n* Space complexity : $O(1)$. \n    \n    Constant extra space is used.\n\n---\n\n### Approach 2: Better Brute Force\n\nWe can improve the last solution, if we make the following observation. For any particular $a$ chosen, the value of $b$ required to satisfy the equation $a^2 + b^2 = c$ will be such that $b^2 = c - a^2$. Thus, we need to traverse over the range $(0, \\sqrt{c})$ only for considering the various values of $a$. For every current value of $a$ chosen, we can determine the corresponding $b^2$ value and check if it is a perfect square or not. If it happens to be a perfect square, $c$ is a sum of squares of two integers, otherwise not.\n\nNow, to determine, if the number $c - a^2$ is a perfect square or not, we can make use of the following theorem:\n\n>The square of $n^{th}$ positive integer can be represented as a sum of first $n$ odd positive integers.\n \nOr in mathematical terms:\n\n$$\nn^2 = 1 + 3 + 5 + ... + (2 \\cdot n-1) = \\sum_{i=1}^{n} (2 \\cdot i - 1)\n$$\n\nTo look at the proof of this statement, look at the L.H.S. of the above statement.\n\n$$\n\\begin{aligned}\n&1 + 3 + 5 + \\ldots + (2 \\cdot n-1) \\\\\n= \\; &(2 \\cdot 1-1) + (2 \\cdot 2-1) + (2 \\cdot 3-1) + \\ldots + (2 \\cdot n-1) \\\\\n= \\; &2 \\cdot (1+2+3+....+n) - (\\underbrace{1+1+ \\ldots +1}_{n\\text{ times}}) \\\\\n= \\; &2 \\cdot \\frac{n\\;(n+1)}{2} - n \\\\\n= \\; &n\\;(n+1) - n \\\\\n= \\; &n^2 + n - n \\\\\n= \\; &n^2\n\\end{aligned}\n$$\n\nThis completes the proof of the above statement.\n\n<iframe src=\"https://leetcode.com/playground/ZTefZRX8/shared\" frameBorder=\"0\" width=\"100%\" height=\"310\" name=\"ZTefZRX8\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $O(c)$. \n    \n    The total number of times the $sum$ is updated is: $1 + 2 + 3 + \\ldots + \\sqrt{c} = \\frac{\\sqrt{c}\\;(\\sqrt{c}+1)}{2} = O(c)$.\n\n* Space complexity : $O(1)$. \n\n    Constant extra space is used.\n\n---\n\n### Approach 3: Using Sqrt Function\n\n**Algorithm**\n\nInstead of finding if $c - a^2$ is a perfect square using sum of odd numbers, as done in the last approach, we can make use of the inbuilt $sqrt$ function and check if $\\sqrt{c - a^2}$ turns out to be an integer. If it happens for any value of $a$ in the range $[0, \\sqrt{c}]$, we can return a True value immediately.\n\n<iframe src=\"https://leetcode.com/playground/N9KMxCjz/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"N9KMxCjz\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $O\\big(\\sqrt{c}\\log c\\big)$. \n\n    We iterate over $\\sqrt{c}$ values for choosing $a$. For every $a$ chosen, finding square root of $c - a^2$ takes $O\\big(\\log c\\big)$ time in the worst case.\n\n* Space complexity : $O(1)$. \n\n    Constant extra space is used.\n\n---\n\n### Approach 4: Binary Search\n\n**Algorithm**\n\nAnother method to check if $c - a^2$ is a perfect square, is by making use of Binary Search. The method remains same as that of a typical Binary Search to find a number.\nThe only difference lies in that we need to find an integer, $mid$ in the range $[0, c - a^2]$, such that this number is the square root of $c - a^2$.\nOr in other words, we need to find an integer, $mid$, in the range $[0, c - a^2]$, such that $mid \\times mid = c - a^2$.\n\nThe following animation illustrates the search process for a particular value of $c - a^2 = 36$.\n\n!?!../Documents/633_Sum_of_Squares.json:1000,563!?!\n\n\n<iframe src=\"https://leetcode.com/playground/6o4MgefR/shared\" frameBorder=\"0\" width=\"100%\" height=\"395\" name=\"6o4MgefR\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $O\\big(\\sqrt{c}\\log c\\big)$. \n    Binary search taking $O\\big(\\log c\\big)$ in the worst case is done for $\\sqrt{c}$ values of $a$.\n\n* Space complexity : $O(\\log c)$. Binary Search will take $O(\\log c)$ space.\n\n---\n\n### Approach 5: Fermat Theorem\n\n**Algorithm**\n\nThis approach is based on the following statement, which is based on Fermat's Theorem:\n\n>Any positive number $n$ is expressible as a sum of two squares if and only if the prime factorization of $n$, every prime of the form $(4k+3)$ occurs an even number of times.\n\nBy making use of the above theorem, we can directly find out if the given number $c$ can be expressed as a sum of two squares.\n\nTo do so we simply find all the prime factors of the given number $c$, which could range from $[2,\\sqrt{c}]$ along with the count of those factors, by repeated division. \nIf at any step, we find out that the number of occurrences of any prime factor of the form $(4k+3)$ occurs an odd number of times, we can return a False value.\n\nIn case, $c$ itself is a prime number, it won't be divisible by any of the primes in the $[2,\\sqrt{c}]$. Thus, we need to check if $c$ can be expressed in the form of\n$4k+3$. If so, we need to return a False value, indicating that this prime occurs an odd number(1) of times. \n\nOtherwise, we can return a True value.\n\nThe proof of this theorem includes the knowledge of advanced mathematics and is beyond the scope of this article. However, interested reader can refer to [this](http://wstein.org/edu/124/lectures/lecture21/lecture21/node2.html) documentation.\n\n<iframe src=\"https://leetcode.com/playground/j4TXamHq/shared\" frameBorder=\"0\" width=\"100%\" height=\"327\" name=\"j4TXamHq\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $O\\left(\\sqrt{c}\\right)$.\n\n    We find the factors of $c$ and their count using repeated division. We check for the factors in the range $[0, \\sqrt{c}]$.\n    \n    However, the number of times a factor can occur is spread over the entire outer loop, so the entire complexity caused by the inner loop is effectively $O(\\log c)$. As a result, the total time complexity is $O(\\sqrt{c} + \\log c) = O\\left(\\sqrt{c}\\right)$.\n\n* Space complexity : $O(1)$. \n\n    Constant space is used.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def judgeSquareSum(self, c: int) -> bool:\n    l = 0\n    r = int(sqrt(c))\n\n    while l <= r:\n      summ = l * l + r * r\n      if summ == c:\n        return True\n      if summ < c:\n        l += 1\n      else:\n        r -= 1\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean judgeSquareSum(int c) {\n    int l = 0;\n    int r = (int) Math.sqrt(c);\n\n    while (l <= r) {\n      final int sum = l * l + r * r;\n      if (sum == c)\n        return true;\n      if (sum < c)\n        ++l;\n      else\n        --r;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool judgeSquareSum(int c) {\n    unsigned l = 0;\n    unsigned r = sqrt(c);\n\n    while (l <= r) {\n      const unsigned sum = l * l + r * r;\n      if (sum == c)\n        return true;\n      if (sum < c)\n        ++l;\n      else\n        --r;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/633.html",
    "category": "Algorithms",
    "acceptance_rate": 36.45941948155872,
    "topics": [
      "Math",
      "Two Pointers",
      "Binary Search"
    ],
    "hints": [],
    "likes": 3319,
    "dislikes": 614,
    "similar_questions": "[{\"title\": \"Valid Perfect Square\", \"titleSlug\": \"valid-perfect-square\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sum of Squares of Special Elements \", \"titleSlug\": \"sum-of-squares-of-special-elements\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"390.9K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 390923, \"totalSubmissionRaw\": 1072213, \"acRate\": \"36.5%\"}",
    "title_pt": "Soma de Dois Quadrados",
    "description_pt": "<p>Dado um inteiro não negativo <code>c</code>, decida se existem dois inteiros <code>a</code> e <code>b</code> tais que <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> c = 5\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> 1 * 1 + 2 * 2 = 5\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> c = 3\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "636",
    "paidOnly": false,
    "title": "Exclusive Time of Functions",
    "titleSlug": "exclusive-time-of-functions",
    "url": "https://leetcode.com/problems/exclusive-time-of-functions",
    "description_url": "https://leetcode.com/problems/exclusive-time-of-functions/description/",
    "description": "<p>On a <strong>single-threaded</strong> CPU, we execute a program containing <code>n</code> functions. Each function has a unique ID between <code>0</code> and <code>n-1</code>.</p>\n\n<p>Function calls are <strong>stored in a <a href=\"https://en.wikipedia.org/wiki/Call_stack\">call stack</a></strong>: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is <strong>the current function being executed</strong>. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.</p>\n\n<p>You are given a list <code>logs</code>, where <code>logs[i]</code> represents the <code>i<sup>th</sup></code> log message formatted as a string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. For example, <code>&quot;0:start:3&quot;</code> means a function call with function ID <code>0</code> <strong>started at the beginning</strong> of timestamp <code>3</code>, and <code>&quot;1:end:2&quot;</code> means a function call with function ID <code>1</code> <strong>ended at the end</strong> of timestamp <code>2</code>. Note that a function can be called <b>multiple times, possibly recursively</b>.</p>\n\n<p>A function&#39;s <strong>exclusive time</strong> is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for <code>2</code> time units and another call executing for <code>1</code> time unit, the <strong>exclusive time</strong> is <code>2 + 1 = 3</code>.</p>\n\n<p>Return <em>the <strong>exclusive time</strong> of each function in an array, where the value at the </em><code>i<sup>th</sup></code><em> index represents the exclusive time for the function with ID </em><code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/04/05/diag1b.png\" style=\"width: 550px; height: 239px;\" />\n<pre>\n<strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;]\n<strong>Output:</strong> [3,4]\n<strong>Explanation:</strong>\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;]\n<strong>Output:</strong> [8]\n<strong>Explanation:</strong>\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;]\n<strong>Output:</strong> [7,1]\n<strong>Explanation:</strong>\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>2 &lt;= logs.length &lt;= 500</code></li>\n\t<li><code>0 &lt;= function_id &lt; n</code></li>\n\t<li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li>\n\t<li>No two start events will happen at the same timestamp.</li>\n\t<li>No two end events will happen at the same timestamp.</li>\n\t<li>Each function has an <code>&quot;end&quot;</code> log for each <code>&quot;start&quot;</code> log.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/exclusive-time-of-functions/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] exclusiveTime(int n, List<String> logs) {\n    int[] ans = new int[n];\n    Deque<Integer> stack = new ArrayDeque<>(); // [oldest_id, ..., latest_id]\n    int prevTime = -1;\n\n    for (final String log : logs) {\n      final String[] splits = log.split(\":\");\n      // Get function_id, label, and timestamp\n      final int id = Integer.parseInt(splits[0]);        // {function_id}\n      final char label = splits[1].charAt(0);            // {\"s\" (\"start\") | \"e\" (\"end\") }\n      final int timestamp = Integer.parseInt(splits[2]); // {timestamp}\n      if (label == 's') {\n        if (!stack.isEmpty())\n          ans[stack.peek()] += timestamp - prevTime;\n        stack.push(id);\n        prevTime = timestamp;\n      } else {\n        ans[stack.pop()] += timestamp - prevTime + 1;\n        prevTime = timestamp + 1;\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> exclusiveTime(int n, vector<string>& logs) {\n    vector<int> ans(n);\n    stack<int> stack;  // [oldest_id, ..., latest_id]\n    int prevTime;\n\n    for (const string& log : logs) {\n      // Get seperators' indices\n      const int colon1 = log.find_first_of(':');\n      const int colon2 = log.find_last_of(':');\n      // Get function_id, label, and timestamp\n      const int id = stoi(log.substr(0, colon1));  // {function_id}\n      const char label = log[colon1 + 1];  // {\"s\" (\"start\") | \"e\" (\"end\") }\n      const int timestamp = stoi(log.substr(colon2 + 1));  // {timestamp}\n      if (label == 's') {\n        if (!stack.empty())\n          ans[stack.top()] += timestamp - prevTime;\n        stack.push(id);\n        prevTime = timestamp;\n      } else {\n        ans[stack.top()] += timestamp - prevTime + 1, stack.pop();\n        prevTime = timestamp + 1;\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/636.html",
    "category": "Algorithms",
    "acceptance_rate": 64.62231356787214,
    "topics": [
      "Array",
      "Stack"
    ],
    "hints": [],
    "likes": 2068,
    "dislikes": 2889,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"276.1K\", \"totalSubmission\": \"427.2K\", \"totalAcceptedRaw\": 276060, \"totalSubmissionRaw\": 427190, \"acRate\": \"64.6%\"}",
    "title_pt": "Tempo Exclusivo de Funções",
    "description_pt": "<p>Em uma CPU <strong>single-threaded</strong>, executamos um programa contendo <code>n</code> funções. Cada função tem um ID único entre <code>0</code> e <code>n-1</code>.</p>\n\n<p>Chamadas de função são <strong>armazenadas em uma <a href=\"https://en.wikipedia.org/wiki/Call_stack\">pilha de chamadas</a></strong>: quando uma chamada de função começa, seu ID é empilhado, e quando uma chamada de função termina, seu ID é desempilhado. A função cujo ID está no topo da pilha é <strong>a função atualmente sendo executada</strong>. Cada vez que uma função começa ou termina, escrevemos um log com o ID, se ela começou ou terminou, e o timestamp.</p>\n\n<p>Você recebe uma lista <code>logs</code>, onde <code>logs[i]</code> representa a <code>i<sup>th</sup></code> mensagem de log formatada como uma string <code>&quot;{function_id}:{&quot;start&quot; | &quot;end&quot;}:{timestamp}&quot;</code>. Por exemplo, <code>&quot;0:start:3&quot;</code> significa que uma chamada de função com ID de função <code>0</code> <strong>começou no início</strong> do timestamp <code>3</code>, e <code>&quot;1:end:2&quot;</code> significa que uma chamada de função com ID de função <code>1</code> <strong>terminou no final</strong> do timestamp <code>2</code>. Note que uma função pode ser chamada <b>múltiplas vezes, possivelmente recursivamente</b>.</p>\n\n<p>O <strong>tempo exclusivo</strong> de uma função é a soma dos tempos de execução de todas as chamadas de função no programa. Por exemplo, se uma função é chamada duas vezes, uma chamada executando por <code>2</code> unidades de tempo e outra chamada executando por <code>1</code> unidade de tempo, o <strong>tempo exclusivo</strong> é <code>2 + 1 = 3</code>.</p>\n\n<p>Retorne <em>o <strong>tempo exclusivo</strong> de cada função em um array, onde o valor no índice </em><code>i<sup>th</sup></code><em> representa o tempo exclusivo da função com ID </em><code>i</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2019/04/05/diag1b.png\" style=\"width: 550px; height: 239px;\" />\n<pre>\n<strong>Entrada:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;1:start:2&quot;,&quot;1:end:5&quot;,&quot;0:end:6&quot;]\n<strong>Saída:</strong> [3,4]\n<strong>Explicação:</strong>\nFunção 0 começa no início do tempo 0, então ela executa por 2 unidades de tempo e alcança o fim do tempo 1.\nFunção 1 começa no início do tempo 2, executa por 4 unidades de tempo e termina no fim do tempo 5.\nFunção 0 retoma a execução no início do tempo 6 e executa por 1 unidade de tempo.\nAssim, a função 0 gasta 2 + 1 = 3 unidades de tempo total executando, e a função 1 gasta 4 unidades de tempo total executando.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;0:start:6&quot;,&quot;0:end:6&quot;,&quot;0:end:7&quot;]\n<strong>Saída:</strong> [8]\n<strong>Explicação:</strong>\nFunção 0 começa no início do tempo 0, executa por 2 unidades de tempo e chama a si mesma recursivamente.\nFunção 0 (chamada recursiva) começa no início do tempo 2 e executa por 4 unidades de tempo.\nFunção 0 (chamada inicial) retoma a execução e então imediatamente chama a si mesma novamente.\nFunção 0 (2ª chamada recursiva) começa no início do tempo 6 e executa por 1 unidade de tempo.\nFunção 0 (chamada inicial) retoma a execução no início do tempo 7 e executa por 1 unidade de tempo.\nAssim, a função 0 gasta 2 + 4 + 1 + 1 = 8 unidades de tempo total executando.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2, logs = [&quot;0:start:0&quot;,&quot;0:start:2&quot;,&quot;0:end:5&quot;,&quot;1:start:6&quot;,&quot;1:end:6&quot;,&quot;0:end:7&quot;]\n<strong>Saída:</strong> [7,1]\n<strong>Explicação:</strong>\nFunção 0 começa no início do tempo 0, executa por 2 unidades de tempo e chama a si mesma recursivamente.\nFunção 0 (chamada recursiva) começa no início do tempo 2 e executa por 4 unidades de tempo.\nFunção 0 (chamada inicial) retoma a execução e então imediatamente chama a função 1.\nFunção 1 começa no início do tempo 6, executa 1 unidade de tempo e termina no fim do tempo 6.\nFunção 0 retoma a execução no início do tempo 6 e executa por 2 unidades de tempo.\nAssim, a função 0 gasta 2 + 4 + 1 = 7 unidades de tempo total executando, e a função 1 gasta 1 unidade de tempo total executando.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 100</code></li>\n\t<li><code>2 &lt;= logs.length &lt;= 500</code></li>\n\t<li><code>0 &lt;= function_id &lt; n</code></li>\n\t<li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li>\n\t<li>Nenhum dois eventos de início acontecerão no mesmo timestamp.</li>\n\t<li>Nenhum dois eventos de término acontecerão no mesmo timestamp.</li>\n\t<li>Cada função tem um log de <code>&quot;end&quot;</code> para cada log de <code>&quot;start&quot;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "637",
    "paidOnly": false,
    "title": "Average of Levels in Binary Tree",
    "titleSlug": "average-of-levels-in-binary-tree",
    "url": "https://leetcode.com/problems/average-of-levels-in-binary-tree",
    "description_url": "https://leetcode.com/problems/average-of-levels-in-binary-tree/description/",
    "description": "Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,null,null,15,7]\n<strong>Output:</strong> [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [3,9,20,15,7]\n<strong>Output:</strong> [3.00000,14.50000,11.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/average-of-levels-in-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Double> averageOfLevels(TreeNode root) {\n    List<Double> ans = new ArrayList<>();\n    Queue<TreeNode> q = new ArrayDeque<>(Arrays.asList(root));\n\n    while (!q.isEmpty()) {\n      long sum = 0;\n      final int size = q.size();\n      for (int i = 0; i < size; ++i) {\n        TreeNode node = q.poll();\n        sum += node.val;\n        if (node.left != null)\n          q.offer(node.left);\n        if (node.right != null)\n          q.offer(node.right);\n      }\n      ans.add(sum / (double) size);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<double> averageOfLevels(TreeNode* root) {\n    vector<double> ans;\n    queue<TreeNode*> q{{root}};\n\n    while (!q.empty()) {\n      long sum = 0;\n      const int size = q.size();\n      for (int i = 0; i < size; ++i) {\n        TreeNode* node = q.front();\n        q.pop();\n        sum += node->val;\n        if (node->left)\n          q.push(node->left);\n        if (node->right)\n          q.push(node->right);\n      }\n      ans.push_back(sum / (double)size);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/637.html",
    "category": "Algorithms",
    "acceptance_rate": 74.01297328940531,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5437,
    "dislikes": 346,
    "similar_questions": "[{\"title\": \"Binary Tree Level Order Traversal\", \"titleSlug\": \"binary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Level Order Traversal II\", \"titleSlug\": \"binary-tree-level-order-traversal-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"642.3K\", \"totalSubmission\": \"867.8K\", \"totalAcceptedRaw\": 642268, \"totalSubmissionRaw\": 867778, \"acRate\": \"74.0%\"}",
    "title_pt": "Média dos Níveis em uma Árvore Binária",
    "description_pt": "Dado a <code>root</code> de uma árvore binária, retorne <em>a média dos valores dos nós em cada nível na forma de um array</em>. Respostas dentro de <code>10<sup>-5</sup></code> da resposta real serão aceitas.\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg\" style=\"width: 277px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,null,null,15,7]\n<strong>Saída:</strong> [3.00000,14.50000,11.00000]\nExplicação: A média dos valores dos nós no nível 0 é 3, no nível 1 é 14.5, e no nível 2 é 11.\nAssim, retorne [3, 14.5, 11].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg\" style=\"width: 292px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,9,20,15,7]\n<strong>Saída:</strong> [3.00000,14.50000,11.00000]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "638",
    "paidOnly": false,
    "title": "Shopping Offers",
    "titleSlug": "shopping-offers",
    "url": "https://leetcode.com/problems/shopping-offers",
    "description_url": "https://leetcode.com/problems/shopping-offers/description/",
    "description": "<p>In LeetCode Store, there are <code>n</code> items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.</p>\n\n<p>You are given an integer array <code>price</code> where <code>price[i]</code> is the price of the <code>i<sup>th</sup></code> item, and an integer array <code>needs</code> where <code>needs[i]</code> is the number of pieces of the <code>i<sup>th</sup></code> item you want to buy.</p>\n\n<p>You are also given an array <code>special</code> where <code>special[i]</code> is of size <code>n + 1</code> where <code>special[i][j]</code> is the number of pieces of the <code>j<sup>th</sup></code> item in the <code>i<sup>th</sup></code> offer and <code>special[i][n]</code> (i.e., the last integer in the array) is the price of the <code>i<sup>th</sup></code> offer.</p>\n\n<p>Return <em>the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers</em>. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\n<strong>Output:</strong> 14\n<strong>Explanation:</strong> There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == price.length == needs.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 6</code></li>\n\t<li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li>\n\t<li><code>1 &lt;= special.length &lt;= 100</code></li>\n\t<li><code>special[i].length == n + 1</code></li>\n\t<li><code>0 &lt;= special[i][j] &lt;= 50</code></li>\n\t<li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/shopping-offers/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n    def dfs(s: int) -> int:\n      ans = 0\n      for i, need in enumerate(needs):\n        ans += need * price[i]\n\n      for i in range(s, len(special)):\n        offer = special[i]\n        if all(offer[j] <= need for j, need in enumerate(needs)):\n          # Use special[i]\n          for j in range(len(needs)):\n            needs[j] -= offer[j]\n          ans = min(ans, offer[-1] + dfs(i))\n          # Backtracking - unuse special[i]\n          for j in range(len(needs)):\n            needs[j] += offer[j]\n\n      return ans\n\n    return dfs(0)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {\n    return dfs(price, special, needs, 0);\n  }\n\n  private int dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, int s) {\n    int ans = 0;\n    for (int i = 0; i < needs.size(); ++i)\n      ans += needs.get(i) * price.get(i);\n\n    for (int i = s; i < special.size(); ++i) {\n      List<Integer> offer = special.get(i);\n      if (isValid(offer, needs)) {\n        // Use special[i]\n        for (int j = 0; j < needs.size(); ++j)\n          needs.set(j, needs.get(j) - offer.get(j));\n        ans = Math.min(ans, offer.get(offer.size() - 1) + dfs(price, special, needs, i));\n        // Backtracking - unuse special[i]\n        for (int j = 0; j < needs.size(); ++j)\n          needs.set(j, needs.get(j) + offer.get(j));\n      }\n    }\n\n    return ans;\n  }\n\n  // Check if this special offer is a valid one\n  private boolean isValid(List<Integer> offer, List<Integer> needs) {\n    for (int i = 0; i < needs.size(); ++i)\n      if (offer.get(i) > needs.get(i))\n        return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int shoppingOffers(vector<int>& price, vector<vector<int>>& special,\n                     vector<int>& needs) {\n    return dfs(price, special, needs, 0);\n  }\n\n private:\n  int dfs(const vector<int>& price, const vector<vector<int>>& special,\n          vector<int>& needs, int s) {\n    int ans = 0;\n    for (int i = 0; i < price.size(); ++i)\n      ans += price[i] * needs[i];\n\n    for (int i = s; i < special.size(); ++i)\n      if (isValid(special[i], needs)) {\n        // Use special[i]\n        for (int j = 0; j < needs.size(); ++j)\n          needs[j] -= special[i][j];\n        ans = min(ans, special[i].back() + dfs(price, special, needs, i));\n        // Backtracking - unuse special[i]\n        for (int j = 0; j < needs.size(); ++j)\n          needs[j] += special[i][j];\n      }\n\n    return ans;\n  }\n\n  // Check if this special offer is a valid one\n  bool isValid(const vector<int>& offer, const vector<int>& needs) {\n    for (int i = 0; i < needs.size(); ++i)\n      if (needs[i] < offer[i])\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/638.html",
    "category": "Algorithms",
    "acceptance_rate": 51.84753822301021,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Backtracking",
      "Bit Manipulation",
      "Memoization",
      "Bitmask"
    ],
    "hints": [],
    "likes": 1576,
    "dislikes": 775,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"69.9K\", \"totalSubmission\": \"134.8K\", \"totalAcceptedRaw\": 69891, \"totalSubmissionRaw\": 134801, \"acRate\": \"51.8%\"}",
    "title_pt": "Ofertas de Compras",
    "description_pt": "<p>No LeetCode Store, há <code>n</code> itens à venda. Cada item tem um preço. No entanto, existem algumas ofertas especiais, e uma oferta especial consiste em um ou mais tipos diferentes de itens com um preço promocional.</p>\n\n<p>Você recebe um array de inteiros <code>price</code> em que <code>price[i]</code> é o preço do <code>i<sup>th</sup></code> item, e um array de inteiros <code>needs</code> em que <code>needs[i]</code> é o número de peças do <code>i<sup>th</sup></code> item que você deseja comprar.</p>\n\n<p>Você também recebe um array <code>special</code> em que <code>special[i]</code> tem tamanho <code>n + 1</code>, onde <code>special[i][j]</code> é o número de peças do <code>j<sup>th</sup></code> item na <code>i<sup>th</sup></code> oferta e <code>special[i][n]</code> (ou seja, o último inteiro no array) é o preço da <code>i<sup>th</sup></code> oferta.</p>\n\n<p>Retorne <em>o menor preço que você precisa pagar exatamente pelos itens indicados, onde você pode fazer uso ótimo das ofertas especiais</em>. Você não tem permissão para comprar mais itens do que deseja, mesmo que isso reduzisse o preço total. Você pode usar qualquer uma das ofertas especiais quantas vezes quiser.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\n<strong>Saída:</strong> 14\n<strong>Explicação:</strong> Há dois tipos de itens, A e B. Seus preços são $2 e $5, respectivamente. \nNa oferta especial 1, você pode pagar $5 por 3A e 0B\nNa oferta especial 2, você pode pagar $10 por 1A e 2B. \nVocê precisa comprar 3A e 2B, então você pode pagar $10 por 1A e 2B (oferta especial #2), e $4 por 2A.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\n<strong>Saída:</strong> 11\n<strong>Explicação:</strong> O preço de A é $2, e $3 para B, $4 para C. \nVocê pode pagar $4 por 1A e 1B, e $9 por 2A ,2B e 1C. \nVocê precisa comprar 1A ,2B e 1C, então você pode pagar $4 por 1A e 1B (oferta especial #1), e $3 por 1B, $4 por 1C. \nVocê não pode adicionar mais itens, embora apenas $9 por 2A ,2B e 1C.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == price.length == needs.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 6</code></li>\n\t<li><code>0 &lt;= price[i], needs[i] &lt;= 10</code></li>\n\t<li><code>1 &lt;= special.length &lt;= 100</code></li>\n\t<li><code>special[i].length == n + 1</code></li>\n\t<li><code>0 &lt;= special[i][j] &lt;= 50</code></li>\n\t<li>The input is generated that at least one of <code>special[i][j]</code> is non-zero for <code>0 &lt;= j &lt;= n - 1</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "639",
    "paidOnly": false,
    "title": "Decode Ways II",
    "titleSlug": "decode-ways-ii",
    "url": "https://leetcode.com/problems/decode-ways-ii",
    "description_url": "https://leetcode.com/problems/decode-ways-ii/description/",
    "description": "<p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p>\n\n<pre>\n&#39;A&#39; -&gt; &quot;1&quot;\n&#39;B&#39; -&gt; &quot;2&quot;\n...\n&#39;Z&#39; -&gt; &quot;26&quot;\n</pre>\n\n<p>To <strong>decode</strong> an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, <code>&quot;11106&quot;</code> can be mapped into:</p>\n\n<ul>\n\t<li><code>&quot;AAJF&quot;</code> with the grouping <code>(1 1 10 6)</code></li>\n\t<li><code>&quot;KJF&quot;</code> with the grouping <code>(11 10 6)</code></li>\n</ul>\n\n<p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>&quot;06&quot;</code> cannot be mapped into <code>&#39;F&#39;</code> since <code>&quot;6&quot;</code> is different from <code>&quot;06&quot;</code>.</p>\n\n<p><strong>In addition</strong> to the mapping above, an encoded message may contain the <code>&#39;*&#39;</code> character, which can represent any digit from <code>&#39;1&#39;</code> to <code>&#39;9&#39;</code> (<code>&#39;0&#39;</code> is excluded). For example, the encoded message <code>&quot;1*&quot;</code> may represent any of the encoded messages <code>&quot;11&quot;</code>, <code>&quot;12&quot;</code>, <code>&quot;13&quot;</code>, <code>&quot;14&quot;</code>, <code>&quot;15&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;17&quot;</code>, <code>&quot;18&quot;</code>, or <code>&quot;19&quot;</code>. Decoding <code>&quot;1*&quot;</code> is equivalent to decoding <strong>any</strong> of the encoded messages it can represent.</p>\n\n<p>Given a string <code>s</code> consisting of digits and <code>&#39;*&#39;</code> characters, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p>\n\n<p>Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;*&quot;\n<strong>Output:</strong> 9\n<strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, or &quot;9&quot;.\nEach of these can be decoded to the strings &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;, and &quot;I&quot; respectively.\nHence, there are a total of 9 ways to decode &quot;*&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;1*&quot;\n<strong>Output:</strong> 18\n<strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, or &quot;19&quot;.\nEach of these encoded messages have 2 ways to be decoded (e.g. &quot;11&quot; can be decoded to &quot;AA&quot; or &quot;K&quot;).\nHence, there are a total of 9 * 2 = 18 ways to decode &quot;1*&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;2*&quot;\n<strong>Output:</strong> 15\n<strong>Explanation:</strong> The encoded message can represent any of the encoded messages &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot;, or &quot;29&quot;.\n&quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, and &quot;26&quot; have 2 ways of being decoded, but &quot;27&quot;, &quot;28&quot;, and &quot;29&quot; only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode &quot;2*&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is a digit or <code>&#39;*&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/decode-ways-ii/solutions/",
    "solution": "[TOC]\n\n\n## Solution\n\n---\n### Approach 1: Recursion with Memoization\n\n**Algorithm**\n\nIn order to find the solution to the given problem, we need to consider every case possible(for the arrangement of the input digits/characters)\n and what value needs to be considered for each case. Let's look at each of the possibilites one by one.\n \nFirstly, let's assume, we have a function `ways(s,i)` which returns the number of ways to decode the input string $$s$$, if only the characters up to the \n$$i^{th}$$ index in this string are considered. We start off by calling the function `ways(s, s.length()-1)` i.e. by considering the full length of this string $$s$$.\n\nWe started by using the last index of the string $$s$$. Suppose, currently, we called the function as `ways(s,i)`. Let's look at how we proceed. At every step, we need \nto look at the current character at the last index ($$i$$) and we need to determine the number of ways of decoding that using this $$i^{th}$$ character could \nadd to the total value. There are the following possiblities for the $$i^{th}$$ character.\n\nThe $$i^{th}$$ character could be  a `*`. In this case, firstly, we can see that this `*` could be decoded into any of the digits from `1-9`. Thus, for every decoding possible \nup to the index $$i-1$$, this `*` could be replaced by any of these digits(`1-9`). Thus, the total number of decodings is 9 times the number of decodings possible \nfor the same string up to the index $$i-1$$. Thus, this `*` initially adds a factor of `9*ways(s,i-1)` to the total value. \n\n![Decode_Ways](../Figures/639/639_Decode_Ways2.png)\n\n\nApart from this, this `*` at the $$i^{th}$$ index could also contribute further to the total number of ways depending upon the character/digit at its preceding\n index. If the preceding character happens to be a `1`, by combining this `1` with the current `*`, we could obtain any of the digits from `11-19` which could be decoded\n into any of the characters from `K-S`. We need to note that these decodings are in addition to the ones already obtained above by considering only a single current \n `*`(`1-9` decoding to `A-J`). Thus, this `1*` pair could be replaced by any of the numbers from `11-19` irrespective of the decodings done for the previous \n indices(before $$i-1$$). Thus, this `1*` pair leads to 9 times the number of decodings possible with the string $$s$$ up to the index $$i-2$$. Thus, this adds\n a factor of `9 * ways(s, i - 2)` to the total number of decodings. \n \n Similarly, a `2*` pair obtained by a `2` at the index $$i-1$$ could be considered of the numbers from `21-26`(decoding into `U-Z`), adding a total of 6 times the \n number of decodings possible up to the index $$i-2$$. \n \n \n ![Decode_Ways](../Figures/639/639_Decode_Ways3.PNG)\n\n\nOn the same basis, if the character at the index $$i-1$$ happens to be another `*`, this `**` pairing could be considered as \n any of the numbers from `11-19`(9) and `21-26`(6). Thus, the total number of decodings will be 15(9+6) times  the number of decodings possible up to the index $$i-2$$.\n \n Now, if the $$i^{th}$$ character could be a digit from `1-9` as well. In this case, the number of decodings that considering this single digit can \n contribute to the total number is equal to the number of decodings that can be contributed by the digits up to the index $$i-1$$. But, if the $$i^{th}$$ character is  \n a `0`, this `0` alone can't contribute anything to the total number of decodings(but it can only contribute if the digit preceding it is a `1` or `2`. We'll consider this case below).\n \n Apart from the value obtained(just above) for the digit at the $$i^{th}$$ index being anyone from `0-9`, this digit could also pair with the digit at the \n preceding index, contributing a value dependent on the previous digit. If the previous digit happens to be a `1`, this `1` can combine with any of the current \ndigits forming a valid number in the range `10-19`. Thus, in this case, we can consider a pair formed by the current and the preceding digit, and, the number of \ndecodings possible by considering the decoded character to be a one formed using this pair, is equal to the total number of decodings possible by using the digits \nup to the index $$i-2$$ only. \n\nBut, if the previous digit is a `2`, a valid number for decoding could only be a one from the range `20-26`. Thus, if the current digit is lesser than 7, again\nthis pairing could add decodings with count equal to the ones possible by using the digits up to the $$(i-2)^{th}$$ index only.\n\nFurther, if the previous digit happens to be a `*`, the additional number of decodings depend on the current digit again i.e. If the current digit is greater than \n`6`, this `*` could lead to pairings only in the range `17-19`(`*` can't be replaced by `2` leading to `27-29`). Thus, additional decodings with count equal to the\ndecodings possible up to the index $$i-2$$. \n\nOn the other hand, if the current digit is lesser than 7, this `*` could be replaced by either a `1` or a `2` leading to the \ndecodings `10-16` and `20-26` respectively. Thus, the total number of decodings possible by considering this pair is equal to twice the number of decodings possible up to the \nindex $$i-2$$(since `*` can now be replaced by two values).\n\nThis way, by considering every possible case, we can obtain the required number of decodings by making use of the recursive function `ways` as and where necessary.\n\nBy making use of memoization, we can reduce the time complexity owing to duplicate function calls.\n\n<iframe src=\"https://leetcode.com/playground/kKGPifS6/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"kKGPifS6\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Size of recursion tree can go up to $$n$$, since $$memo$$ array is filled exactly once. Here, $$n$$ refers to the length of the input \nstring.\n\n* Space complexity : $$O(n)$$. The depth of recursion tree can go up to $$n$$.\n<br />\n<br />\n\n---\n\n### Approach 2: Dynamic Programming\n\n**Algorithm**\n\nFrom the solutions discussed above, we can observe that the number of decodings possible up to any index, $$i$$, is dependent only on the characters up to the \nindex $$i$$ and not on any of the characters following it. This leads us to the idea that this problem can be solved by making use of Dynamic Programming.\n\nWe can also easily observe from the recursive solution that, the number of decodings possible up to the index $$i$$ can be determined easily if we know \nthe number of decodings possible up to the index $$i-1$$ and $$i-2$$. Thus, we fill in the $$dp$$ array in a forward manner. $$dp[i]$$ is used to store the \nnumber of decodings possible by considering the characters in the given string $$s$$ up to the $$(i-1)^{th}$$ index only(including it).\n\nThe equations for filling this $$dp$$ at any step again depend on the current character and the just preceding character. These equations are similar \nto the ones used in the recursive solution.\n\nThe following animation illustrates the process of filling the $$dp$$ for a simple example.\n\n\n!?!../Documents/639_Decode_Ways_II.json:1000,563!?!\n\n<iframe src=\"https://leetcode.com/playground/54Dnrv9F/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"54Dnrv9F\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. $$dp$$ array of size $$n+1$$ is filled once only. Here, $$n$$ refers to the length of the input string.\n\n* Space complexity : $$O(n)$$. $$dp$$ array of size $$n+1$$ is used.\n<br />\n<br />\n\n---\n\n### Approach 3: Constant Space Dynamic Programming\n\n**Algorithm**\n\nIn the last approach, we can observe that only the last two values $$dp[i-2]$$ and $$dp[i-1]$$ are used to fill the entry at $$dp[i-1]$$. We can save some \nspace in the last approach, if instead of maintaining a whole $$dp$$ array of length $$n$$, we keep a track of only the required last two values. The rest of the \nprocess remains the same as in the last approach.\n\n<iframe src=\"https://leetcode.com/playground/hwsVsuZK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"hwsVsuZK\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Single loop up to $$n$$ is required to find the required result. Here, $$n$$ refers to the length of the input string $$s$$.\n\n* Space complexity : $$O(1)$$. Constant space is used.",
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int numDecodings(string s) {\n    constexpr int kMod = 1'000'000'007;\n    const int n = s.length();\n    long prev2 = 1;\n    long prev1 = count(s[n - 1]);\n\n    for (int i = n - 2; i >= 0; --i) {\n      long dp = count(s[i], s[i + 1]) * prev2 + count(s[i]) * prev1;\n      dp %= kMod;\n      prev2 = prev1;\n      prev1 = dp;\n    }\n\n    return prev1;\n  }\n\n private:\n  int count(char c) {\n    if (c == '*')\n      return 9;\n    return c != '0';\n  }\n\n  int count(char c1, char c2) {\n    if (c1 == '*' && c2 == '*')  // C1c2: [11-19, 21-26]\n      return 15;\n    if (c1 == '*') {\n      if ('0' <= c2 && c2 <= '6')  // C1: [1-2]\n        return 2;\n      else  // C1: [1]\n        return 1;\n    }\n    if (c2 == '*') {\n      if (c1 == '1')  // C2: [1-9]\n        return 9;\n      if (c1 == '2')  // C2: [1-6]\n        return 6;\n      return 0;\n    }\n    return c1 == '1' || (c1 == '2' && c2 <= '6');\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numDecodings(String s) {\n    final int kMod = 1_000_000_007;\n    final int n = s.length();\n    // dp[i] := # of ways to decode s[i..n - 1]\n    long[] dp = new long[n + 1];\n    dp[n] = 1;\n    dp[n - 1] = count(s.charAt(n - 1));\n\n    for (int i = n - 2; i >= 0; --i) {\n      dp[i] += count(s.charAt(i), s.charAt(i + 1)) * dp[i + 2];\n      dp[i] += count(s.charAt(i)) * dp[i + 1];\n      dp[i] %= kMod;\n    }\n\n    return (int) dp[0];\n  }\n\n  private int count(char c) {\n    if (c == '*')\n      return 9;\n    return c == '0' ? 0 : 1;\n  }\n\n  private int count(char c1, char c2) {\n    if (c1 == '*' && c2 == '*')\n      return 15; // C1c2: [11-19, 21-26]\n    if (c1 == '*') {\n      if ('0' <= c2 && c2 <= '6')\n        return 2; // C1: [1-2]\n      else\n        return 1; // C1: [1]\n    }\n    if (c2 == '*') {\n      if (c1 == '1')\n        return 9; // C2: [1-9]\n      if (c1 == '2')\n        return 6; // C2: [1-6]\n      return 0;\n    }\n    return (c1 == '1' || (c1 == '2' && c2 <= '6')) ? 1 : 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numDecodings(string s) {\n    constexpr int kMod = 1'000'000'007;\n    const int n = s.length();\n    // dp[i] := # of ways to decode s[i:n]\n    vector<long> dp(n + 1);\n    dp.back() = 1;\n    dp[n - 1] = count(s[n - 1]);\n\n    for (int i = n - 2; i >= 0; --i) {\n      dp[i] += count(s[i], s[i + 1]) * dp[i + 2];\n      dp[i] += count(s[i]) * dp[i + 1];\n      dp[i] %= kMod;\n    }\n\n    return dp[0];\n  }\n\n private:\n  int count(char c) {\n    if (c == '*')\n      return 9;\n    return c != '0';\n  }\n\n  int count(char c1, char c2) {\n    if (c1 == '*' && c2 == '*')  // C1c2: [11-19, 21-26]\n      return 15;\n    if (c1 == '*') {\n      if ('0' <= c2 && c2 <= '6')  // C1: [1-2]\n        return 2;\n      else  // C1: [1]\n        return 1;\n    }\n    if (c2 == '*') {\n      if (c1 == '1')  // C2: [1-9]\n        return 9;\n      if (c1 == '2')  // C2: [1-6]\n        return 6;\n      return 0;\n    }\n    return c1 == '1' || (c1 == '2' && c2 <= '6');\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/639.html",
    "category": "Algorithms",
    "acceptance_rate": 31.147565982851894,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 1616,
    "dislikes": 822,
    "similar_questions": "[{\"title\": \"Decode Ways\", \"titleSlug\": \"decode-ways\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Separate Numbers\", \"titleSlug\": \"number-of-ways-to-separate-numbers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Divide a Long Corridor\", \"titleSlug\": \"number-of-ways-to-divide-a-long-corridor\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"81.7K\", \"totalSubmission\": \"262.3K\", \"totalAcceptedRaw\": 81701, \"totalSubmissionRaw\": 262303, \"acRate\": \"31.1%\"}",
    "title_pt": "Formas de Decodificar II",
    "description_pt": "<p>Uma mensagem contendo letras de <code>A-Z</code> pode ser <strong>codificada</strong> em números usando o seguinte mapeamento:</p>\n\n<pre>\n&#39;A&#39; -&gt; &quot;1&quot;\n&#39;B&#39; -&gt; &quot;2&quot;\n...\n&#39;Z&#39; -&gt; &quot;26&quot;\n</pre>\n\n<p>Para <strong>decodificar</strong> uma mensagem codificada, todos os dígitos devem ser agrupados e então mapeados de volta para letras usando o inverso do mapeamento acima (pode haver várias maneiras). Por exemplo, <code>&quot;11106&quot;</code> pode ser mapeada para:</p>\n\n<ul>\n\t<li><code>&quot;AAJF&quot;</code> com o agrupamento <code>(1 1 10 6)</code></li>\n\t<li><code>&quot;KJF&quot;</code> com o agrupamento <code>(11 10 6)</code></li>\n</ul>\n\n<p>Observe que o agrupamento <code>(1 11 06)</code> é inválido porque <code>&quot;06&quot;</code> não pode ser mapeado para <code>&#39;F&#39;</code> já que <code>&quot;6&quot;</code> é diferente de <code>&quot;06&quot;</code>.</p>\n\n<p><strong>Além disso</strong> ao mapeamento acima, uma mensagem codificada pode conter o caractere <code>&#39;*&#39;</code>, que pode representar qualquer dígito de <code>&#39;1&#39;</code> a <code>&#39;9&#39;</code> (<code>&#39;0&#39;</code> é excluído). Por exemplo, a mensagem codificada <code>&quot;1*&quot;</code> pode representar qualquer uma das mensagens codificadas <code>&quot;11&quot;</code>, <code>&quot;12&quot;</code>, <code>&quot;13&quot;</code>, <code>&quot;14&quot;</code>, <code>&quot;15&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;17&quot;</code>, <code>&quot;18&quot;</code> ou <code>&quot;19&quot;</code>. Decodificar <code>&quot;1*&quot;</code> é equivalente a decodificar <strong>qualquer</strong> uma das mensagens codificadas que ela pode representar.</p>\n\n<p>Dada uma string <code>s</code> consistindo de dígitos e caracteres <code>&#39;*&#39;</code>, retorne <em>o <strong>número</strong> de maneiras de <strong>decodificá-la</strong></em>.</p>\n\n<p>Como a resposta pode ser muito grande, retorne-a <strong>módulo</strong> <code>10<sup>9</sup> + 7</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;*&quot;\n<strong>Saída:</strong> 9\n<strong>Explicação:</strong> A mensagem codificada pode representar qualquer uma das mensagens codificadas &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot; ou &quot;9&quot;.\nCada uma delas pode ser decodificada para as strings &quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot; e &quot;I&quot;, respectivamente.\nAssim, há um total de 9 maneiras de decodificar &quot;*&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;1*&quot;\n<strong>Saída:</strong> 18\n<strong>Explicação:</strong> A mensagem codificada pode representar qualquer uma das mensagens codificadas &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot; ou &quot;19&quot;.\nCada uma dessas mensagens codificadas tem 2 maneiras de ser decodificada (por exemplo, &quot;11&quot; pode ser decodificada como &quot;AA&quot; ou &quot;K&quot;).\nAssim, há um total de 9 * 2 = 18 maneiras de decodificar &quot;1*&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;2*&quot;\n<strong>Saída:</strong> 15\n<strong>Explicação:</strong> A mensagem codificada pode representar qualquer uma das mensagens codificadas &quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot;, &quot;26&quot;, &quot;27&quot;, &quot;28&quot; ou &quot;29&quot;.\n&quot;21&quot;, &quot;22&quot;, &quot;23&quot;, &quot;24&quot;, &quot;25&quot; e &quot;26&quot; têm 2 maneiras de serem decodificadas, mas &quot;27&quot;, &quot;28&quot; e &quot;29&quot; têm apenas 1 maneira.\nAssim, há um total de (6 * 2) + (3 * 1) = 12 + 3 = 15 maneiras de decodificar &quot;2*&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> é um dígito ou <code>&#39;*&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "640",
    "paidOnly": false,
    "title": "Solve the Equation",
    "titleSlug": "solve-the-equation",
    "url": "https://leetcode.com/problems/solve-the-equation",
    "description_url": "https://leetcode.com/problems/solve-the-equation/description/",
    "description": "<p>Solve a given equation and return the value of <code>&#39;x&#39;</code> in the form of a string <code>&quot;x=#value&quot;</code>. The equation contains only <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code> operation, the variable <code>&#39;x&#39;</code> and its coefficient. You should return <code>&quot;No solution&quot;</code> if there is no solution for the equation, or <code>&quot;Infinite solutions&quot;</code> if there are infinite solutions for the equation.</p>\n\n<p>If there is exactly one solution for the equation, we ensure that the value of <code>&#39;x&#39;</code> is an integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> equation = &quot;x+5-3+x=6+x-2&quot;\n<strong>Output:</strong> &quot;x=2&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> equation = &quot;x=x&quot;\n<strong>Output:</strong> &quot;Infinite solutions&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> equation = &quot;2x=x&quot;\n<strong>Output:</strong> &quot;x=0&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= equation.length &lt;= 1000</code></li>\n\t<li><code>equation</code> has exactly one <code>&#39;=&#39;</code>.</li>\n\t<li><code>equation</code> consists of integers with an absolute value in the range <code>[0, 100]</code> without any leading zeros, and the variable <code>&#39;x&#39;</code>.</li>\n\t<li>The input is generated that if there is a single solution, it will be an integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/solve-the-equation/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1 Partioning Coefficients [Accepted]\n\nIn the current approach, we start by splitting the given $$equation$$ based on `=` sign. This way, we've separated the left and right hand side of this equation. Once this is done, we need to extract the individual elements(i.e. `x`'s and the numbers) from both sides of the equation. To do so, we make use of `breakIt` function, in which we traverse over the given equation(either left hand side or right hand side), and put the separated parts into an array. \n\nNow, the idea is as follows. We treat the given equation as if we're bringing all the `x`'s on the left hand side and all the rest of the numbers on the right hand side as done below for an example.\n\n`x+5-3+x=6+x-2`\n\n`x+x-x=6-2-5+3`\n\nThus, every `x` in the left hand side of the given equation is treated as positive, while that on the right hand side is treated as negative, in the current implementation. \n\nLikewise, every number on the left hand side is treated as negative, while that on the right hand side is treated as positive. Thus, by doing so, we obtain all the `x`'s in the new $$lhs$$ and all the numbers in the new $$rhs$$ of the original equation. \n\nFurther, in case of an `x`, we also need to find its corresponding coefficients in order to evaluate the final effective coefficient of `x` on the left hand side. We also evaluate the final effective number on the right hand side as well.\n\nNow, in case of a unique solution, the ratio of the effective $$rhs$$ and $$lhs$$ gives the required result. In case of infinite solutions, both the effective $$lhs$$ and $$rhs$$ turns out to be zero e.g. `x+1=x+1`. In case of no solution, the coefficient of `x`($$lhs$$) turns out to be zero, but the effective number on the $$rhs$$ is non-zero.\n\n\n<iframe src=\"https://leetcode.com/playground/5qsPscf9/shared\" frameBorder=\"0\" name=\"5qsPscf9\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Generating coefficients and findinn $$lhs$$ and $$rhs$$ will take $$O(n)$$.\n\n* Space complexity : $$O(n)$$. ArrayList $$res$$ size can grow upto $$n$$.\n\n---\n### Approach #2 Using regex for spliting [Accepted]\n\n**Algorithm**\n\nIn the last approach, we made use of a new function `breakIt` to obtain the individual components of either the left hand side or the right hand side. Instead of doing so, we can also make use of splitting based on `+` or `-` sign, to obtain the individual elements. The rest of the process remains the same as in the last approach. \n\nIn order to do the splitting, we make use of an expression derived from regular expressions(regex). Simply speaking, regex is a functionality used to match a target string based on some given criteria. The ?=n quantifier, in regex, matches any string that is followed by a specific string $$n$$. What it's saying is that the captured match must be followed by $$n$$ but the $$n$$ itself isn't captured.\n\nBy making use of this kind of expression in the `split` functionality, we make sure that the partitions are obtained such that the `+` or `-` sign remains along with the parts(numbers or coefficients) even after the splitting.\n\n<iframe src=\"https://leetcode.com/playground/9JbHjYgz/shared\" frameBorder=\"0\" name=\"9JbHjYgz\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n)$$. Generating coefficients and finding $$lhs$$ and $$rhs$$ will take $$O(n)$$.\n\n* Space complexity : $$O(n)$$. ArrayList $$res$$ size can grow upto $$n$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def solveEquation(self, equation: str) -> str:\n    def calculate(s: str) -> tuple:\n      coefficient = 0\n      constant = 0\n      num = 0\n      sign = 1\n\n      for i, c in enumerate(s):\n        if c.isdigit():\n          num = num * 10 + ord(c) - ord('0')\n        elif c in '+-':\n          constant += sign * num\n          sign = 1 if c == '+' else -1\n          num = 0\n        else:\n          if i > 0 and num == 0 and s[i - 1] == '0':\n            continue\n          coefficient += sign if num == 0 else sign * num\n          num = 0\n\n      return coefficient, constant + sign * num\n\n    lhsEquation, rhsEquation = equation.split('=')\n    lhsCoefficient, lhsConstant = calculate(lhsEquation)\n    rhsCoefficient, rhsConstant = calculate(rhsEquation)\n    coefficient = lhsCoefficient - rhsCoefficient\n    constant = rhsConstant - lhsConstant\n\n    if coefficient == 0 and constant == 0:\n      return \"Infinite solutions\"\n    if coefficient == 0 and constant != 0:\n      return \"No solution\"\n    return \"x=\" + str(constant // coefficient)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String solveEquation(String equation) {\n    String[] equations = equation.split(\"=\");\n    int[] lhs = calculate(equations[0]);\n    int[] rhs = calculate(equations[1]);\n    int coefficient = lhs[0] - rhs[0];\n    int constant = rhs[1] - lhs[1];\n\n    if (coefficient == 0 && constant == 0)\n      return \"Infinite solutions\";\n    if (coefficient == 0 && constant != 0)\n      return \"No solution\";\n    return \"x=\" + constant / coefficient;\n  }\n\n  private int[] calculate(final String s) {\n    int coefficient = 0;\n    int constant = 0;\n    int num = 0;\n    int sign = 1;\n\n    for (int i = 0; i < s.length(); ++i) {\n      char c = s.charAt(i);\n      if (Character.isDigit(c))\n        num = num * 10 + (c - '0');\n      else if (c == '+' || c == '-') {\n        constant += sign * num;\n        sign = c == '+' ? 1 : -1;\n        num = 0;\n      } else {\n        if (i > 0 && num == 0 && s.charAt(i - 1) == '0')\n          continue;\n        coefficient += num == 0 ? sign : sign * num;\n        num = 0;\n      }\n    }\n\n    return new int[] {coefficient, constant + sign * num};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string solveEquation(string equation) {\n    const string lhsEquation = equation.substr(0, equation.find('='));\n    const string rhsEquation = equation.substr(equation.find('=') + 1);\n    const auto& [lhsCoefficient, lhsConstant] = calculate(lhsEquation);\n    const auto& [rhsCoefficient, rhsConstant] = calculate(rhsEquation);\n    const int coefficient = lhsCoefficient - rhsCoefficient;\n    const int constant = rhsConstant - lhsConstant;\n\n    if (coefficient == 0 && constant == 0)\n      return \"Infinite solutions\";\n    if (coefficient == 0 && constant != 0)\n      return \"No solution\";\n    return \"x=\" + to_string(constant / coefficient);\n  }\n\n private:\n  pair<int, int> calculate(const string& s) {\n    int coefficient = 0;\n    int constant = 0;\n    int num = 0;\n    int sign = 1;\n\n    for (int i = 0; i < s.length(); ++i) {\n      const char c = s[i];\n      if (isdigit(c))\n        num = num * 10 + (c - '0');\n      else if (c == '+' || c == '-') {\n        constant += sign * num;\n        sign = c == '+' ? 1 : -1;\n        num = 0;\n      } else {\n        if (i > 0 && num == 0 && s[i - 1] == '0')\n          continue;\n        coefficient += num == 0 ? sign : sign * num;\n        num = 0;\n      }\n    }\n\n    return {coefficient, constant + sign * num};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/640.html",
    "category": "Algorithms",
    "acceptance_rate": 44.48125719433462,
    "topics": [
      "Math",
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 525,
    "dislikes": 845,
    "similar_questions": "[{\"title\": \"Fraction Addition and Subtraction\", \"titleSlug\": \"fraction-addition-and-subtraction\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimize Result by Adding Parentheses to Expression\", \"titleSlug\": \"minimize-result-by-adding-parentheses-to-expression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"44.4K\", \"totalSubmission\": \"99.9K\", \"totalAcceptedRaw\": 44439, \"totalSubmissionRaw\": 99905, \"acRate\": \"44.5%\"}",
    "title_pt": "Resolver a Equação",
    "description_pt": "<p>Resolva uma equação dada e retorne o valor de <code>&#39;x&#39;</code> na forma de uma string <code>&quot;x=#value&quot;</code>. A equação contém apenas a operação <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, a variável <code>&#39;x&#39;</code> e seu coeficiente. Você deve retornar <code>&quot;No solution&quot;</code> se não houver solução para a equação, ou <code>&quot;Infinite solutions&quot;</code> se houver infinitas soluções.</p>\n\n<p>Se houver exatamente uma solução para a equação, garantimos que o valor de <code>&#39;x&#39;</code> é um inteiro.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equation = &quot;x+5-3+x=6+x-2&quot;\n<strong>Saída:</strong> &quot;x=2&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equation = &quot;x=x&quot;\n<strong>Saída:</strong> &quot;Infinite solutions&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> equation = &quot;2x=x&quot;\n<strong>Saída:</strong> &quot;x=0&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>3 &lt;= equation.length &lt;= 1000</code></li>\n\t<li><code>equation</code> possui exatamente um <code>&#39;=&#39;</code>.</li>\n\t<li><code>equation</code> consiste em inteiros com valor absoluto no intervalo <code>[0, 100]</code> sem zeros à esquerda, e a variável <code>&#39;x&#39;</code>.</li>\n\t<li>O input é gerado de forma que, se houver uma solução única, ela será um inteiro.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "641",
    "paidOnly": false,
    "title": "Design Circular Deque",
    "titleSlug": "design-circular-deque",
    "url": "https://leetcode.com/problems/design-circular-deque",
    "description_url": "https://leetcode.com/problems/design-circular-deque/description/",
    "description": "<p>Design your implementation of the circular double-ended queue (deque).</p>\n\n<p>Implement the <code>MyCircularDeque</code> class:</p>\n\n<ul>\n\t<li><code>MyCircularDeque(int k)</code> Initializes the deque with a maximum size of <code>k</code>.</li>\n\t<li><code>boolean insertFront()</code> Adds an item at the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li>\n\t<li><code>boolean insertLast()</code> Adds an item at the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li>\n\t<li><code>boolean deleteFront()</code> Deletes an item from the front of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li>\n\t<li><code>boolean deleteLast()</code> Deletes an item from the rear of Deque. Returns <code>true</code> if the operation is successful, or <code>false</code> otherwise.</li>\n\t<li><code>int getFront()</code> Returns the front item from the Deque. Returns <code>-1</code> if the deque is empty.</li>\n\t<li><code>int getRear()</code> Returns the last item from Deque. Returns <code>-1</code> if the deque is empty.</li>\n\t<li><code>boolean isEmpty()</code> Returns <code>true</code> if the deque is empty, or <code>false</code> otherwise.</li>\n\t<li><code>boolean isFull()</code> Returns <code>true</code> if the deque is full, or <code>false</code> otherwise.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\n<strong>Output</strong>\n[null, true, true, true, false, 2, true, true, true, 4]\n\n<strong>Explanation</strong>\nMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1);  // return True\nmyCircularDeque.insertLast(2);  // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear();      // return 2\nmyCircularDeque.isFull();       // return True\nmyCircularDeque.deleteLast();   // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront();     // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 1000</code></li>\n\t<li><code>0 &lt;= value &lt;= 1000</code></li>\n\t<li>At most <code>2000</code> calls will be made to <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-circular-deque/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass MyCircularDeque {\n  /** Initialize your data structure here. Set the size of the deque to be k. */\n  public MyCircularDeque(int k) {\n    this.k = k;\n    this.q = new int[k];\n    this.rear = k - 1;\n  }\n\n  /** Adds an item at the front of Deque. Return true if the operation is successful. */\n  public boolean insertFront(int value) {\n    if (isFull())\n      return false;\n\n    front = (--front + k) % k;\n    q[front] = value;\n    ++size;\n    return true;\n  }\n\n  /** Adds an item at the rear of Deque. Return true if the operation is successful. */\n  public boolean insertLast(int value) {\n    if (isFull())\n      return false;\n\n    rear = ++rear % k;\n    q[rear] = value;\n    ++size;\n    return true;\n  }\n\n  /** Deletes an item from the front of Deque. Return true if the operation is successful. */\n  public boolean deleteFront() {\n    if (isEmpty())\n      return false;\n\n    front = ++front % k;\n    --size;\n    return true;\n  }\n\n  /** Deletes an item from the rear of Deque. Return true if the operation is successful. */\n  public boolean deleteLast() {\n    if (isEmpty())\n      return false;\n\n    rear = (--rear + k) % k;\n    --size;\n    return true;\n  }\n\n  /** Get the front item from the deque. */\n  public int getFront() {\n    return isEmpty() ? -1 : q[front];\n  }\n\n  /** Get the last item from the deque. */\n  public int getRear() {\n    return isEmpty() ? -1 : q[rear];\n  }\n\n  /** Checks whether the circular deque is empty or not. */\n  public boolean isEmpty() {\n    return size == 0;\n  }\n\n  /** Checks whether the circular deque is full or not. */\n  public boolean isFull() {\n    return size == k;\n  }\n\n  private final int k;\n  private int[] q;\n  private int size = 0;\n  private int front = 0;\n  private int rear;\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyCircularDeque {\n public:\n  /** Initialize your data structure here. Set the size of the deque to be k. */\n  MyCircularDeque(int k) : k(k), q(k), rear(k - 1) {}\n\n  /** Adds an item at the front of Deque. Return true if the operation is\n   * successful. */\n  bool insertFront(int value) {\n    if (isFull())\n      return false;\n\n    front = (--front + k) % k;\n    q[front] = value;\n    ++size;\n    return true;\n  }\n\n  /** Adds an item at the rear of Deque. Return true if the operation is\n   * successful. */\n  bool insertLast(int value) {\n    if (isFull())\n      return false;\n\n    rear = ++rear % k;\n    q[rear] = value;\n    ++size;\n    return true;\n  }\n\n  /** Deletes an item from the front of Deque. Return true if the operation is\n   * successful. */\n  bool deleteFront() {\n    if (isEmpty())\n      return false;\n\n    front = ++front % k;\n    --size;\n    return true;\n  }\n\n  /** Deletes an item from the rear of Deque. Return true if the operation is\n   * successful. */\n  bool deleteLast() {\n    if (isEmpty())\n      return false;\n\n    rear = (--rear + k) % k;\n    --size;\n    return true;\n  }\n\n  /** Get the front item from the deque. */\n  int getFront() {\n    return isEmpty() ? -1 : q[front];\n  }\n\n  /** Get the last item from the deque. */\n  int getRear() {\n    return isEmpty() ? -1 : q[rear];\n  }\n\n  /** Checks whether the circular deque is empty or not. */\n  bool isEmpty() {\n    return size == 0;\n  }\n\n  /** Checks whether the circular deque is full or not. */\n  bool isFull() {\n    return size == k;\n  }\n\n private:\n  const int k;\n  vector<int> q;\n  int size = 0;\n  int front = 0;\n  int rear;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/641.html",
    "category": "Algorithms",
    "acceptance_rate": 64.34436183440211,
    "topics": [
      "Array",
      "Linked List",
      "Design",
      "Queue"
    ],
    "hints": [],
    "likes": 1619,
    "dislikes": 105,
    "similar_questions": "[{\"title\": \"Design Circular Queue\", \"titleSlug\": \"design-circular-queue\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design Front Middle Back Queue\", \"titleSlug\": \"design-front-middle-back-queue\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"177.5K\", \"totalSubmission\": \"275.9K\", \"totalAcceptedRaw\": 177501, \"totalSubmissionRaw\": 275861, \"acRate\": \"64.3%\"}",
    "title_pt": "Projetar Deque Circular",
    "description_pt": "<p>Projete sua implementação da fila dupla circular (deque).</p>\n\n<p>Implemente a classe <code>MyCircularDeque</code>:</p>\n\n<ul>\n\t<li><code>MyCircularDeque(int k)</code> Inicializa o deque com um tamanho máximo de <code>k</code>.</li>\n\t<li><code>boolean insertFront()</code> Adiciona um item na frente do Deque. Retorna <code>true</code> se a operação for bem-sucedida, ou <code>false</code> caso contrário.</li>\n\t<li><code>boolean insertLast()</code> Adiciona um item na traseira do Deque. Retorna <code>true</code> se a operação for bem-sucedida, ou <code>false</code> caso contrário.</li>\n\t<li><code>boolean deleteFront()</code> Remove um item da frente do Deque. Retorna <code>true</code> se a operação for bem-sucedida, ou <code>false</code> caso contrário.</li>\n\t<li><code>boolean deleteLast()</code> Remove um item da traseira do Deque. Retorna <code>true</code> se a operação for bem-sucedida, ou <code>false</code> caso contrário.</li>\n\t<li><code>int getFront()</code> Retorna o item da frente do Deque. Retorna <code>-1</code> se o deque estiver vazio.</li>\n\t<li><code>int getRear()</code> Retorna o último item do Deque. Retorna <code>-1</code> se o deque estiver vazio.</li>\n\t<li><code>boolean isEmpty()</code> Retorna <code>true</code> se o deque estiver vazio, ou <code>false</code> caso contrário.</li>\n\t<li><code>boolean isFull()</code> Retorna <code>true</code> se o deque estiver cheio, ou <code>false</code> caso contrário.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyCircularDeque&quot;, &quot;insertLast&quot;, &quot;insertLast&quot;, &quot;insertFront&quot;, &quot;insertFront&quot;, &quot;getRear&quot;, &quot;isFull&quot;, &quot;deleteLast&quot;, &quot;insertFront&quot;, &quot;getFront&quot;]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\n<strong>Saída</strong>\n[null, true, true, true, false, 2, true, true, true, 4]\n\n<strong>Explicação</strong>\nMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1);  // return True\nmyCircularDeque.insertLast(2);  // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear();      // return 2\nmyCircularDeque.isFull();       // return True\nmyCircularDeque.deleteLast();   // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront();     // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= 1000</code></li>\n\t<li><code>0 &lt;= value &lt;= 1000</code></li>\n\t<li>No máximo <code>2000</code> chamadas serão feitas para <code>insertFront</code>, <code>insertLast</code>, <code>deleteFront</code>, <code>deleteLast</code>, <code>getFront</code>, <code>getRear</code>, <code>isEmpty</code>, <code>isFull</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "643",
    "paidOnly": false,
    "title": "Maximum Average Subarray I",
    "titleSlug": "maximum-average-subarray-i",
    "url": "https://leetcode.com/problems/maximum-average-subarray-i",
    "description_url": "https://leetcode.com/problems/maximum-average-subarray-i/description/",
    "description": "<p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p>\n\n<p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4\n<strong>Output:</strong> 12.75000\n<strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [5], k = 1\n<strong>Output:</strong> 5.00000\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-average-subarray-i/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findMaxAverage(self, nums: List[int], k: int) -> float:\n    summ = sum(nums[:k])\n    ans = summ\n\n    for i in range(k, len(nums)):\n      summ += nums[i] - nums[i - k]\n      ans = max(ans, summ)\n\n    return ans / k",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public double findMaxAverage(int[] nums, int k) {\n    double sum = 0;\n    for (int i = 0; i < k; ++i)\n      sum += nums[i];\n    double ans = sum;\n\n    for (int i = k; i < nums.length; ++i) {\n      sum += nums[i] - nums[i - k];\n      ans = Math.max(ans, sum);\n    }\n\n    return ans / k;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  double findMaxAverage(vector<int>& nums, int k) {\n    double sum = accumulate(begin(nums), begin(nums) + k, 0);\n    double ans = sum;\n\n    for (int i = k; i < nums.size(); ++i) {\n      sum += nums[i] - nums[i - k];\n      ans = max(ans, sum);\n    }\n\n    return ans / k;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/643.html",
    "category": "Algorithms",
    "acceptance_rate": 45.15140745347823,
    "topics": [
      "Array",
      "Sliding Window"
    ],
    "hints": [],
    "likes": 3871,
    "dislikes": 355,
    "similar_questions": "[{\"title\": \"Maximum Average Subarray II\", \"titleSlug\": \"maximum-average-subarray-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"K Radius Subarray Averages\", \"titleSlug\": \"k-radius-subarray-averages\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"813.1K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 813071, \"totalSubmissionRaw\": 1800764, \"acRate\": \"45.2%\"}",
    "title_pt": "Subarray de Média Máxima I",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> consistindo de <code>n</code> elementos, e um inteiro <code>k</code>.</p>\n\n<p>Encontre um subarray contíguo cujo <strong>comprimento seja igual a</strong> <code>k</code> que tenha o valor médio máximo e retorne <em>este valor</em>. Qualquer resposta com um erro de cálculo menor que <code>10<sup>-5</sup></code> será aceita.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,12,-5,-6,50,3], k = 4\n<strong>Saída:</strong> 12.75000\n<strong>Explicação:</strong> A média máxima é (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [5], k = 1\n<strong>Saída:</strong> 5.00000\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "645",
    "paidOnly": false,
    "title": "Set Mismatch",
    "titleSlug": "set-mismatch",
    "url": "https://leetcode.com/problems/set-mismatch",
    "description_url": "https://leetcode.com/problems/set-mismatch/description/",
    "description": "<p>You have a set of integers <code>s</code>, which originally contains all the numbers from <code>1</code> to <code>n</code>. Unfortunately, due to some error, one of the numbers in <code>s</code> got duplicated to another number in the set, which results in <strong>repetition of one</strong> number and <strong>loss of another</strong> number.</p>\n\n<p>You are given an integer array <code>nums</code> representing the data status of this set after the error.</p>\n\n<p>Find the number that occurs twice and the number that is missing and return <em>them in the form of an array</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> nums = [1,2,2,4]\n<strong>Output:</strong> [2,3]\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> nums = [1,1]\n<strong>Output:</strong> [1,2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/set-mismatch/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findErrorNums(self, nums: List[int]) -> List[int]:\n    for num in nums:\n      if nums[abs(num) - 1] < 0:\n        duplicate = abs(num)\n      else:\n        nums[abs(num) - 1] *= -1\n\n    for i, num in enumerate(nums):\n      if num > 0:\n        return [duplicate, i + 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] findErrorNums(int[] nums) {\n    int duplicate = 0;\n\n    for (final int num : nums) {\n      if (nums[Math.abs(num) - 1] < 0)\n        duplicate = Math.abs(num);\n      else\n        nums[Math.abs(num) - 1] *= -1;\n    }\n\n    for (int i = 0; i < nums.length; ++i)\n      if (nums[i] > 0)\n        return new int[] {duplicate, i + 1};\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findErrorNums(vector<int>& nums) {\n    int duplicate;\n\n    for (const int num : nums)\n      if (nums[abs(num) - 1] < 0)\n        duplicate = abs(num);\n      else\n        nums[abs(num) - 1] *= -1;\n\n    for (int i = 0; i < nums.size(); ++i)\n      if (nums[i] > 0)\n        return {duplicate, i + 1};\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/645.html",
    "category": "Algorithms",
    "acceptance_rate": 44.923103966441026,
    "topics": [
      "Array",
      "Hash Table",
      "Bit Manipulation",
      "Sorting"
    ],
    "hints": [],
    "likes": 4944,
    "dislikes": 1187,
    "similar_questions": "[{\"title\": \"Find the Duplicate Number\", \"titleSlug\": \"find-the-duplicate-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"526.5K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 526456, \"totalSubmissionRaw\": 1171904, \"acRate\": \"44.9%\"}",
    "title_pt": "Descompasso de Conjunto",
    "description_pt": "<p>Você tem um conjunto de inteiros <code>s</code>, que originalmente contém todos os números de <code>1</code> até <code>n</code>. Infelizmente, devido a algum erro, um dos números em <code>s</code> foi duplicado para outro número no conjunto, o que resulta na <strong>repetição de um</strong> número e na <strong>perda de outro</strong> número.</p>\n\n<p>Você recebe um array de inteiros <code>nums</code> representando o estado desses dados desse conjunto após o erro.</p>\n\n<p>Encontre o número que ocorre duas vezes e o número que está faltando e retorne <em>eles na forma de um array</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,2,2,4]\n<strong>Saída:</strong> [2,3]\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> nums = [1,1]\n<strong>Saída:</strong> [1,2]\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>2 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "646",
    "paidOnly": false,
    "title": "Maximum Length of Pair Chain",
    "titleSlug": "maximum-length-of-pair-chain",
    "url": "https://leetcode.com/problems/maximum-length-of-pair-chain",
    "description_url": "https://leetcode.com/problems/maximum-length-of-pair-chain/description/",
    "description": "<p>You are given an array of <code>n</code> pairs <code>pairs</code> where <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> and <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p>\n\n<p>A pair <code>p2 = [c, d]</code> <strong>follows</strong> a pair <code>p1 = [a, b]</code> if <code>b &lt; c</code>. A <strong>chain</strong> of pairs can be formed in this fashion.</p>\n\n<p>Return <em>the length longest chain which can be formed</em>.</p>\n\n<p>You do not need to use up all the given intervals. You can select pairs in any order.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> pairs = [[1,2],[2,3],[3,4]]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The longest chain is [1,2] -&gt; [3,4].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> pairs = [[1,2],[7,8],[4,5]]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest chain is [1,2] -&gt; [4,5] -&gt; [7,8].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == pairs.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-length-of-pair-chain/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLongestChain(self, pairs: List[List[int]]) -> int:\n    ans = 0\n    prevEnd = -math.inf\n\n    for s, e in sorted(pairs, key=lambda x: x[1]):\n      if s > prevEnd:\n        ans += 1\n        prevEnd = e\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nimport java.util.Arrays;\n\nclass Solution {\n  public int findLongestChain(int[][] pairs) {\n    int ans = 0;\n    int prevEnd = Integer.MIN_VALUE;\n\n    Arrays.sort(pairs, (a, b) -> a[1] - b[1]);\n\n    for (int[] pair : pairs)\n      if (pair[0] > prevEnd) {\n        ++ans;\n        prevEnd = pair[1];\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLongestChain(vector<vector<int>>& pairs) {\n    int ans = 0;\n    int prevEnd = INT_MIN;\n\n    sort(begin(pairs), end(pairs),\n         [](const auto& a, const auto& b) { return a[1] < b[1]; });\n\n    for (const vector<int>& pair : pairs)\n      if (pair[0] > prevEnd) {\n        ++ans;\n        prevEnd = pair[1];\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/646.html",
    "category": "Algorithms",
    "acceptance_rate": 60.76013722612248,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy",
      "Sorting"
    ],
    "hints": [],
    "likes": 4739,
    "dislikes": 135,
    "similar_questions": "[{\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Non-decreasing Subsequences\", \"titleSlug\": \"non-decreasing-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Non-decreasing Subarray From Two Arrays\", \"titleSlug\": \"longest-non-decreasing-subarray-from-two-arrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"274.9K\", \"totalSubmission\": \"452.4K\", \"totalAcceptedRaw\": 274874, \"totalSubmissionRaw\": 452392, \"acRate\": \"60.8%\"}",
    "title_pt": "Comprimento Máximo de uma Cadeia de Pares",
    "description_pt": "<p>Você recebe um array de <code>n</code> pares <code>pairs</code>, em que <code>pairs[i] = [left<sub>i</sub>, right<sub>i</sub>]</code> e <code>left<sub>i</sub> &lt; right<sub>i</sub></code>.</p>\n\n<p>Um par <code>p2 = [c, d]</code> <strong>segue</strong> um par <code>p1 = [a, b]</code> se <code>b &lt; c</code>. Uma <strong>cadeia</strong> de pares pode ser formada dessa maneira.</p>\n\n<p>Retorne <em>o comprimento da cadeia mais longa que pode ser formada</em>.</p>\n\n<p>Você não precisa usar todos os intervalos dados. Você pode selecionar pares em qualquer ordem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> pairs = [[1,2],[2,3],[3,4]]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A cadeia mais longa é [1,2] -&gt; [3,4].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> pairs = [[1,2],[7,8],[4,5]]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A cadeia mais longa é [1,2] -&gt; [4,5] -&gt; [7,8].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == pairs.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>-1000 &lt;= left<sub>i</sub> &lt; right<sub>i</sub> &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "647",
    "paidOnly": false,
    "title": "Palindromic Substrings",
    "titleSlug": "palindromic-substrings",
    "url": "https://leetcode.com/problems/palindromic-substrings",
    "description_url": "https://leetcode.com/problems/palindromic-substrings/description/",
    "description": "<p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p>\n\n<p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p>\n\n<p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abc&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aaa&quot;\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/palindromic-substrings/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countSubstrings(self, s: str) -> int:\n    def extendPalindromes(l: int, r: int) -> int:\n      count = 0\n\n      while l >= 0 and r < len(s) and s[l] == s[r]:\n        count += 1\n        l -= 1\n        r += 1\n\n      return count\n\n    ans = 0\n\n    for i in range(len(s)):\n      ans += extendPalindromes(i, i)\n      ans += extendPalindromes(i, i + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countSubstrings(String s) {\n    int ans = 0;\n\n    for (int i = 0; i < s.length(); ++i) {\n      ans += extendPalindromes(s, i, i);\n      ans += extendPalindromes(s, i, i + 1);\n    }\n\n    return ans;\n  }\n\n  private int extendPalindromes(final String s, int l, int r) {\n    int count = 0;\n\n    while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {\n      ++count;\n      --l;\n      ++r;\n    }\n\n    return count;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countSubstrings(string s) {\n    int ans = 0;\n\n    for (int i = 0; i < s.length(); ++i) {\n      ans += extendPalindromes(s, i, i);\n      ans += extendPalindromes(s, i, i + 1);\n    }\n\n    return ans;\n  }\n\n private:\n  int extendPalindromes(const string& s, int l, int r) {\n    int count = 0;\n\n    while (l >= 0 && r < s.length() && s[l] == s[r]) {\n      ++count;\n      --l;\n      ++r;\n    }\n\n    return count;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/647.html",
    "category": "Algorithms",
    "acceptance_rate": 71.53886696255766,
    "topics": [
      "Two Pointers",
      "String",
      "Dynamic Programming"
    ],
    "hints": [
      "How can we reuse a previously computed palindrome to compute a larger palindrome?",
      "If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome?",
      "Complexity based hint:</br>\r\nIf we use brute force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation?"
    ],
    "likes": 11104,
    "dislikes": 245,
    "similar_questions": "[{\"title\": \"Longest Palindromic Substring\", \"titleSlug\": \"longest-palindromic-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Palindromic Subsequence\", \"titleSlug\": \"longest-palindromic-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"989.5K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 989501, \"totalSubmissionRaw\": 1383166, \"acRate\": \"71.5%\"}",
    "title_pt": "Substrings Palindrômicas",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne <em>o número de <strong>substrings palindrômicas</strong> nela</em>.</p>\n\n<p>Uma string é um <strong>palíndromo</strong> quando pode ser lida da mesma forma de trás para frente e de frente para trás.</p>\n\n<p>Uma <strong>substring</strong> é uma sequência contígua de caracteres dentro da string.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abc&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Três strings palindrômicas: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aaa&quot;\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Seis strings palindrômicas: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 1000</code></li>\n\t<li><code>s</code> consiste em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Como podemos reutilizar um palíndromo previamente calculado para calcular um palíndromo maior?",
      "- Dica 2: Se “aba” é um palíndromo, “xabax” também é um palíndromo? Da mesma forma, “xabay” é um palíndromo?",
      "- Dica 3: Dica baseada em complexidade:</br>\r\nSe usarmos força bruta e verificarmos se, para cada posição inicial e final, uma substring é um palíndromo, teremos O(n^2) pares início-fim e O(n) verificações de palíndromo. Podemos reduzir o tempo das verificações de palíndromo para O(1) reutilizando algum cálculo anterior?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "648",
    "paidOnly": false,
    "title": "Replace Words",
    "titleSlug": "replace-words",
    "url": "https://leetcode.com/problems/replace-words",
    "description_url": "https://leetcode.com/problems/replace-words/description/",
    "description": "<p>In English, we have a concept called <strong>root</strong>, which can be followed by some other word to form another longer word - let&#39;s call this word <strong>derivative</strong>. For example, when the <strong>root</strong> <code>&quot;help&quot;</code> is followed by the word <code>&quot;ful&quot;</code>, we can form a derivative <code>&quot;helpful&quot;</code>.</p>\n\n<p>Given a <code>dictionary</code> consisting of many <strong>roots</strong> and a <code>sentence</code> consisting of words separated by spaces, replace all the derivatives in the sentence with the <strong>root</strong> forming it. If a derivative can be replaced by more than one <strong>root</strong>, replace it with the <strong>root</strong> that has <strong>the shortest length</strong>.</p>\n\n<p>Return <em>the <code>sentence</code></em> after the replacement.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot;\n<strong>Output:</strong> &quot;the cat was rat by the bat&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot;\n<strong>Output:</strong> &quot;a a b c&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li>\n\t<li><code>dictionary[i]</code> consists of only lower-case letters.</li>\n\t<li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li>\n\t<li><code>sentence</code> consists of only lower-case letters and spaces.</li>\n\t<li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li>\n\t<li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li>\n\t<li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li>\n\t<li><code>sentence</code> does not have leading or trailing spaces.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/replace-words/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Hash Set\n\n#### Intuition\n\nA brute force approach of searching the entire dictionary for every possible root of every word in the sentence would be inefficient. Instead, we can preprocess the dictionary by creating a hash set, `dictSet`, containing all the words from the dictionary. The `dictSet` will allow us to check if a word has a root in the dictionary in constant time.\n\nFor a word in the sentence, its root will be found at the beginning of the word. This means that a word's root is a prefix of the word. The possible prefixes for a word are the set of substrings that start at the beginning of the word and end at any index of the word. For example, the prefixes for \"cat\" are \"c\", \"ca\", and \"cat\".\n\nTo solve the problem, we break it down into two sub-problems:\n\n1. Finding the shortest root in the `dictSet` that matches a prefix of a given word.\n\n2. Replacing the word with its shortest root.\n\nWe can create a helper function, `shortestRoot`, to solve the first subproblem. For each word in the sentence, we check if the `dictSet` contains any words that qualify as roots for the word. If any of the prefixes of the word matches a root word, we return the shortest one. If not, we return the full word.\n\nBelow is an image showing the process for finding the shortest root:\n\n![Shortest Root A](../Figures/648/shortest_rootA.png)\n\nBelow is an image showing the process for finding the shortest root when the `word` has no corresponding root:\n\n![Shortest Root B](../Figures/648/shortest_rootB.png)\n\nTo solve the second subproblem, we will create a data structure to store each word from the sentence. Then, we use the `shortestRoot` function to find the corresponding shortest root for each word and replace the word with the root.\n\n#### Algorithm\n\n1. Create a data structure `wordArray` that contains each word from the `sentence`.\n2. Create a hash set `dictSet` containing each word from the dictionary.\n3. Define a helper function `shortestRoot` that finds the shortest corresponding root word in the given dictionary for a given `word`.\n    - For each index of `word`, save the substring of `word` that starts at the beginning of `word` and ends at the index as `root`. If the `dictSet` contains `root`, return `root`.\n    - Return `word` if there is not a corresponding root in the dictionary.\n4. For each index `word` in `wordArray`:\n    - Search for the corresponding shortest root using the helper function and set `wordArray[word]` to the shortest root.\n5. Convert `wordArray` to a string and return.\n\n#### Implementation\n\n**Note:** The C++ implementation uses `istringstream` instead of an array to store the words in the sentence because there is no built-in way to create an array of words from a string by splitting at the spaces. It also uses a string to build the result.\n\n<iframe src=\"https://leetcode.com/playground/cjSqDM4T/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"cjSqDM4T\"></iframe>\n\n#### Complexity Analysis\n\nLet $d$ be the number of words in the dictionary, $s$ be the number of words in the sentence, and $w$ be the average length of each word. \n\n* Time complexity: $O(d \\cdot w + s \\cdot w^2)$\n\n    Creating a set from the dictionary takes $O(d \\cdot w)$. Creating the data structure that stores the words in the sentence takes $O(s \\cdot w)$.\n\n    The loop in the helper function runs once for each letter in the word. Building each substring takes the helper function $O(w)$. Hash set lookups take $O(1)$ in the average case. Therefore, the time complexity of the helper function is $O(w^2)$.\n\n    The main loop calls the helper function once for each word in the sentence, so it takes $O(s \\cdot w^2)$.\n\n    Converting the result to a string takes $O(s \\cdot w)$.\n\n    Therefore, the overall time complexity is $O(d \\cdot w + s \\cdot w^2)$\n\n* Space complexity: $O(d \\cdot w + s \\cdot w)$\n\n    The set that stores the dictionary requires $O(d \\cdot w)$ space. The data structure that stores the words in the sentence uses $O(s \\cdot w)$ space.\n\n---\n\n### Approach 2: Prefix Trie\n\n#### Intuition\n\nIn the above approach, we searched for each prefix of each word separately in the hash set. We created a new substring for each prefix, which is inefficient because each prefix differs from the previous by just one letter.\n\nInstead of using a hashmap to store the dictionary, we can use a Trie, sometimes known as a Prefix Trie.\n\n> A Trie is a tree-based data structure where each node represents a character in a word, and the path from the root to a leaf node represents a complete word. Tries allow for efficient word lookup and prefix matching.\n\nBelow is an image of a Trie storing the dictionary [\"to\", \"too\", \"the\", \"that\", \"toe\", \"theatre\", \"apple\", \"pen\", \"pencil\", \"pineapple\", \"pine\"]:\n\n![Trie](../Figures/648/prefix_trie.png)\n\nIf you are unfamiliar with the Trie data structure, we recommend you read our [Trie Explore Card](https://leetcode.com/explore/learn/card/trie/)\n\nThe Trie is made up of TrieNodes, which each consist of a boolean flag that is set to `true` when the node represents the end of a word and an array with pointers to the child nodes.\n\nSome implementations of Trie use a hashmap to store pointers to the children nodes instead, which uses less space but may take more time. We chose to use an array because we are working with a relatively small set of characters, the lowercase English alphabet.\n\nA Trie has a root and a constructor. Our implementation of Trie uses two additional functions:\n\n1. `insert`, which inserts a word into the Trie.\n\n2. `shortestRoot`, which finds the shortest corresponding root for a given `word`.\n\nWe will focus our discussion on the `shortestRoot` function because it is unique to this problem. This function is similar to searching in a Trie.\n\nThe basic idea is to start at the root and progress to the child node that corresponds to the next character in `word` until we either reach the end of the given `word`, or the current character in the `word` is not in the Trie. In either case, we return `word`.\n\nDuring the search process, the first node with the `isEnd` flag set to `true` is the shortest root. We return the substring of the word that ends after the current index.\n\nThe `replaceWords` function is very similar to the previous approach, except we use our Trie class and its `shortestRoot` function instead of a hash set and a helper function.\n\n#### Algorithm\n\n**A. Implement the `TrieNode` class:**\n\nProperties:\n`isEnd`: A boolean value indicating whether the node marks the end of a word.\n`children`: An array of size 26 (the number of lowercase English letters) to store pointers to child nodes.\n\nConstructor:\nThe constructor initializes `isEnd` to false and all elements in the `children` array to `null`.\n\n**B. Implement the `Trie` class:**\n\nProperties:\n`root`: A `TrieNode` that points to the root of the Trie.\n\nConstructor:\nThe constructor initializes the `root` with a new TrieNode object. The `root` is associated with an empty string.\n\n`insert` function:\nInserts the given `word` in the `Trie`.\n1. Set a TrieNode `current` to `root`.\n2. For each character `c` in the `word`:\n    - If the child node for `c` doesn't exist, create a new TrieNode and insert it into the `children` array.\n    - Move to the child node for `c`.\n3. After processing all the characters, mark `isEnd` as true for the current node.\n\n`shortestRoot` function:\nFinds the shortest corresponding root for a given `word`.\n1. Set a TrieNode `current` to `root`.\n2. For each index in the word:\n    - Set a character `c` to the current character.\n    - If the child node for `c` doesn't exist, return `word`.\n    - Move to the child node for `c`.\n    - If `current` is the end of a word, return the substring of `word` from the start of the word through the current index.\n3. After processing all the characters, return `word` if there is no corresponding root.\n\n**C. Implement the `replaceWords` function:**\n\n1. Create a data structure `wordArray` that contains each word from the `sentence`.\n2. Create a Trie `dictTree` and insert each word from the dictionary.\n3. For each index `word` in `wordArray`:\n    - Search for the corresponding shortest root using `dictTree.shortestRoot` and set `wordArray[word]` to the shortest root.\n4. Convert `wordArray` to a string and return.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/W5cSaBcY/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"W5cSaBcY\"></iframe>\n\n#### Complexity Analysis\n\nLet $d$ be the number of words in the dictionary, $s$ be the number of words in the sentence, and $w$ be the average length of each word. \n\n* Time complexity: $O(d \\cdot w + s \\cdot w)$\n\n    Creating the Trie takes $O(d \\cdot w)$. Creating the data structure that stores the words in the sentence takes $O(s \\cdot w)$.\n\n    The loop in the `shortestRoot` function runs once for each letter in the word. If a corresponding prefix is found, it creates one substring, which takes $O(w)$. Therefore, the time complexity of finding the shortest root is $O(w)$.\n\n    The main loop calls the `shortestRoot` function once for each word in the sentence, so it takes $O(s \\cdot w)$.\n\n    Converting the result to a string takes $O(s \\cdot w)$.\n\n    Therefore, the overall time complexity is $O(d \\cdot w + 2 \\cdot s \\cdot w)$, which we can simplify to $O(d \\cdot w + s \\cdot w)$.\n\n* Space complexity: $O(d \\cdot w + s \\cdot w)$\n\n    The Trie may store up to $O(d \\cdot w)$ nodes, and each node stores an array with $26$ pointers, so the Trie requires $O(d \\cdot w \\cdot 26)$ space. $26$ is a constant factor, so we can simplify this to $O(d \\cdot w)$. The data structure that stores the words in the sentence uses $O(s \\cdot w)$ space.\n\n    > Note: Though the space complexity looks similar to the above approach, this approach will usually require less space because when any words have the same prefix, it stores the prefix only once, while the hash set stores words like \"semicircle\" and \"semitruck\" separately.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self):\n    self.root = {}\n\n  def insert(self, word: str) -> None:\n    node = self.root\n    for c in word:\n      if c not in node:\n        node[c] = {}\n      node = node[c]\n    node['word'] = word\n\n  def search(self, word: str) -> str:\n    node = self.root\n    for c in word:\n      if 'word' in node:\n        return node['word']\n      if c not in node:\n        return word\n      node = node[c]\n    return word\n\n  def replaceWords(self, dict: List[str], sentence: str) -> str:\n    for word in dict:\n      self.insert(word)\n\n    words = sentence.split(' ')\n    return ' '.join([self.search(word) for word in words])",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String replaceWords(List<String> dict, String sentence) {\n    StringBuilder sb = new StringBuilder();\n\n    for (final String word : dict)\n      insert(word);\n\n    final String[] words = sentence.split(\" \");\n    for (final String word : words)\n      sb.append(' ').append(search(word));\n\n    return sb.substring(1).toString();\n  }\n\n  private class TrieNode {\n    private TrieNode[] children = new TrieNode[26];\n    private String word;\n  }\n\n  private TrieNode root = new TrieNode();\n\n  private void insert(final String word) {\n    TrieNode node = root;\n    for (char c : word.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n    }\n    node.word = word;\n  }\n\n  private String search(final String word) {\n    TrieNode node = root;\n    for (char c : word.toCharArray()) {\n      if (node.word != null)\n        return node.word;\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        return word;\n      node = node.children[i];\n    }\n    return word;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  const string* word = nullptr;\n  TrieNode() : children(26) {}\n};\n\nclass Solution {\n public:\n  string replaceWords(vector<string>& dict, string sentence) {\n    for (const string& word : dict)\n      insert(word);\n\n    string ans;\n    istringstream iss(sentence);\n\n    for (string s; iss >> s;)\n      ans += search(s) + ' ';\n    ans.pop_back();\n\n    return ans;\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n\n  void insert(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n    }\n    node->word = &word;\n  }\n\n  string search(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      if (node->word)\n        return *node->word;\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        return word;\n      node = node->children[i];\n    }\n    return word;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/648.html",
    "category": "Algorithms",
    "acceptance_rate": 68.33703648273718,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Trie"
    ],
    "hints": [],
    "likes": 3028,
    "dislikes": 218,
    "similar_questions": "[{\"title\": \"Implement Trie (Prefix Tree)\", \"titleSlug\": \"implement-trie-prefix-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"296.8K\", \"totalSubmission\": \"434.3K\", \"totalAcceptedRaw\": 296798, \"totalSubmissionRaw\": 434315, \"acRate\": \"68.3%\"}",
    "title_pt": "Substituir Palavras",
    "description_pt": "<p>Em inglês, temos um conceito chamado <strong>raiz</strong>, que pode ser seguido por alguma outra palavra para formar uma outra palavra mais longa - vamos chamar essa palavra de <strong>derivada</strong>. Por exemplo, quando a <strong>raiz</strong> <code>&quot;help&quot;</code> é seguida pela palavra <code>&quot;ful&quot;</code>, podemos formar a derivada <code>&quot;helpful&quot;</code>.</p>\n\n<p>Dado um <code>dictionary</code> consistindo de muitas <strong>raízes</strong> e uma <code>sentence</code> consistindo de palavras separadas por espaços, substitua todas as derivadas na <code>sentence</code> pela <strong>raiz</strong> que as forma. Se uma derivada puder ser substituída por mais de uma <strong>raiz</strong>, substitua-a pela <strong>raiz</strong> que tiver <strong>o menor comprimento</strong>.</p>\n\n<p>Retorne <em>a <code>sentence</code></em> após a substituição.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> dictionary = [&quot;cat&quot;,&quot;bat&quot;,&quot;rat&quot;], sentence = &quot;the cattle was rattled by the battery&quot;\n<strong>Saída:</strong> &quot;the cat was rat by the bat&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> dictionary = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;], sentence = &quot;aadsfasf absbs bbab cadsfafs&quot;\n<strong>Saída:</strong> &quot;a a b c&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= dictionary[i].length &lt;= 100</code></li>\n\t<li><code>dictionary[i]</code> consists of only lower-case letters.</li>\n\t<li><code>1 &lt;= sentence.length &lt;= 10<sup>6</sup></code></li>\n\t<li><code>sentence</code> consists of only lower-case letters and spaces.</li>\n\t<li>The number of words in <code>sentence</code> is in the range <code>[1, 1000]</code></li>\n\t<li>The length of each word in <code>sentence</code> is in the range <code>[1, 1000]</code></li>\n\t<li>Every two consecutive words in <code>sentence</code> will be separated by exactly one space.</li>\n\t<li><code>sentence</code> does not have leading or trailing spaces.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "649",
    "paidOnly": false,
    "title": "Dota2 Senate",
    "titleSlug": "dota2-senate",
    "url": "https://leetcode.com/problems/dota2-senate",
    "description_url": "https://leetcode.com/problems/dota2-senate/description/",
    "description": "<p>In the world of Dota2, there are two parties: the Radiant and the Dire.</p>\n\n<p>The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise <strong>one</strong> of the two rights:</p>\n\n<ul>\n\t<li><strong>Ban one senator&#39;s right:</strong> A senator can make another senator lose all his rights in this and all the following rounds.</li>\n\t<li><strong>Announce the victory:</strong> If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.</li>\n</ul>\n\n<p>Given a string <code>senate</code> representing each senator&#39;s party belonging. The character <code>&#39;R&#39;</code> and <code>&#39;D&#39;</code> represent the Radiant party and the Dire party. Then if there are <code>n</code> senators, the size of the given string will be <code>n</code>.</p>\n\n<p>The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.</p>\n\n<p>Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be <code>&quot;Radiant&quot;</code> or <code>&quot;Dire&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> senate = &quot;RD&quot;\n<strong>Output:</strong> &quot;Radiant&quot;\n<strong>Explanation:</strong> \nThe first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. \nAnd the second senator can&#39;t exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> senate = &quot;RDD&quot;\n<strong>Output:</strong> &quot;Dire&quot;\n<strong>Explanation:</strong> \nThe first senator comes from Radiant and he can just ban the next senator&#39;s right in round 1. \nAnd the second senator can&#39;t exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator&#39;s right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == senate.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/dota2-senate/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string predictPartyVictory(string senate) {\n    const int n = senate.length();\n    queue<int> qR;\n    queue<int> qD;\n\n    for (int i = 0; i < n; ++i)\n      if (senate[i] == 'R')\n        qR.push(i);\n      else\n        qD.push(i);\n\n    while (!qR.empty() && !qD.empty()) {\n      const int indexR = qR.front();\n      qR.pop();\n      const int indexD = qD.front();\n      qD.pop();\n      if (indexR < indexD)\n        qR.push(indexR + n);\n      else\n        qD.push(indexD + n);\n    }\n\n    return qR.empty() ? \"Dire\" : \"Radiant\";\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/649.html",
    "category": "Algorithms",
    "acceptance_rate": 48.77375599600803,
    "topics": [
      "String",
      "Greedy",
      "Queue"
    ],
    "hints": [],
    "likes": 2601,
    "dislikes": 1993,
    "similar_questions": "[{\"title\": \"Teemo Attacking\", \"titleSlug\": \"teemo-attacking\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"227.3K\", \"totalSubmission\": \"465.9K\", \"totalAcceptedRaw\": 227252, \"totalSubmissionRaw\": 465931, \"acRate\": \"48.8%\"}",
    "title_pt": "Senado Dota2",
    "description_pt": "<p>No mundo de Dota2, existem dois partidos: o Radiant e o Dire.</p>\n\n<p>O senado de Dota2 consiste em senadores vindos de dois partidos. Agora o Senado quer decidir sobre uma mudança no jogo Dota2. A votação para essa mudança é um procedimento baseado em rodadas. Em cada rodada, cada senador pode exercer <strong>um</strong> dos dois direitos:</p>\n\n<ul>\n\t<li><strong>Banir o direito de um senador:</strong> Um senador pode fazer com que outro senador perca todos os seus direitos nesta rodada e em todas as rodadas seguintes.</li>\n\t<li><strong>Anunciar a vitória:</strong> Se esse senador descobrir que os senadores que ainda têm direitos de voto são todos do mesmo partido, ele pode anunciar a vitória e decidir a mudança no jogo.</li>\n</ul>\n\n<p>Dada uma string <code>senate</code> representando a filiação partidária de cada senador. O caractere <code>&#39;R&#39;</code> e <code>&#39;D&#39;</code> representam o partido Radiant e o partido Dire. Então, se houver <code>n</code> senadores, o tamanho da string fornecida será <code>n</code>.</p>\n\n<p>O procedimento baseado em rodadas começa do primeiro senador até o último senador na ordem dada. Esse procedimento durará até o fim da votação. Todos os senadores que tiverem perdido seus direitos serão ignorados durante o procedimento.</p>\n\n<p>Suponha que todo senador seja inteligente o suficiente e jogará com a melhor estratégia para o seu próprio partido. Preveja qual partido finalmente anunciará a vitória e mudará o jogo Dota2. A saída deve ser <code>&quot;Radiant&quot;</code> ou <code>&quot;Dire&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> senate = &quot;RD&quot;\n<strong>Saída:</strong> &quot;Radiant&quot;\n<strong>Explicação:</strong> \nO primeiro senador vem do Radiant e ele pode simplesmente banir o direito do próximo senador na rodada 1. \nE o segundo senador não pode mais exercer nenhum direito, já que seu direito foi banido. \nE na rodada 2, o primeiro senador pode simplesmente anunciar a vitória, já que ele é o único senador que pode votar.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> senate = &quot;RDD&quot;\n<strong>Saída:</strong> &quot;Dire&quot;\n<strong>Explicação:</strong> \nO primeiro senador vem do Radiant e ele pode simplesmente banir o direito do próximo senador na rodada 1. \nE o segundo senador não pode mais exercer nenhum direito, já que seu direito foi banido. \nE o terceiro senador vem do Dire e ele pode banir o direito do primeiro senador na rodada 1. \nE na rodada 2, o terceiro senador pode simplesmente anunciar a vitória, já que ele é o único senador que pode votar.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == senate.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>senate[i]</code> is either <code>&#39;R&#39;</code> or <code>&#39;D&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "650",
    "paidOnly": false,
    "title": "2 Keys Keyboard",
    "titleSlug": "2-keys-keyboard",
    "url": "https://leetcode.com/problems/2-keys-keyboard",
    "description_url": "https://leetcode.com/problems/2-keys-keyboard/description/",
    "description": "<p>There is only one character <code>&#39;A&#39;</code> on the screen of a notepad. You can perform one of two operations on this notepad for each step:</p>\n\n<ul>\n\t<li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li>\n\t<li>Paste: You can paste the characters which are copied last time.</li>\n</ul>\n\n<p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>&#39;A&#39;</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Initially, we have one character &#39;A&#39;.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get &#39;AA&#39;.\nIn step 3, we use Paste operation to get &#39;AAA&#39;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/2-keys-keyboard/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nIn the problem, we start with one character `A` on our screen. At each step, we can perform one of two operations available:  \n\n1. Copy All: Copy all the A's currently on the screen.  \n2. Paste: Paste all the A's that were copied in the last Copy All operation.  \n\nGiven an integer `n`, the goal is to determine the minimum number of operations needed to get exactly `n` A's on the screen.  \n\n### Approach 1: Recursion / Backtracking\n\n### Intuition\n\nWhen adding A's on the screen to achieve `n` A's, we note that it is unnecessary to apply consecutive Copy All operations because applying consecutive Copy All operations has the same effect as applying just one. If a Copy All operation is applied, then a Paste operation should be applied right after. Thus, we have two options to add A's on the screen at every step:\n\n1) Apply a Copy All operation first and then apply the Paste operation right after.\n2) Apply a Paste operation.\n\nA brute-force approach involves exploring both ways recursively at each step. This would allow us to find all possible sequences of operations that result in exactly `n` A's, and then choose the sequence that requires the minimum number of operations.  \n\nTo implement this, we define a function $f(i, j)$, which represents the minimum number of operations needed to get to `n` A's starting with $i$ A's, where the previous copy operation had $j$ A's.\n\nWe can break the problem into subproblems based on the two options described above:  \n\n1. **Copy All + Paste**: This option takes 2 operations. It doubles the number of A's to `i * 2`, and updates the previous copy length to `i`. Thus, the number of operations needed for this choice is $2 + f(i * 2, i)$.  \n\n2. **Paste**: This option takes 1 Paste operation. It increases the number of A's by `j` while keeping the previous copy length as `j`. Thus, the number of operations needed for this choice is $1 + f(i + j, j)$.  \n\nBy making recursive calls for these two choices — $2 + f(i * 2, i)$  and $1 + f(i + j, j)$ — our solution can return the minimum value among these options, effectively finding the global minimum number of operations needed to reach `n` A's.  \n\n### Algorithm \n\n1. If `n == 1`, no operations are needed so return `0`.\n2. Define a recursive helper function `minStepsHelper(int currLen, int pasteLen)`:\n    * **Base Case**: If `currLen == n`, then we have reached `n` A's, so return `0`\n    * **Base Case**: If `currLen > n`, then we have exceeded the number of A's needed, so return max value `1000`, ignoring this current sequence\n    * **Try Copy All + Paste**: Initialize `opt1` to `2 + minStepsHelper(currLen * 2, currLen)`, where 2 operations are used, `currLen` is doubled, and `pasteLen` is updated to `currlen`\n    * **Try Paste**: Initialize `opt2` to `1 + minStepsHelper(currLen + pasteLen, pasteLen)`, where 1 operation is used, `currLen` increases by `pasteLen` and `pasteLen` remains the same.\n    * Return the minimum between `opt1` and `opt2`\n3. Return `1 + minStepsHelper(1, 1)`, the minimum number of operations to get to `n` A's from `1` `A`, where `pasteLen` is `1` from performing a Copy All operation first.\n\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/8c53DB9n/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"8c53DB9n\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(2^n)$\n\n    The `minStepsHelper` function is recursively called 2 times at each point. The maximum height of the call stack would be $n$, leading to a total exponential time complexity of $O(2^n)$.\n\n* Space Complexity: $O(n)$\n\n    The space complexity is determined by the call stack, which has a maximum height of $O(n)$.\n\n### Approach 2: Top-Down Dynamic Programming\n\n### Intuition\n\nIn Approach 1, certain subproblems $f(i, j)$ can appear more than once, resulting in duplicate calculations. This issue is illustrated by the recursive call tree for `minStepsHelper`, where duplicate calls are highlighted in red.  \n\n![Recursive tree for minStepsHelper](../Figures/650/minsteps_recursive_tree.png)  \n\nTo optimize this, we can utilize a technique called [memoization](https://leetcode.com/explore/learn/card/recursion-i/255/recursion-memoization/1495/), which stores previously computed results in a cache. With memoization, we can check if an answer to a subproblem has already been computed, and retrieve the answer from our cache to avoid redundant calculations.  \n\nOur cache can be a 2D array `memo`, where `memo[i][j]` stores the answer to subproblem $f(i, j)$. The dimensions of `memo` can be $(n + 1) \\times \\left(\\frac{n}{2} + 1\\right)$, because the current number of characters is at most `n` and the previous copy length is at most $\\frac{n}{2}$.  \n\nBy employing memoization, we eliminate duplicate work and solve each unique subproblem exactly once, improving the efficiency of our solution.\n\n### Algorithm\n\n1. If `n == 1`, no operations are needed so return `0`.\n2. Initialize cache `memo[i][j]` to 2D array with dimensions `(n + 1) x (n / 2 + 1)`.\n3. Define a recursive helper function `minStepsHelper(int currLen, int pasteLen, int[][] memo)`:\n    * **Base Case**: If `currLen == n`, then we have reached `n` A's, so return `0`\n    * **Base Case**: If `currLen > n`, then we have exceeded the number of A's needed, so return max value `1000`, ignoring this current sequence\n    * **Check cache**: If `memo` has the answer to the subproblem, return `memo[currLen][pasteLen]`.\n    * **Solve subproblem**:\n        * **Try Copy All + Paste**: Initialize `opt1` to `2 + minStepsHelper(currLen * 2, currLen)`, where 2 operations are used, `currLen` is doubled, and `pasteLen` is updated to `currlen`\n        * **Try Paste**: Initialize `opt2` to `1 + minStepsHelper(currLen + pasteLen, pasteLen)`, where 1 operation is used, `currLen` increases by `pasteLen` and `pasteLen` remains the same.\n        * Save the minimum between `opt1` and `opt2` in `memo[currLen][pasteLen]` and return it.\n4. Return `1 + minStepsHelper(1, 1, memo)`, the minimum number of operations to get to `n` A's from `1` `A`, where `pasteLen` is `1` due to performing a Copy All operation first.\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/YSMWfomF/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"YSMWfomF\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(n^2)$\n\n    The time complexity is determined by the total number of subproblems solved, which is proportional to the size of the `memo` array: $(n + 1) \\cdot (n / 2 + 1)$. This leads to a time complexity of $O(n^2)$.\n\n* Space Complexity: $O(n^2)$\n\n    The space complexity is determined by the size of the `memo` array, which is $O(n^2)$.\n\n### Approach 3: Bottom-Up Dynamic Programming \n\n### Intuition\n\nAn alternate approach is to solve our subproblems from bottom to top (bottom-up dynamic programming), by working from the base case up to the final answer. We define a new function $f(i)$ to represent the minimum number of operations to get to $i$ A's starting from 1 A. Note that in contrast to Approaches 1 and 2, we do not keep track of the length of the previous copy. This approach focuses on incrementally building up from the base case $f(1) = 0$ to $f(n)$, the final result.\n\nTo do this, we'd like to form a relation between subproblems and express $f(i)$ in terms of $f(j)$ for values of $j$ where $1 \\leq j < i$. \nFor a given subproblem $f(i)$ where there are currently `i` A's, we recognize the last operation must have been a paste. Furthermore, we know that the number of A's previously copied must be a factor of $i$. For example, if we currently have $6$ A's, the previous copy could have been of $1$, $2$, or $3$ A's, which are all the factors of $6$.\n\n![3 Ways To Get To AAAAAA](../Figures/650/Three_ways_getting_AAAAAA.png)\n\n Thus, one possible way to make $i$ A's is to use the Copy All operation on $j$ A's, where $j$ is a factor of $i$. We can then paste the $j$ A's $(i - j)/ j$ times to reach a total of `i` A's. If this approach is chosen, then the minimum number of operations possible would be $f(j) + 1 + (i-j) / j$.  Here, $f(j)$ represents the minimum number of operations to reach $j$ A's, $1$ accounts for the single Copy All operation on the $j$ A's, and $(i-j) / j$ represents the number of additional Paste operations of $j$ A's needed. \n \n We can simplify the expression $f(j) + 1 + (i-j)/j$ to $f(j) + i/j$.\n\nIf we consider all possible factors $j$ of `i`, then we can solve for $f(i)$. Thus, we have the relation:\n\n $f(i) = f(j) + i/j$ for all $j$ such that $i \\mod j == 0$. Note that $j \\leq i/2$ since $i/2$ is the largest factor of $i$. \n\nBy iteratively applying this relation, we can build up to compute $f(n)$, effectively solving the problem from the bottom up.\n \n### Algorithm\n\n1. Initialize an array `dp` of size `n+1` where $dp[i] =  f(i)$, $1 <= i <= n$\n2. Initialize values of `dp` to a default max value of `1000`\n3. Fill in the base case: `dp[1] = 0`\n4. Iterate through values of `i` from `2` to `n`:\n    * Iterate through values of `j` from `1` to `i/2`:\n        * If `i % j == 0`: Set `dp[i]` to minimum between `dp[i]` and `dp[j] + i / j`.\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/QcYr8QWP/shared\" frameBorder=\"0\" width=\"100%\" height=\"412\" name=\"QcYr8QWP\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(n^2)$\n\n    Initializing our `dp` array takes $O(n)$ time. To fill in the `dp` array, the outer and inner loop each run $O(n)$ times, resulting in a total time complexity of $O(n^2)$. \n\n* Space Complexity: $O(n)$\n\n    The space complexity is determined by our `dp` array, which has a size of $O(n)$. \n\n### Approach 4: Prime Factorization\n\n### Intuition\n\n> Note: This approach contains some mathematical notation. We encourage you to read carefully to fully understand the intuition.\n\nIn Approach 3, we recognize that getting to $i$ A's will repeatedly involve a Copy All operation followed by a series of Paste operations. For example, a possible sequence of operations might look like `[CPP][CPPPP][CP]`. In this approach, we will find a way to minimize the length of each block of this sequence. In doing so, we can find the minimum number of operations needed to achieve `n` A's at the end.\n\nTo start, we call the length of the $i-th$ block in this sequence $g_i$. From this setup, We can make two important observations:\n\n1. The total number of operations performed can be expressed as $g_1 + g_2 + ... + g_n$.\n2. After applying $g_1$ operations, we have $g_1$ A's. Then, after applying $g_2$ operations, we have $g_1 \\times g_2$ A's. In general, $g_1 \\times g_2 \\times ... \\times g_n = n$.\n\nThus, to solve the problem, we need to find values for $g_1,g_2, ... , g_n$ so that their sum is minimized while ensuring that their product is equal to `n`.\n\nLet's dive deep on how a certain block's length can be minimized. When examining a block $i$ where its length $g_i$ is composite, (i.e. $g_i = p \\times q$), we can break it down into two smaller blocks of size $p$ and $q$. For example, if our first block is $[CPPPPP]$, where $g_i = 3 \\times 2$, we can break that down into $[CPP][CP]$. This splitting reduces the total number of operations in this example from 6 to 5, while still producing the same number of A's as the original block. \n\nBecause using $p + q$ moves by splitting is never more than using $p \\times q$ moves by not splitting, the optimal strategy involves breaking down each composite $g_i$ into its prime factors. Thus, splitting whenever possible will lead to the minimum number of operations. \n\nThis will lead to each $g_i$ being a prime factor of `n`. This problem then reduces to finding the sum of the prime factors of `n`.\n\n### Algorithm\n\n1. Initialize `ans` to 0, representing the current sum of prime factors\n2. Initialize `d` to 2, the first possible prime factor to consider.\n3. While `n` is not equal to `0`:\n    * **While d is a prime factor:** While `n % d == 0`:\n        * **Divide `n` by the prime factor:** n = n / d\n        * **Add `d` to current sum `ans`:**`ans += d`\n    * **Increment `d` to find the next prime factor:** `d++`\n4. Return `ans`\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/854oRmED/shared\" frameBorder=\"0\" width=\"100%\" height=\"344\" name=\"854oRmED\"></iframe>\n\n### Complexity Analysis\n\n* Time Complexity: $O(\\sqrt{n})$\n\n    The outer `while` loop runs until `n` becomes 1. The inner `while` loop divides `n` by `d` whenever `d` is a divisor of `n`.\n    \n    The factorization of `n` involves checking divisibility from `d = 2` to $d \\leq \\sqrt{n}$. After `d` surpasses $sqrt{n}$, `n` can only have one prime factor greater than $\\sqrt{n}$, which will be handled in one iteration of the outer loop.\n\n    Thus, the complexity is dominated by the number of potential divisors up to $\\sqrt{n}$, leading to a time complexity of $O(\\sqrt{n})$.\n\n* Space Complexity: $O(1)$\n\n    Our iterative algorithm has no recursive overhead and no auxiliary data structures. Thus, the space complexity is $O(1)$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minSteps(self, n: int) -> int:\n    if n <= 1:\n      return 0\n\n    # dp[i] := min steps to get i 'A'\n    # Copy 'A', then paste 'A' i - 1 times\n    dp = [i for i in range(n + 1)]\n\n    for i in range(2, n + 1):\n      for j in range(i // 2, 2, -1):\n        if i % j == 0:\n          dp[i] = dp[j] + i // j  # Paste dp[j] i / j times\n          break\n\n    return dp[n]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minSteps(int n) {\n    // dp[i] := min steps to get i 'A'\n    int[] dp = new int[n + 1];\n\n    for (int i = 2; i <= n; ++i) {\n      dp[i] = i; // Copy 'A', then paste 'A' i - 1 times\n      for (int j = i / 2; j > 2; --j)\n        if (i % j == 0) {\n          dp[i] = dp[j] + i / j; // Paste dp[j] i / j times\n          break;\n        }\n    }\n\n    return dp[n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minSteps(int n) {\n    if (n <= 1)\n      return 0;\n\n    // dp[i] := min steps to get i 'A'\n    vector<int> dp(n + 1);\n\n    // Copy 'A', then paste 'A' i - 1 times\n    iota(begin(dp), end(dp), 0);\n\n    for (int i = 2; i <= n; ++i)\n      for (int j = i / 2; j > 2; --j)\n        if (i % j == 0) {\n          dp[i] = dp[j] + i / j;  // Paste dp[j] i / j times\n          break;\n        }\n\n    return dp[n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/650.html",
    "category": "Algorithms",
    "acceptance_rate": 59.05780376468175,
    "topics": [
      "Math",
      "Dynamic Programming"
    ],
    "hints": [
      "How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?"
    ],
    "likes": 4287,
    "dislikes": 245,
    "similar_questions": "[{\"title\": \"4 Keys Keyboard\", \"titleSlug\": \"4-keys-keyboard\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Broken Calculator\", \"titleSlug\": \"broken-calculator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Value After Replacing With Sum of Prime Factors\", \"titleSlug\": \"smallest-value-after-replacing-with-sum-of-prime-factors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Distinct Prime Factors of Product of Array\", \"titleSlug\": \"distinct-prime-factors-of-product-of-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"276.3K\", \"totalSubmission\": \"467.9K\", \"totalAcceptedRaw\": 276347, \"totalSubmissionRaw\": 467927, \"acRate\": \"59.1%\"}",
    "title_pt": "Teclado de 2 Teclas",
    "description_pt": "<p>Há apenas um caractere <code>&#39;A&#39;</code> na tela de um bloco de notas. Você pode realizar uma das duas operações neste bloco de notas a cada passo:</p>\n\n<ul>\n\t<li>Copiar Tudo: Você pode copiar todos os caracteres presentes na tela (não é permitida uma cópia parcial).</li>\n\t<li>Colar: Você pode colar os caracteres que foram copiados da última vez.</li>\n</ul>\n\n<p>Dado um inteiro <code>n</code>, retorne <em>o número mínimo de operações para obter o caractere</em> <code>&#39;A&#39;</code> <em>exatamente</em> <code>n</code> <em>vezes na tela</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Inicialmente, temos um caractere &#39;A&#39;.\nNo passo 1, usamos a operação Copiar Tudo.\nNo passo 2, usamos a operação Colar para obter &#39;AA&#39;.\nNo passo 3, usamos a operação Colar para obter &#39;AAA&#39;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Quantos caracteres podem estar na área de transferência no último passo se n = 3? n = 7? n = 10? n = 24?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "652",
    "paidOnly": false,
    "title": "Find Duplicate Subtrees",
    "titleSlug": "find-duplicate-subtrees",
    "url": "https://leetcode.com/problems/find-duplicate-subtrees",
    "description_url": "https://leetcode.com/problems/find-duplicate-subtrees/description/",
    "description": "<p>Given the <code>root</code>&nbsp;of a binary tree, return all <strong>duplicate subtrees</strong>.</p>\n\n<p>For each kind of duplicate subtrees, you only need to return the root node of any <b>one</b> of them.</p>\n\n<p>Two trees are <strong>duplicate</strong> if they have the <strong>same structure</strong> with the <strong>same node values</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e1.jpg\" style=\"width: 450px; height: 354px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,4,null,2,4,null,null,4]\n<strong>Output:</strong> [[2,4],[4]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e2.jpg\" style=\"width: 321px; height: 201px;\" />\n<pre>\n<strong>Input:</strong> root = [2,1,1]\n<strong>Output:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e33.jpg\" style=\"width: 450px; height: 303px;\" />\n<pre>\n<strong>Input:</strong> root = [2,2,2,3,null,3,null]\n<strong>Output:</strong> [[2,3],[3]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of the nodes in the tree will be in the range <code>[1, 5000]</code></li>\n\t<li><code>-200 &lt;= Node.val &lt;= 200</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-duplicate-subtrees/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n    ans = []\n    count = Counter()\n\n    def encode(root: Optional[TreeNode]) -> str:\n      if not root:\n        return ''\n\n      encoded = str(root.val) + '#' + \\\n          encode(root.left) + '#' + \\\n          encode(root.right)\n      count[encoded] += 1\n      if count[encoded] == 2:\n        ans.append(root)\n      return encoded\n\n    encode(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<TreeNode> findDuplicateSubtrees(TreeNode root) {\n    List<TreeNode> ans = new ArrayList<>();\n    Map<String, Integer> count = new HashMap<>();\n    encode(root, count, ans);\n    return ans;\n  }\n\n  private String encode(TreeNode root, Map<String, Integer> count, List<TreeNode> ans) {\n    if (root == null)\n      return \"\";\n\n    final String encoded =\n        root.val + \"#\" + encode(root.left, count, ans) + \"#\" + encode(root.right, count, ans);\n    count.merge(encoded, 1, Integer::sum);\n    if (count.get(encoded) == 2)\n      ans.add(root);\n    return encoded;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {\n    vector<TreeNode*> ans;\n    unordered_map<string, int> count;\n    encode(root, count, ans);\n    return ans;\n  }\n\n private:\n  string encode(TreeNode* root, unordered_map<string, int>& count,\n                vector<TreeNode*>& ans) {\n    if (root == nullptr)\n      return \"\";\n\n    const string encoded = to_string(root->val) + \"#\" +\n                           encode(root->left, count, ans) + \"#\" +\n                           encode(root->right, count, ans);\n    if (++count[encoded] == 2)\n      ans.push_back(root);\n    return encoded;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/652.html",
    "category": "Algorithms",
    "acceptance_rate": 60.02196391230123,
    "topics": [
      "Hash Table",
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5977,
    "dislikes": 492,
    "similar_questions": "[{\"title\": \"Serialize and Deserialize Binary Tree\", \"titleSlug\": \"serialize-and-deserialize-binary-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Serialize and Deserialize BST\", \"titleSlug\": \"serialize-and-deserialize-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Construct String from Binary Tree\", \"titleSlug\": \"construct-string-from-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete Duplicate Folders in System\", \"titleSlug\": \"delete-duplicate-folders-in-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"290.8K\", \"totalSubmission\": \"484.4K\", \"totalAcceptedRaw\": 290762, \"totalSubmissionRaw\": 484428, \"acRate\": \"60.0%\"}",
    "title_pt": "Encontrar Subárvores Duplicadas",
    "description_pt": "<p>Dada a <code>root</code>&nbsp;de uma árvore binária, retorne todas as <strong>subárvores duplicadas</strong>.</p>\n\n<p>Para cada tipo de subárvore duplicada, você precisa retornar apenas o nó raiz de qualquer <b>uma</b> delas.</p>\n\n<p>Duas árvores são <strong>duplicadas</strong> se elas têm a <strong>mesma estrutura</strong> com os <strong>mesmos valores de nó</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e1.jpg\" style=\"width: 450px; height: 354px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,4,null,2,4,null,null,4]\n<strong>Saída:</strong> [[2,4],[4]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e2.jpg\" style=\"width: 321px; height: 201px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,1,1]\n<strong>Saída:</strong> [[1]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/08/16/e33.jpg\" style=\"width: 450px; height: 303px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,2,2,3,null,3,null]\n<strong>Saída:</strong> [[2,3],[3]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore estará na faixa de <code>[1, 5000]</code></li>\n\t<li><code>-200 &lt;= Node.val &lt;= 200</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "653",
    "paidOnly": false,
    "title": "Two Sum IV - Input is a BST",
    "titleSlug": "two-sum-iv-input-is-a-bst",
    "url": "https://leetcode.com/problems/two-sum-iv-input-is-a-bst",
    "description_url": "https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/",
    "description": "<p>Given the <code>root</code> of a binary search tree and an integer <code>k</code>, return <code>true</code> <em>if there exist two elements in the BST such that their sum is equal to</em> <code>k</code>, <em>or</em> <code>false</code> <em>otherwise</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg\" style=\"width: 400px; height: 229px;\" />\n<pre>\n<strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg\" style=\"width: 400px; height: 229px;\" />\n<pre>\n<strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li>\n\t<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/two-sum-iv-input-is-a-bst/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass BSTIterator:\n  def __init__(self, root: Optional[TreeNode], leftToRight: bool):\n    self.stack = []\n    self.leftToRight = leftToRight\n    self.pushUntilNone(root)\n\n  def next(self) -> int:\n    node = self.stack.pop()\n    if self.leftToRight:\n      self.pushUntilNone(node.right)\n    else:\n      self.pushUntilNone(node.left)\n    return node.val\n\n  def pushUntilNone(self, root: Optional[TreeNode]):\n    while root:\n      self.stack.append(root)\n      root = root.left if self.leftToRight else root.right\n\n\nclass Solution:\n  def findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n    if not root:\n      return False\n\n    left = BSTIterator(root, True)\n    right = BSTIterator(root, False)\n\n    l = left.next()\n    r = right.next()\n\n    while l < r:\n      summ = l + r\n      if summ == k:\n        return True\n      if summ < k:\n        l = left.next()\n      else:\n        r = right.next()\n\n    return False",
    "solution_code_java": "\t\t\t\n\nclass BSTIterator {\n  public BSTIterator(TreeNode root, boolean leftToRight) {\n    this.leftToRight = leftToRight;\n    pushLeftsUntilNull(root);\n  }\n\n  public int next() {\n    TreeNode root = stack.pop();\n    pushLeftsUntilNull(leftToRight ? root.right : root.left);\n    return root.val;\n  }\n\n  public boolean hasNext() {\n    return !stack.isEmpty();\n  }\n\n  private Deque<TreeNode> stack = new ArrayDeque<>();\n  private boolean leftToRight;\n\n  private void pushLeftsUntilNull(TreeNode root) {\n    while (root != null) {\n      stack.push(root);\n      root = leftToRight ? root.left : root.right;\n    }\n  }\n}\n\nclass Solution {\n  public boolean findTarget(TreeNode root, int k) {\n    if (root == null)\n      return false;\n\n    BSTIterator left = new BSTIterator(root, true);\n    BSTIterator right = new BSTIterator(root, false);\n\n    for (int l = left.next(), r = right.next(); l < r;) {\n      final int sum = l + r;\n      if (sum == k)\n        return true;\n      if (sum < k)\n        l = left.next();\n      else\n        r = right.next();\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass BSTIterator {\n public:\n  BSTIterator(TreeNode* root, bool leftToRight) : leftToRight(leftToRight) {\n    pushUntilNull(root);\n  }\n\n  int next() {\n    TreeNode* root = stack.top();\n    stack.pop();\n    pushUntilNull(leftToRight ? root->right : root->left);\n    return root->val;\n  }\n\n private:\n  stack<TreeNode*> stack;\n  bool leftToRight;\n\n  void pushUntilNull(TreeNode* root) {\n    while (root) {\n      stack.push(root);\n      root = leftToRight ? root->left : root->right;\n    }\n  }\n};\n\nclass Solution {\n public:\n  bool findTarget(TreeNode* root, int k) {\n    if (root == nullptr)\n      return false;\n\n    BSTIterator left(root, true);\n    BSTIterator right(root, false);\n\n    for (int l = left.next(), r = right.next(); l < r;) {\n      const int sum = l + r;\n      if (sum == k)\n        return true;\n      if (sum < k)\n        l = left.next();\n      else\n        r = right.next();\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/653.html",
    "category": "Algorithms",
    "acceptance_rate": 62.08608300689722,
    "topics": [
      "Hash Table",
      "Two Pointers",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 6979,
    "dislikes": 283,
    "similar_questions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum II - Input Array Is Sorted\", \"titleSlug\": \"two-sum-ii-input-array-is-sorted\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum III - Data structure design\", \"titleSlug\": \"two-sum-iii-data-structure-design\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum BSTs\", \"titleSlug\": \"two-sum-bsts\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"645.9K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 645864, \"totalSubmissionRaw\": 1040273, \"acRate\": \"62.1%\"}",
    "title_pt": "Soma de Dois Números IV - Entrada é uma Árvore Binária de Busca",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária de busca e um inteiro <code>k</code>, retorne <code>true</code> <em>se existirem dois elementos na BST tal que sua soma seja igual a</em> <code>k</code>, <em>ou</em> <code>false</code> <em>caso contrário</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg\" style=\"width: 400px; height: 229px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,3,6,2,4,null,7], k = 9\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg\" style=\"width: 400px; height: 229px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,3,6,2,4,null,7], k = 28\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li><code>root</code> tem garantia de ser uma árvore binária de busca <strong>válida</strong>.</li>\n\t<li><code>-10<sup>5</sup> &lt;= k &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "654",
    "paidOnly": false,
    "title": "Maximum Binary Tree",
    "titleSlug": "maximum-binary-tree",
    "url": "https://leetcode.com/problems/maximum-binary-tree",
    "description_url": "https://leetcode.com/problems/maximum-binary-tree/description/",
    "description": "<p>You are given an integer array <code>nums</code> with no duplicates. A <strong>maximum binary tree</strong> can be built recursively from <code>nums</code> using the following algorithm:</p>\n\n<ol>\n\t<li>Create a root node whose value is the maximum value in <code>nums</code>.</li>\n\t<li>Recursively build the left subtree on the <strong>subarray prefix</strong> to the <strong>left</strong> of the maximum value.</li>\n\t<li>Recursively build the right subtree on the <strong>subarray suffix</strong> to the <strong>right</strong> of the maximum value.</li>\n</ol>\n\n<p>Return <em>the <strong>maximum binary tree</strong> built from </em><code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg\" style=\"width: 302px; height: 421px;\" />\n<pre>\n<strong>Input:</strong> nums = [3,2,1,6,0,5]\n<strong>Output:</strong> [6,3,5,null,2,0,null,null,1]\n<strong>Explanation:</strong> The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n    - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n        - Empty array, so no child.\n        - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n            - Empty array, so no child.\n            - Only one element, so child is a node with value 1.\n    - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n        - Only one element, so child is a node with value 0.\n        - Empty array, so no child.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg\" style=\"width: 182px; height: 301px;\" />\n<pre>\n<strong>Input:</strong> nums = [3,2,1]\n<strong>Output:</strong> [3,null,2,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>All integers in <code>nums</code> are <strong>unique</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-binary-tree/solutions/",
    "solution": "[TOC]\n\n\n## Solution\n\n---\n### Approach 1: Recursive Solution\n\nThe current solution is very simple. We make use of a function `construct(nums, l, r)`, which returns the maximum binary tree consisting of numbers within the indices $$l$$ and $$r$$ in the given $$nums$$ array(excluding the $$r^{th}$$ element).\n\nThe algorithm consists of the following steps:\n\n1. Start with the function call `construct(nums, 0, n)`. Here, $$n$$ refers to the number of elements in the given $$nums$$ array.\n\n2. Find the index, $$max_i$$, of the largest element in the current range of indices $$(l:r-1)$$. Make this largest element, $$nums[max\\_i]$$ as the local root node.\n\n3. Determine the left child using `construct(nums, l, max_i)`. Doing this recursively finds the largest element in the subarray left to the current largest element.\n\n4. Similarly, determine the right child using `construct(nums, max_i + 1, r)`.\n\n5. Return the root node to the calling function.\n\n<iframe src=\"https://leetcode.com/playground/3hVy3spd/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"3hVy3spd\"></iframe>\n\n**Complexity Analysis**\n\n* Time complexity : $$O(n^2)$$. The function `construct` is called $$n$$ times. At each level of the recursive tree, we traverse over all the $$n$$ elements to find the maximum element.  In the average case, there will be a $$\\log n$$ levels leading to a complexity of $$O\\big(n\\log n\\big)$$. In the worst case, the depth of the recursive tree can grow upto $$n$$, which happens in the case of a sorted $$nums$$ array, giving a complexity of $$O(n^2)$$.\n\n* Space complexity : $$O(n)$$. The size of the $$set$$ can grow upto $$n$$ in the worst case. In the average case, the size will be $$\\log n$$ for $$n$$ elements in $$nums$$, giving an average case complexity of $$O(\\log n)$$",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n    def build(i: int, j: int) -> Optional[TreeNode]:\n      if i > j:\n        return None\n\n      maxNum = max(nums[i:j + 1])\n      maxIndex = nums.index(maxNum)\n\n      root = TreeNode(maxNum)\n      root.left = build(i, maxIndex - 1)\n      root.right = build(maxIndex + 1, j)\n      return root\n\n    return build(0, len(nums) - 1)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode constructMaximumBinaryTree(int[] nums) {\n    return build(nums, 0, nums.length - 1);\n  }\n\n  private TreeNode build(int[] nums, int i, int j) {\n    if (i > j)\n      return null;\n\n    int maxIndex = i;\n    for (int k = i + 1; k <= j; ++k)\n      if (nums[k] > nums[maxIndex])\n        maxIndex = k;\n\n    TreeNode root = new TreeNode(nums[maxIndex]);\n    root.left = build(nums, i, maxIndex - 1);\n    root.right = build(nums, maxIndex + 1, j);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* constructMaximumBinaryTree(vector<int>& nums) {\n    return build(nums, 0, nums.size() - 1);\n  }\n\n private:\n  TreeNode* build(const vector<int>& nums, int i, int j) {\n    if (i > j)\n      return nullptr;\n\n    const auto it = max_element(begin(nums) + i, begin(nums) + j + 1);\n    const int maxNum = *it;\n    const int maxIndex = it - begin(nums);\n\n    TreeNode* root = new TreeNode(maxNum);\n    root->left = build(nums, i, maxIndex - 1);\n    root->right = build(nums, maxIndex + 1, j);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/654.html",
    "category": "Algorithms",
    "acceptance_rate": 85.89321217789784,
    "topics": [
      "Array",
      "Divide and Conquer",
      "Stack",
      "Tree",
      "Monotonic Stack",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5319,
    "dislikes": 346,
    "similar_questions": "[{\"title\": \"Maximum Binary Tree II\", \"titleSlug\": \"maximum-binary-tree-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"328.8K\", \"totalSubmission\": \"382.8K\", \"totalAcceptedRaw\": 328764, \"totalSubmissionRaw\": 382759, \"acRate\": \"85.9%\"}",
    "title_pt": "Árvore Binária Máxima",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> sem duplicatas. Uma <strong>árvore binária máxima</strong> pode ser construída recursivamente a partir de <code>nums</code> usando o seguinte algoritmo:</p>\n\n<ol>\n\t<li>Crie um nó raiz cujo valor seja o maior valor em <code>nums</code>.</li>\n\t<li>Construa recursivamente a subárvore esquerda no <strong>prefixo do subarray</strong> à <strong>esquerda</strong> do maior valor.</li>\n\t<li>Construa recursivamente a subárvore direita no <strong>sufixo do subarray</strong> à <strong>direita</strong> do maior valor.</li>\n</ol>\n\n<p>Retorne <em>a <strong>árvore binária máxima</strong> construída a partir de </em><code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/tree1.jpg\" style=\"width: 302px; height: 421px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [3,2,1,6,0,5]\n<strong>Saída:</strong> [6,3,5,null,2,0,null,null,1]\n<strong>Explicação:</strong> As chamadas recursivas são as seguintes:\n- O maior valor em [3,2,1,6,0,5] é 6. O prefixo esquerdo é [3,2,1] e o sufixo direito é [0,5].\n    - O maior valor em [3,2,1] é 3. O prefixo esquerdo é [] e o sufixo direito é [2,1].\n        - Array vazio, então não há filho.\n        - O maior valor em [2,1] é 2. O prefixo esquerdo é [] e o sufixo direito é [1].\n            - Array vazio, então não há filho.\n            - Há apenas um elemento, então o filho é um nó com valor 1.\n    - O maior valor em [0,5] é 5. O prefixo esquerdo é [0] e o sufixo direito é [].\n        - Há apenas um elemento, então o filho é um nó com valor 0.\n        - Array vazio, então não há filho.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/24/tree2.jpg\" style=\"width: 182px; height: 301px;\" />\n<pre>\n<strong>Entrada:</strong> nums = [3,2,1]\n<strong>Saída:</strong> [3,null,2,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li>Todos os inteiros em <code>nums</code> são <strong>únicos</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "655",
    "paidOnly": false,
    "title": "Print Binary Tree",
    "titleSlug": "print-binary-tree",
    "url": "https://leetcode.com/problems/print-binary-tree",
    "description_url": "https://leetcode.com/problems/print-binary-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p>\n\n<ul>\n\t<li>The <strong>height</strong> of the tree is <code>height</code>&nbsp;and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li>\n\t<li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li>\n\t<li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li>\n\t<li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2<sup>height-r-1</sup>]</code> and its <strong>right child</strong> at <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li>\n\t<li>Continue this process until all the nodes in the tree have been placed.</li>\n\t<li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p>Return <em>the constructed matrix </em><code>res</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg\" style=\"width: 141px; height: 181px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2]\n<strong>Output:</strong> \n[[&quot;&quot;,&quot;1&quot;,&quot;&quot;],\n&nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg\" style=\"width: 207px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [1,2,3,null,4]\n<strong>Output:</strong> \n[[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;],\n&nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;],\n&nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li>\n\t<li><code>-99 &lt;= Node.val &lt;= 99</code></li>\n\t<li>The depth of the tree will be in the range <code>[1, 10]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/print-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:\n    def maxHeight(root: Optional[TreeNode]) -> int:\n      if not root:\n        return 0\n      return 1 + max(maxHeight(root.left), maxHeight(root.right))\n\n    def dfs(root: Optional[TreeNode], row: int, left: int, right: int) -> None:\n      if not root:\n        return\n\n      mid = (left + right) // 2\n      ans[row][mid] = str(root.val)\n      dfs(root.left, row + 1, left, mid - 1)\n      dfs(root.right, row + 1, mid + 1, right)\n\n    m = maxHeight(root)\n    n = pow(2, m) - 1\n    ans = [[''] * n for _ in range(m)]\n    dfs(root, 0, 0, len(ans[0]) - 1)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<List<String>> printTree(TreeNode root) {\n    final int m = maxHeight(root);\n    final int n = (int) Math.pow(2, m) - 1;\n    List<List<String>> ans = new ArrayList<>();\n    List<String> row = new ArrayList<>();\n\n    for (int i = 0; i < n; ++i)\n      row.add(\"\");\n\n    for (int i = 0; i < m; ++i)\n      ans.add(new ArrayList<>(row));\n\n    dfs(root, 0, 0, n - 1, ans);\n    return ans;\n  }\n\n  private int maxHeight(TreeNode root) {\n    if (root == null)\n      return 0;\n    return 1 + Math.max(maxHeight(root.left), maxHeight(root.right));\n  }\n\n  private void dfs(TreeNode root, int row, int left, int right, List<List<String>> ans) {\n    if (root == null)\n      return;\n\n    final int mid = (left + right) / 2;\n    ans.get(row).set(mid, Integer.toString(root.val));\n    dfs(root.left, row + 1, left, mid - 1, ans);\n    dfs(root.right, row + 1, mid + 1, right, ans);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<string>> printTree(TreeNode* root) {\n    const int m = maxHeight(root);\n    const int n = pow(2, m) - 1;\n    vector<vector<string>> ans(m, vector<string>(n));\n    dfs(root, 0, 0, ans[0].size() - 1, ans);\n    return ans;\n  }\n\n private:\n  int maxHeight(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n    return 1 + max(maxHeight(root->left), maxHeight(root->right));\n  }\n\n  void dfs(TreeNode* root, int row, int left, int right,\n           vector<vector<string>>& ans) {\n    if (root == nullptr)\n      return;\n\n    const int mid = (left + right) / 2;\n    ans[row][mid] = to_string(root->val);\n    dfs(root->left, row + 1, left, mid - 1, ans);\n    dfs(root->right, row + 1, mid + 1, right, ans);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/655.html",
    "category": "Algorithms",
    "acceptance_rate": 65.46174362393732,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 529,
    "dislikes": 463,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"78.5K\", \"totalSubmission\": \"120K\", \"totalAcceptedRaw\": 78541, \"totalSubmissionRaw\": 119980, \"acRate\": \"65.5%\"}",
    "title_pt": "Imprimir Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, construa uma matriz de strings <code>res</code> <strong>indexada em 0</strong> de tamanho <code>m x n</code> que represente um <strong>layout formatado</strong> da árvore. A matriz do layout formatado deve ser construída usando as seguintes regras:</p>\n\n<ul>\n\t<li>A <strong>altura</strong> da árvore é <code>height</code>&nbsp; e o número de linhas <code>m</code> deve ser igual a <code>height + 1</code>.</li>\n\t<li>O número de colunas <code>n</code> deve ser igual a <code>2<sup>height+1</sup> - 1</code>.</li>\n\t<li>Coloque o <strong>nó raiz</strong> no <strong>meio</strong> da <strong>primeira linha</strong> (mais formalmente, na posição <code>res[0][(n-1)/2]</code>).</li>\n\t<li>Para cada nó que tenha sido colocado na matriz na posição <code>res[r][c]</code>, coloque seu <strong>filho esquerdo</strong> em <code>res[r+1][c-2<sup>height-r-1</sup>]</code> e seu <strong>filho direito</strong> em <code>res[r+1][c+2<sup>height-r-1</sup>]</code>.</li>\n\t<li>Continue esse processo até que todos os nós da árvore tenham sido colocados.</li>\n\t<li>Quaisquer células vazias devem conter a string vazia <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p>Retorne <em>a matriz construída </em><code>res</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg\" style=\"width: 141px; height: 181px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2]\n<strong>Saída:</strong> \n[[&quot;&quot;,&quot;1&quot;,&quot;&quot;],\n&nbsp;[&quot;2&quot;,&quot;&quot;,&quot;&quot;]]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg\" style=\"width: 207px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,2,3,null,4]\n<strong>Saída:</strong> \n[[&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;1&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;],\n&nbsp;[&quot;&quot;,&quot;2&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;3&quot;,&quot;&quot;],\n&nbsp;[&quot;&quot;,&quot;&quot;,&quot;4&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós da árvore está no intervalo <code>[1, 2<sup>10</sup>]</code>.</li>\n\t<li><code>-99 &lt;= Node.val &lt;= 99</code></li>\n\t<li>A profundidade da árvore estará no intervalo <code>[1, 10]</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "657",
    "paidOnly": false,
    "title": "Robot Return to Origin",
    "titleSlug": "robot-return-to-origin",
    "url": "https://leetcode.com/problems/robot-return-to-origin",
    "description_url": "https://leetcode.com/problems/robot-return-to-origin/description/",
    "description": "<p>There is a robot starting at the position <code>(0, 0)</code>, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot <strong>ends up at </strong><code>(0, 0)</code> after it completes its moves.</p>\n\n<p>You are given a string <code>moves</code> that represents the move sequence of the robot where <code>moves[i]</code> represents its <code>i<sup>th</sup></code> move. Valid moves are <code>&#39;R&#39;</code> (right), <code>&#39;L&#39;</code> (left), <code>&#39;U&#39;</code> (up), and <code>&#39;D&#39;</code> (down).</p>\n\n<p>Return <code>true</code><em> if the robot returns to the origin after it finishes all of its moves, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p><strong>Note</strong>: The way that the robot is &quot;facing&quot; is irrelevant. <code>&#39;R&#39;</code> will always make the robot move to the right once, <code>&#39;L&#39;</code> will always make it move left, etc. Also, assume that the magnitude of the robot&#39;s movement is the same for each move.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> moves = &quot;UD&quot;\n<strong>Output:</strong> true\n<strong>Explanation</strong>: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> moves = &quot;LL&quot;\n<strong>Output:</strong> false\n<strong>Explanation</strong>: The robot moves left twice. It ends up two &quot;moves&quot; to the left of the origin. We return false because it is not at the origin at the end of its moves.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= moves.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>moves</code> only contains the characters <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code> and <code>&#39;R&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/robot-return-to-origin/solutions/",
    "solution": "[TOC]\n\n---\n### Approach #1: Simulation [Accepted]\n\n**Intuition**\n\nWe can simulate the position of the robot after each command.\n\n**Algorithm**\n\nInitially, the robot is at `(x, y) = (0, 0)`. If the move is `'U'`, the robot goes to `(x, y - 1)`; if the move is `'R'`, the robot goes to `(x, y) = (x + 1, y)`, and so on.\n\n<iframe src=\"https://leetcode.com/playground/jyFhh6vm/shared\" frameBorder=\"0\" width=\"100%\" height=\"259\" name=\"jyFhh6vm\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `moves`. We iterate through the string.\n\n* Space Complexity: $$O(1)$$. In Java, our character array is $$O(N)$$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def judgeCircle(self, moves: str) -> bool:\n    return moves.count('R') == moves.count('L') and moves.count('U') == moves.count('D')",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean judgeCircle(String moves) {\n    int right = 0;\n    int up = 0;\n\n    for (final char move : moves.toCharArray()) {\n      switch (move) {\n        case 'R':\n          ++right;\n          break;\n        case 'L':\n          --right;\n          break;\n        case 'U':\n          ++up;\n          break;\n        case 'D':\n          --up;\n          break;\n      }\n    }\n\n    return right == 0 && up == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool judgeCircle(string moves) {\n    int right = 0;\n    int up = 0;\n\n    for (const char move : moves) {\n      switch (move) {\n        case 'R':\n          ++right;\n          break;\n        case 'L':\n          --right;\n          break;\n        case 'U':\n          ++up;\n          break;\n        case 'D':\n          --up;\n          break;\n      }\n    }\n\n    return right == 0 && up == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/657.html",
    "category": "Algorithms",
    "acceptance_rate": 76.12670929968613,
    "topics": [
      "String",
      "Simulation"
    ],
    "hints": [],
    "likes": 2500,
    "dislikes": 749,
    "similar_questions": "[{\"title\": \"Number of Provinces\", \"titleSlug\": \"number-of-provinces\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Execution of All Suffix Instructions Staying in a Grid\", \"titleSlug\": \"execution-of-all-suffix-instructions-staying-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Furthest Point From Origin\", \"titleSlug\": \"furthest-point-from-origin\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"486.3K\", \"totalSubmission\": \"638.8K\", \"totalAcceptedRaw\": 486286, \"totalSubmissionRaw\": 638785, \"acRate\": \"76.1%\"}",
    "title_pt": "Robô Retorna à Origem",
    "description_pt": "<p>Há um robô começando na posição <code>(0, 0)</code>, a origem, em um plano 2D. Dada uma sequência de seus movimentos, julgue se esse robô <strong>termina em </strong><code>(0, 0)</code> após completar seus movimentos.</p>\n\n<p>Você recebe uma string <code>moves</code> que representa a sequência de movimentos do robô, em que <code>moves[i]</code> representa seu <code>i<sup>ésimo</sup></code> movimento. Os movimentos válidos são <code>&#39;R&#39;</code> (direita), <code>&#39;L&#39;</code> (esquerda), <code>&#39;U&#39;</code> (cima) e <code>&#39;D&#39;</code> (baixo).</p>\n\n<p>Retorne <code>true</code><em> se o robô retornar à origem depois de finalizar todos os seus movimentos, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p><strong>Nota</strong>: A direção para a qual o robô está &quot;virado&quot; é irrelevante. <code>&#39;R&#39;</code> sempre fará o robô mover-se uma vez para a direita, <code>&#39;L&#39;</code> sempre fará com que ele se mova para a esquerda, etc. Além disso, assuma que a magnitude do movimento do robô é a mesma para cada movimento.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> moves = &quot;UD&quot;\n<strong>Saída:</strong> true\n<strong>Explicação</strong>: O robô se move para cima uma vez e, em seguida, para baixo uma vez. Todos os movimentos têm a mesma magnitude, então ele terminou na origem onde começou. Portanto, retornamos true.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> moves = &quot;LL&quot;\n<strong>Saída:</strong> false\n<strong>Explicação</strong>: O robô se move para a esquerda duas vezes. Ele termina dois &quot;movimentos&quot; à esquerda da origem. Retornamos false porque ele não está na origem ao final de seus movimentos.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= moves.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>moves</code> contém apenas os caracteres <code>&#39;U&#39;</code>, <code>&#39;D&#39;</code>, <code>&#39;L&#39;</code> e <code>&#39;R&#39;</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "658",
    "paidOnly": false,
    "title": "Find K Closest Elements",
    "titleSlug": "find-k-closest-elements",
    "url": "https://leetcode.com/problems/find-k-closest-elements",
    "description_url": "https://leetcode.com/problems/find-k-closest-elements/description/",
    "description": "<p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>\n\n<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>\n\n<ul>\n\t<li><code>|a - x| &lt; |b - x|</code>, or</li>\n\t<li><code>|a - x| == |b - x|</code> and <code>a &lt; b</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">arr = [1,2,3,4,5], k = 4, x = 3</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,2,3,4]</span></p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong> <span class=\"example-io\">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[1,1,2,3]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= arr.length</code></li>\n\t<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>\n\t<li><code>-10<sup>4</sup> &lt;= arr[i], x &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-k-closest-elements/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n    l = 0\n    r = len(arr) - k\n\n    while l < r:\n      m = (l + r) // 2\n      if x - arr[m] <= arr[m + k] - x:\n        r = m\n      else:\n        l = m + 1\n\n    return arr[l:l + k]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<Integer> findClosestElements(int[] arr, int k, int x) {\n    int l = 0;\n    int r = arr.length - k;\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (x - arr[m] <= arr[m + k] - x)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return Arrays.stream(arr, l, l + k).boxed().collect(Collectors.toList());\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n    int l = 0;\n    int r = arr.size() - k;\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (x - arr[m] <= arr[m + k] - x)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return {begin(arr) + l, begin(arr) + l + k};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/658.html",
    "category": "Algorithms",
    "acceptance_rate": 48.55336709784127,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search",
      "Sliding Window",
      "Sorting",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 8630,
    "dislikes": 797,
    "similar_questions": "[{\"title\": \"Guess Number Higher or Lower\", \"titleSlug\": \"guess-number-higher-or-lower\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Guess Number Higher or Lower II\", \"titleSlug\": \"guess-number-higher-or-lower-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K-th Smallest Pair Distance\", \"titleSlug\": \"find-k-th-smallest-pair-distance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Closest Number to Zero\", \"titleSlug\": \"find-closest-number-to-zero\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"689.6K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 689569, \"totalSubmissionRaw\": 1420229, \"acRate\": \"48.6%\"}",
    "title_pt": "Encontrar os K Elementos Mais Próximos",
    "description_pt": "<p>Dado um array de inteiros <strong>ordenado</strong> <code>arr</code>, dois inteiros <code>k</code> e <code>x</code>, retorne os <code>k</code> inteiros mais próximos de <code>x</code> no array. O resultado também deve ser ordenado em ordem crescente.</p>\n\n<p>Um inteiro <code>a</code> está mais próximo de <code>x</code> do que um inteiro <code>b</code> se:</p>\n\n<ul>\n\t<li><code>|a - x| &lt; |b - x|</code>, ou</li>\n\t<li><code>|a - x| == |b - x|</code> e <code>a &lt; b</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">arr = [1,2,3,4,5], k = 4, x = 3</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,2,3,4]</span></p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong> <span class=\"example-io\">arr = [1,1,2,3,4,5], k = 4, x = -1</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[1,1,2,3]</span></p>\n</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= arr.length</code></li>\n\t<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>arr</code> é ordenado em ordem <strong>crescente</strong>.</li>\n\t<li><code>-10<sup>4</sup> &lt;= arr[i], x &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "659",
    "paidOnly": false,
    "title": "Split Array into Consecutive Subsequences",
    "titleSlug": "split-array-into-consecutive-subsequences",
    "url": "https://leetcode.com/problems/split-array-into-consecutive-subsequences",
    "description_url": "https://leetcode.com/problems/split-array-into-consecutive-subsequences/description/",
    "description": "<p>You are given an integer array <code>nums</code> that is <strong>sorted in non-decreasing order</strong>.</p>\n\n<p>Determine if it is possible to split <code>nums</code> into <strong>one or more subsequences</strong> such that <strong>both</strong> of the following conditions are true:</p>\n\n<ul>\n\t<li>Each subsequence is a <strong>consecutive increasing sequence</strong> (i.e. each integer is <strong>exactly one</strong> more than the previous integer).</li>\n\t<li>All subsequences have a length of <code>3</code><strong> or more</strong>.</li>\n</ul>\n\n<p>Return <code>true</code><em> if you can split </em><code>nums</code><em> according to the above conditions, or </em><code>false</code><em> otherwise</em>.</p>\n\n<p>A <strong>subsequence</strong> of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., <code>[1,3,5]</code> is a subsequence of <code>[<u>1</u>,2,<u>3</u>,4,<u>5</u>]</code> while <code>[1,3,2]</code> is not).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,3,4,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> nums can be split into the following subsequences:\n[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,4,5] --&gt; 1, 2, 3\n[1,2,3,<strong><u>3</u></strong>,<strong><u>4</u></strong>,<strong><u>5</u></strong>] --&gt; 3, 4, 5\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,3,4,4,5,5]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> nums can be split into the following subsequences:\n[<strong><u>1</u></strong>,<strong><u>2</u></strong>,<strong><u>3</u></strong>,3,<strong><u>4</u></strong>,4,<strong><u>5</u></strong>,5] --&gt; 1, 2, 3, 4, 5\n[1,2,3,<strong><u>3</u></strong>,4,<strong><u>4</u></strong>,5,<strong><u>5</u></strong>] --&gt; 3, 4, 5\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4,4,5]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/split-array-into-consecutive-subsequences/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nimport java.util.List;\n\nclass Solution {\n  public boolean isPossible(int[] nums) {\n    Map<Integer, Integer> count = new HashMap<>();\n    List<Integer> starts = new ArrayList<>(); // Start index of subsequence\n    List<Integer> ends = new ArrayList<>();   // End index of subsequence\n\n    for (final int num : nums)\n      count.put(num, count.getOrDefault(num, 0) + 1);\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      final int num = nums[i];\n      final int currCount = count.get(num);\n      final int prevCount = count.containsKey(num - 1) ? count.get(num - 1) : 0;\n      final int nextCount = count.containsKey(num + 1) ? count.get(num + 1) : 0;\n      for (int j = 0; j < currCount - prevCount; ++j)\n        starts.add(num);\n      for (int j = 0; j < currCount - nextCount; ++j)\n        ends.add(num);\n    }\n\n    for (int i = 0; i < starts.size(); ++i)\n      if (ends.get(i) - starts.get(i) < 2)\n        return false;\n\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isPossible(vector<int>& nums) {\n    unordered_map<int, int> count;\n    vector<int> starts;  // Start index of subsequence\n    vector<int> ends;    // End index of subsequence\n\n    for (const int num : nums)\n      ++count[num];\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (i > 0 && nums[i] == nums[i - 1])\n        continue;\n      const int num = nums[i];\n      const int currCount = count[num];\n      const int prevCount = count.count(num - 1) ? count[num - 1] : 0;\n      const int nextCount = count.count(num + 1) ? count[num + 1] : 0;\n      for (int j = 0; j < currCount - prevCount; ++j)\n        starts.push_back(num);\n      for (int j = 0; j < currCount - nextCount; ++j)\n        ends.push_back(num);\n    }\n\n    for (int i = 0; i < starts.size(); ++i)\n      if (ends[i] - starts[i] < 2)\n        return false;\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/659.html",
    "category": "Algorithms",
    "acceptance_rate": 51.4734314755096,
    "topics": [
      "Array",
      "Hash Table",
      "Greedy",
      "Heap (Priority Queue)"
    ],
    "hints": [],
    "likes": 4494,
    "dislikes": 812,
    "similar_questions": "[{\"title\": \"Top K Frequent Elements\", \"titleSlug\": \"top-k-frequent-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Divide Array in Sets of K Consecutive Numbers\", \"titleSlug\": \"divide-array-in-sets-of-k-consecutive-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"138.7K\", \"totalSubmission\": \"269.5K\", \"totalAcceptedRaw\": 138706, \"totalSubmissionRaw\": 269472, \"acRate\": \"51.5%\"}",
    "title_pt": "Dividir Array em Subsequências Consecutivas",
    "description_pt": "<p>Você recebe um array de inteiros <code>nums</code> que está <strong>ordenado em ordem não decrescente</strong>.</p>\n\n<p>Determine se é possível dividir <code>nums</code> em <strong>uma ou mais subsequências</strong> de modo que <strong>ambas</strong> as condições a seguir sejam verdadeiras:</p>\n\n<ul>\n\t<li>Cada subsequência é uma <strong>sequência crescente consecutiva</strong> (ou seja, cada inteiro é <strong>exatamente um</strong> a mais que o inteiro anterior).</li>\n\t<li>Todas as subsequências têm comprimento de <code>3</code><strong> ou mais</strong>.</li>\n</ul>\n\n<p>Retorne <code>true</code><em> se você puder dividir </em><code>nums</code><em> de acordo com as condições acima, ou </em><code>false</code><em> caso contrário</em>.</p>\n\n<p>Uma <strong>subsequência</strong> de um array é um novo array formado a partir do array original ao حذف?",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "661",
    "paidOnly": false,
    "title": "Image Smoother",
    "titleSlug": "image-smoother",
    "url": "https://leetcode.com/problems/image-smoother",
    "description_url": "https://leetcode.com/problems/image-smoother/description/",
    "description": "<p>An <strong>image smoother</strong> is a filter of the size <code>3 x 3</code> that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smoother-grid.jpg\" style=\"width: 493px; height: 493px;\" />\n<p>Given an <code>m x n</code> integer matrix <code>img</code> representing the grayscale of an image, return <em>the image after applying the smoother on each cell of it</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg\" style=\"width: 613px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]\n<strong>Output:</strong> [[0,0,0],[0,0,0],[0,0,0]]\n<strong>Explanation:</strong>\nFor the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg\" style=\"width: 613px; height: 253px;\" />\n<pre>\n<strong>Input:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]\n<strong>Output:</strong> [[137,141,137],[141,138,141],[137,141,137]]\n<strong>Explanation:</strong>\nFor the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == img.length</code></li>\n\t<li><code>n == img[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= img[i][j] &lt;= 255</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/image-smoother/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nIn this problem, we are given an `m x n` integer matrix `img`. \n\nWe need to return a matrix of dimension `m x n` where each cell is obtained by applying **smoother** on the corresponding cell of the `img` matrix.\n\nNow, **smoother**, as given in the problem statement, can be thought of as an operator that takes as an input a cell. It then returns the *average* of the values of the \"cell and its *neighbors*\".\n\n- *average*: the average of a list of integers is the sum of the integers divided by the number of integers in the list. The average can be a floating point number, and in that case, the smoother should round down the result to the nearest integer.\n\n- *neighbors*: a cell is called a neighbor of another cell if they share a common edge or a common corner.\n\nNow, based on the different numbers of neighbors, let's see how we can apply the **smoother** operator on a cell.\n\n- A cell can have at most 8 neighbors. 4 of these share a common edge, and the remaining 4 share a common corner. \n  \n   ![8_neighbors](../Figures/661/661_slide_images_used/Slide1.PNG)\n\n   To apply smoother on the central cell, colored in yellow, we need to find the average of the values of the cell and its 8 neighbors. It is worth noting that for computing the average, we need to consider the value of the cell itself as well.\n\n   - The sum of the values of the cell and its 8 neighbors is `24 + 4 + 56 + 8 + 78 + 2 + 23 + 8 + 69`, which adds up to `272`.\n\n   - The number of cells we are using to compute the average is `9`.\n\n   - Hence, the average is `272 / 9`, which is `30.22`, rounded down to `30`.\n\n- If there is only one cell in the matrix, then it has no neighbors.\n\n    ![no_neighbors](../Figures/661/661_slide_images_used/Slide2_1.PNG)\n\n    To apply smoother on this cell, we need to find the average of the values of the cell and its (non-existent) neighbors.\n\n    - The sum of the values of the cell and its 0 neighbors is the value present in the cell itself, which is `68`.\n\n    - The number of cells we are using to compute the average is `1` only since there were no neighbors.\n\n    - Hence, the average is `68 / 1`, which is the same as the value of the cell itself, which is `68`.\n\n- If there is more than one cell in the matrix, then each cell has at least one neighbor.\n\n    ![1neighbors](../Figures/661/661_slide_images_used/Slide2_2.PNG)\n\n- If the matrix has more than one row, and more than one column, then each cell has at least 3 neighbors. \n\n    ![3neighbors](../Figures/661/661_slide_images_used/Slide3.PNG)\n\n    To apply smoother on the corner cell, colored in yellow, we need to find the average of the values of the cell and its 3 neighbors.\n\n    - The sum of the values of the cell and its 3 neighbors is `42 + 59 + 23 + 75`, which adds up to `199`.\n\n    - The number of cells we are using to compute the average is `4`.  \n\n    - Hence, the average is `199 / 4`, which is `49.75`, rounded down to `49`.\n\nThus, using this way, we need to apply the **smoother** operator on each cell of the `img`, and return the resultant matrix.\n\n<details> <summary> <b> Why it is called a smoother? </b> Click to find out! </summary>\n\n<p>\n\n> Grayscale images are nothing but a matrix (two-dimensional array) of integers. Each integer represents a pixel, the smallest unit of a digital image. The value of the integer represents the intensity of the pixel. The higher the value, the more intense the pixel is. The intensity of the pixel ranges from `0` to `255`. The value `0` represents black, and the value `255` represents white. The values in between represent different shades of gray.\n>\n> Here is a grayscale image of size `400 px x 400 px`.\n> \n> ![gray_image](../Figures/661/661_code_images/gray_image.png)\n>\n> One pixel represents one cell, hence the dimension of the corresponding matrix will be `400 x 400`. Here is what a part of the matrix looks like.\n>\n> ![gray_image_matrix](../Figures/661/661_code_images/matrix_gray_image.png)\n> \n> On applying the **smoother** operator on each cell of the matrix, the same part of the matrix will look like this.\n>\n> ![gray_image_matrix_smoother](../Figures/661/661_code_images/matrix_smooth_image1.png)\n> \n> Let's convert the smoothened matrix back to the grayscale image, and compare it with the original image.\n>\n> ![comparison](../Figures/661/661_code_images/compare1.png)\n>\n> Readers can observe that the image after applying the **smoother** operator is blurr than the original image with sharp and fine details chopped off. If we again and again apply the **smoother** operator on the image, the image will become more and more blurred. Here are a few rounds of repeated application of the **smoother** operator on the image.\n>\n> ![repeated_application](../Figures/661/661_code_images/compare2.png)\n\n> As **trivia**, it is worth knowing that a grayscale image is a two-dimensional array of integers, but a colored image is a three-dimensional array of integers. It has three dimensions because each pixel has three components: red, green, and blue. The value of each component ranges from `0` to `255`. The value `0` represents the absence of the component, and the value `255` represents the presence of the component in its full intensity. The values in between represent different shades of the component. The three components together represent the color of the pixel. \n\n</p>\n</details>\n<br/>\n\nLet's see how we can solve this problem with different approaches.\n\n---\n\n\n### Approach 1: Create a New Smoothened Image\n\n#### Intuition\n\nWe know that for applying the **smoother** operator, we need to consider the neighbors in the original `img` matrix, not the neighbors in the resultant matrix. Hence, we cannot overwrite the values of the `img` matrix with the result of the **smoother** operator. \n\nThe following example illustrates this point.\n\n> Let our `img` be `[[100, 0, 10], [0, 0, 25], [10, 10, 10]]`. The output should be `[[25, 22, 8], [20, 18, 9], [5, 9, 11]]`\n>\n> ![img-out](../Figures/661/661_slide_images_used/Slide4.PNG)\n>\n> Assume that we have applied the smooth operator on the first cell, and overwritten the value of the cell with the result. The `img` now will become `[[25, 0, 10], [0, 0, 25], [10, 10, 10]]`.\n>\n> ![overwrite](../Figures/661/661_slide_images_used/Slide5_1.PNG)\n>\n> Now if we use this matrix to apply the smooth operator on the second cell of the first row, we will get the value `10` instead of the expected value `22`.\n> \n> ![wrong](../Figures/661/661_slide_images_used/Slide5_2.PNG)\n\nFor this reason, we will not overwrite the values of the `img` matrix with the result of the **smoother** operator. This, thus calls for an extra space to store the result of the **smoother** operator for each cell of the `img` matrix.\n\nThe dimension of the input `img` matrix is `m x n`. Thus, let's create smoothened image in a new matrix `smooth_img` of dimension `m x n`.\n\nNow to compute individual cells of the `smooth_img`, we need to read the corresponding cell and its (valid) neighbors from the `img` matrix. \n\nThus, to compute the `smooth_img[i][j]`, we may need to read the following cells from the `img` matrix.\n- `img[i][j]`, the cell itself.\n- `img[i - 1][j - 1]`, the cell that shares the top-left corner with this cell. \n- `img[i - 1][j]`, the cell that shares the top edge with this cell.\n- `img[i - 1][j + 1]`, the cell that shares the top-right corner with this cell.\n- `img[i][j - 1]`, the cell that shares the left edge with this cell.\n- `img[i][j + 1]`, the cell that shares the right edge with this cell.\n- `img[i + 1][j - 1]`, the cell that shares the bottom-left corner with this cell.\n- `img[i + 1][j]`, the cell that shares the bottom edge with this cell.\n- `img[i + 1][j + 1]`, the cell that shares the bottom-right corner with this cell.\n\nHowever, not all of these cells are necessarily valid. \n\n> If `i = 0`, then `img[i - 1][j - 1]`, `img[i - 1][j]`, and `img[i - 1][j + 1]` are invalid, because they are above the top most row of the `img` matrix.\n\nA cell will be valid only if it is within the bounds of the `img` matrix.\n- The row index of the cell should be greater than or equal to `0`, and less than `m`.\n- The column index of the cell should be greater than or equal to `0`, and less than `n`.\n\nThus, in general, a neighbor with row index `x`, and column index `y` will be valid if `0 <= x < m`, and `0 <= y < n`. Both of these conditions should be true.\n\nNow we need to compute the average of the values of the valid neighbors of the cell, and the value of the cell itself. For this, we need the sum of these values and the count of these values. \n\nHence, to compute `smooth_img[i][j]`\n- Use two variables, `sum` and `count`, to store the sum and count of the values of the valid neighbors of the cell, and the value of the cell itself.\n- Iterate over all plausible nine indices, if the indices form a valid neighbor, then add the value of the cell at that index to `sum`, and increment `count` by `1`.\n- Compute the average by `sum / count`, and store the rounded down value in `smooth_img[i][j]`.\n\nReaders are encouraged to implement this algorithm on their own.\n\n\n#### Algorithm\n\n1. Save the dimensions of the image. Store the number of rows in `m`, and the number of columns in `n`, as convention used in the problem statement as well.\n\n2. Create a new image of the same dimension as the input image. Let's call this new image `smooth_img`. Initialize all the cells of the `smooth_img` with `0`.\n\n3. Iterate over the cells of the image. Let's call the current cell `img[i][j]`.\n    \n    - Initialize two integer variables `sum` and `count` to `0`.\n\n    - Iterate over all plausible nine indices `(x, y)`. The `(x, y)` are\n      - `(i - 1, j - 1)`\n\n      - `(i - 1, j)`\n      - `(i - 1, j + 1)`\n      - `(i, j - 1)`\n      - `(i, j)`\n      - `(i, j + 1)`\n      - `(i + 1, j - 1)`\n      - `(i + 1, j)`\n      - `(i + 1, j + 1)` \n\n      If index `(x, y)` is valid, then add the value of `img[x][y]` to `sum`, and increment `count` by `1`.\n    \n    - In `smooth_img[i][j]`, store the rounded down value of `sum / count`.\n\n4. Return the `smooth_img`. \n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/9UY4TRnT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"9UY4TRnT\"></iframe>\n\n**Implementation Note:** For iterating the nine neighbors, we have used constant time nested for loops, which list the nine neighbors.\n\nThe other approach to achieving this is using the `DIRECTION` array, which lists the change in the neighbor's position. A typical `DIRECTION` array will look like this\n\n```DIRECTION []\n[\n    (-1, -1), (-1, 0), (-1, 1),\n    (0, -1), (0, 0), (0, 1),\n    (1, -1), (1, 0), (1, 1)\n]\n```\n\nReaders are encouraged to implement this approach as well to widen their implementation skills.\n\n#### Complexity Analysis\n\nLet $m$ be the number of rows in the `img` matrix, and $n$ be the number of columns in the `img` matrix.\n\n* Time complexity: $O(m \\cdot n)$\n\n    We are computing the value of each cell of the `smooth_img` matrix. There are $m \\cdot n$ cells in the `smooth_img` matrix. \n    \n    For each cell, we are iterating over all plausible nine indices. There are at most nine indices for each cell. \n    \n    Hence, the time complexity of the algorithm is $O(m \\cdot n \\cdot 9)$, which is $O(m \\cdot n)$.\n\n* Space complexity: $O(m \\cdot n)$\n\n    We are creating a new matrix of dimension $m \\cdot n$ to store the result. Hence, the space complexity of the algorithm is $O(m \\cdot n)$.  \n        \n---\n\n### Approach 2: Space-Optimized Smoothened Image\n\n#### Intuition\n\nIn the previous approach, we created a new matrix of dimension `m x n` to store the result. Moreover, we have seen that we can't overwrite the values of the `img` matrix with the result of the **smoother** operator. If we modify `img[i][j]` in place, we won't be able to use the original `img[i][j]` in subsequent calculations because the value at this position has already been overwritten.\n\nLet's take a closer look at why we can't overwrite these values.\n\nWe were moving row-by-row, and in each row, we were moving column-by-column. Assume we are overwriting the cells *(with somehow correct smoothened value)* as we move on. \n\nLet's call the current cell `img[i][j]`. To compute `smooth_img[i][j]`, we need to read the value of `img[i][j]`, and its neighbors.\n\n![neighbors](../Figures/661/661_slide_images_used/Slide6.PNG)\n\nHowever, because of our order of traversal, out of these 8 neighbors, the top 3 neighbors (which are in the row `img[i - 1]`), and the left neighbor (which is in cell `img[i][j - 1]`) have already been overwritten. Hence, we don't have access to the original values of these neighbors.\n\n![no_access](../Figures/661/661_slide_images_used/Slide7.PNG)\n\nIn summary, for calculating `smooth_img[i]`\n- We need to save the original values of two rows `img[i]` and `img[i - 1]`.\n- Rows before `img[i - 1]`, such as `img[i - 2]` or `img[i - 3]`, are no longer needed and need not be saved. \n- The next row `img[i + 1]` has not been overwritten yet, and hence, we can use it as is it.\n\nTo achieve this, we can proceed by saving all original values of two rows in two temporary arrays. The previous row is saved as `prev` and the current row is saved as `curr`.\n\nNow, for computing `img[i][j]`\n - All three neighbors of the previous row will be saved in the `prev` array. The stored values in `img[i - 1]` will be the smoothed value as we are supposed to overwrite as we proceed.\n - The original value of `img[i][j - 1]` will be saved in `curr` array. The presently stored value of `img[i][j - 1]` is the smoothed value of `img[i][j - 1]`, and not the original value.\n - The original value of `img[i][j]` is in `img` itself, because it has not been overwritten yet.\n - The original value of `img[i][j + 1]` is in `img` itself, because it has not been overwritten yet.\n - All three neighbors of the next row will be saved in `img` itself.\n\nHence, by using this approach, we can overwrite the values of the `img` matrix. The `curr` can be filled on the fly before overwriting, and will be given the name of `prev` after the iteration is over. \n\nReaders are encouraged to implement this approach where we need not construct a new matrix to store the result. However, there are a few more optimizations that can be done.\n\nLet's brainstorm further to use only one array `temp` instead of two arrays. The idea is that if we are on `img[i][j]` \n- The indices `temp[j]`, `temp[j + 1]`, `temp[j + 2]` ... represent the value of the `prev` array, or in other terms, original values of `img[i - 1]`\n- The indices ... `temp[j - 3]`, `temp[j - 2]`, `temp[j - 1]` represent the value of the `curr` array, or in other terms, original values of `img[i]`\n\nThis construction overwrites *previous row values* in `temp` with *current row values* as we traverse along the row. However, it has one major flaw. Let's enlist to see what it is by focusing on cell `img[i][j]`.\n\n- The neighbors in next row `img[i + 1]` are in `img` only.\n- The next neighbor in same row `img[i][j + 1]` is in `img` only.\n- The current value of `img[i][j]` is also not overwritten yet.\n- The previous neighbor in same row `img[i][j - 1]` is in `temp`.\n- The two of neighbors in previous row `img[i - 1]` are in `temp`. Precisely original value of `img[i - 1][j]` is in `temp[j]`, and original value of `img[i - 1][j + 1]` is in `temp[j + 1]`.\n\nThe only missing piece is the original value of `img[i - 1][j - 1]`. The value there now is smoothed value of `img[i - 1][j - 1]`, and `temp[j - 1]` stores `curr[j - 1]`, and not `prev[j - 1]`. \n\nWhat if before writing original `img[i][j - 1]` into `temp[j - 1]` *(which before writing stores `img[i - 1][j - 1]`)*, we store its original value in an integer variable `prev_val`? Turns out this will work, and the missing piece will be filled.\n\nWe have reduced the space used from $m \\cdot n$ to $2n$, then to $n$. \n\n<details>\n<summary>Any further optimization? Click to find out!</summary>\n\n<p>\n\nWhat if we have $n \\gg m$? In this case, we would prefer to store one column *(which will have elements from $m$ rows)* in an array, and not one row *(which will have elements from $n$ columns)* in an array. This will reduce the space used from $n$ to $m$, or precisely to $\\min(m,n)$. \n\nThere are two ways of achieving this.\n\n1. [Transpose the matrix](https://leetcode.com/problems/transpose-matrix/description/), and then use row-order traversal. After obtaining the result, transpose the matrix again to get the original matrix. \n\n    However, \n    \n    - Transposing a non-square matrix in $O(m \\cdot n)$ time takes $O(m \\cdot n)$ space. We aimed to reduce from $O(n)$ to $O(\\min(m,n))$. This indeed has increased space utilization.\n    \n    - The [in-place transpose](https://en.wikipedia.org/wiki/In-place_matrix_transposition) will increase the time complexity from $O(m \\cdot n)$ to $O(m \\cdot n \\cdot \\log(mn))$. This is because the in-place transpose is done by swapping the elements of the matrix. The swapping is done in a cycle. The number of cycles is $O(m \\cdot n)$. The length of each cycle is $O(\\log(m  n))$. Hence, the time complexity of the in-place transpose is $O(m \\cdot n \\cdot \\log(m  n))$.\n\n    Hence, transposing the matrix is not a good idea. Let's see what's the other way.\n\n2. Use column-order traversal instead of row-order traversal. The `temp` will store values of one column and not one row. The `prev_val` will store the original value of the cell in the same column but in the previous row. \n\n    However, two-dimension arrays in most of the programming languages are **[row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order)**, and not **column-major**. *The consecutive elements of a row are contiguous in memory*. Reading memory in contiguous locations is faster than jumping around among locations. Hence, column order traversal will be slower than row order traversal. However, asymptotically both will have the same time complexity.\n\nThus all two ways of reducing space complexity from $O(n)$ to $O(\\min(m,n))$ have their downsides. Hence, we will stick with the space complexity of $O(n)$.\n\n</p>\n</details>\n<br/>\n\n$\\downarrow_{\\text{Portion after realizing that sticking with space complexity of } O(n) \\text{ is better, at least in this approach}}$\n\nWith all the details being discussed minutely, let's see how we can implement this approach.\n\n\n#### Algorithm\n\n1. Save the dimensions of the image. Store the number of rows in `m`, and the number of columns in `n`, as convention used in the problem statement as well.\n\n2. Create an array of size `n`. Let's call this array `temp`.\n\n3. Declare an integer variable `prev_val`, and initialize it with `0`.\n\n4. Iterate over the cells of the image. Let's call the current cell `img[i][j]`.\n    \n    - Initialize two integer variables `sum` and `count` to `0`.\n\n    - If there exists the next row, that is, `i + 1 < m`, then we have to consider all the bottom neighbors.\n      - If there exists the left-bottom neighbor, that is, `j - 1 >= 0`, then add the value of `img[i + 1][j - 1]` to `sum`, and increment `count` by `1`.\n\n      - Add the value of `img[i + 1][j]` to `sum`, and increment `count` by `1`.\n      - If there exists the right-bottom neighbor, that is, `j + 1 < n`, then add the value of `img[i + 1][j + 1]` to `sum`, and increment `count` by `1`.\n\n    - If there exists the next neighbor, that is, `j + 1 < n`, then add the value of `img[i][j + 1]` to `sum`, and increment `count` by `1`.\n\n    - Add the value of `img[i][j]` to `sum`, and increment `count` by `1`.\n\n    - If there exists the previous neighbor, that is, `j - 1 >= 0`, then add the value of `temp[j - 1]` to `sum`, and increment `count` by `1`. The `temp` till index `j - 1` stores the original values of the current row `img[i]` only.\n\n    - If there exists the previous row, that is, `i - 1 >= 0`, then we have to consider all the top neighbors.\n\n      - If there exists the left-top neighbor, that is, `j - 1 >= 0`, then add the value of `prev_val` to `sum`, and increment `count` by `1`. The `prev_val` stores original value of `img[i - 1][j - 1]`.\n\n      - Add the value of `temp[j]` to `sum`, and increment `count` by `1`. The `temp` at index `j` stores the original value of `img[i - 1][j]`.\n      - If there exists the right-top neighbor, that is, `j + 1 < n`, then add the value of `temp[j + 1]` to `sum`, and increment `count` by `1`. The `temp` at index `j + 1` stores original value of `img[i - 1][j + 1]`.\n\n    - Now comes the overwriting part.\n\n    - If there exists the previous row, that is, `i - 1 >= 0`, then the value at `temp[j]` will serve the purpose of the top-left corner sharing neighbor of the next location in iteration, that is, of `img[i][j + 1]`. Hence, store `temp[j]` in `prev_val`.\n\n    - Store the value of `img[i][j]` in `temp[j]`. This will maintain the loop invariant of the definition of `temp`.\n\n    - Overwrite the value of `img[i][j]` with the rounded down value of `sum / count`.\n\n5. Return the `img`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/9b5KtAMB/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"9b5KtAMB\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $m$ be the number of rows in the `img` matrix, and $n$ be the number of columns in the `img` matrix.\n\n* Time complexity: $O(m \\cdot n)$\n\n    We are traversing every cell of the `img` matrix. There are $m \\cdot n$ cells in the `img` matrix.\n\n    In every traversal, we are doing constant time work of computing the smoothed value, overwriting, and updating the `temp` array. \n    \n    Hence, the time complexity of the algorithm is $O(m \\cdot n)$.\n\n* Space complexity: $O(n)$\n\n    The array `temp` is of size $n$. The remaining variables are of constant size. Hence, the space complexity of the algorithm is $O(n)$.\n        \n---\n\n### Approach 3: Constant Space Smoothened Image\n\n#### Intuition\n\nBased on the previous algorithms, we know that if we modify `img[i][j]` in place, we won't be able to use the original `img[i][j]` in subsequent calculations because the value at this position has already been overwritten. Can we somehow store both the pre-modified and post-modified `img[i][j]` values in the same cell? Ideally speaking, it's possible. \n\nConsidering the data structure of `img`, we cannot store two separate numbers in one cell. However, we can represent two independent numbers using a single number.\n\nAssume we have two independent numbers, $p$ and $r$. Let's define another number $Y$ as   \n$Y = p \\cdot X + r$  \nwhere $X$ is a constant.\n\n- To extract $p$ from $Y$, we can do $Y / X$.\n- To extract $r$ from $Y$, we can do $Y \\% X$.\n\nHence, the encoded $Y$ indeed stores two integers of our interest, $p$ and $r$.   \n\nLet's focus more on $X$. What should be the value of $X$? It turns out it depends on $r$. The $r$ is the remainder when we divide $Y$ by $X$. Hence, $r$ can take values from $0$ to $X - 1$.\n>\n> If we divide an integer by $X$, the remainder will be in the range $0$ to $X - 1$. For example, when divided by $8$, the remainder will be in the range $0$ to $7$.\n\nThus our $r$ varies from $0$ to $X - 1$. \n\nNow, let's look at the constraints given in the problem statement.\n\n> `0 <= img[i][j] <= 255`\n\nThus, every cell of the `img` matrix can take values from `0` to `255`. Thus, we can have correspondence between $r$ and `img[i][j]`. To limit the remainder $r$ to `255`, we can choose $X$ to be `256`.\n\nLet's now find out the value of $p$. In a single integer, we wish to store the original value of `img[i][j]`, and the smoothed value of `img[i][j]`. \n\n- The task of storing original value of `img[i][j]` is done by $r$.\n- We can allot $p$ to store the smoothed value of `img[i][j]`.\n\nHence, the summarized correspondence is\n- $Y$ represents two integers encoded in one integer. The two integers are the original value of `img[i][j]`, and smoothed value of `img[i][j]`.\n- $X$ is `256`, the carefully chosen constant.\n- $r$ is the remainder when we divide $Y$ by $X$. The remainder $r$ is the original value of `img[i][j]`.\n- $p$ is the quotient when we divide $Y$ by $X$. The quotient $p$ is the smoothed value of `img[i][j]`.\n\nHence, our algorithm will be \n- For every cell, assume it stores $Y$ (and not $r$)\n- Extract $r$, the original value of `img[i][j]`, from $Y$ using $Y \\% 256$\n- Compute smoothened value using neighbors of `img[i][j]`. For computing a smoothened value, we need the original value of neighbors as well, which will be extracted using the same logic. The smoothened value will be stored in $p$.\n- Encode the smoothened value in $Y$ itself by updating it as $Y = p \\cdot 256 + r$. \n- Once every $Y$ of the matrix is encoded with smoothened value, from it extract smoothened value $p$ by doing $Y / 256$. \n\nHence, the algorithm sounds simple. However, there is a word of caution. Multiplying integers may cause overflow if multiplication exceeds the range of integers. For this, let's find the minimum and maximum value our encoded $Y$ can take.\n\n$\\boxed{Y = p \\cdot 256 + r}$\n\n- $p$ is the smoothened value which is an average of at most nine values ranging from $0$ to $255$. Hence, the average $p$ will also lie between $0$ to $255$.\n\n- $r$ also lies between $0$ to $255$.\n\n- The minimum value of $Y$ is $0 \\cdot 256 + 0 = 0$.\n- The maximum value of $Y$ is $255 \\cdot 256 + 255 = 65535$ represented as $2^{16} - 1$, which is reasonably less than the maximum value of an integer, which is $2^{31} - 1$.\n\nHence, we need not to worry about overflow in this particular problem.\n\nWith all the details being discussed minutely, let's see how we can implement this approach.\n\n#### Algorithm\n\n1. Save the dimensions of the image. Store the number of rows in `m`, and the number of columns in `n`, as convention used in the problem statement as well.\n\n2. Iterate over the cells of the image. Let's call the current cell `img[i][j]`.\n    \n    - Initialize two integer variables `sum` and `count` to `0`.\n\n    - Iterate over all plausible nine indices `(x, y)`. The `(x, y)` are\n      - `(i - 1, j - 1)`\n\n      - `(i - 1, j)`\n      - `(i - 1, j + 1)`\n      - `(i, j - 1)`\n      - `(i, j)`\n      - `(i, j + 1)`\n      - `(i + 1, j - 1)`\n      - `(i + 1, j)`\n      - `(i + 1, j + 1)` \n        \n      If the indices form a valid neighbor, then extract the original value of `img[x][y]` using `img[x][y] % 256`, and add it to `sum`. Increment `count` by `1`.\n    \n    - Encode the smoothed value in `img[i][j]` as `img[i][j] += (sum / count) * 256 `.\n\n3. Traverse again over the cells of the image. Let's call the current cell `img[i][j]`. Extract the smoothed value from `img[i][j]` using `img[i][j] / 256`, and store it in `img[i][j]`.\n\n4. Return the `img`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/82csSf8n/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"82csSf8n\"></iframe>\n\n**Point to Ponder:** With the number `256`, we are doing three operations\n- Taking modulo\n- Multiplying\n- Dividing\n\nNow, `256` is special in the sense that it is a power of two. Is there a faster way to do these three operations? Readers are encouraged to think about it.\n\n#### Complexity Analysis\n\nLet $m$ be the number of rows in the `img` matrix, and $n$ be the number of columns in the `img` matrix.\n\n* Time complexity: $O(m \\cdot n)$\n\n    We are traversing every cell of the `img` matrix. There are $m \\cdot n$ cells in the `img` matrix.\n    \n    For each cell, we are iterating over all plausible nine indices. There are at most nine indices for each cell. At each index, we are doing constant time arithmetic operations.\n\n    Again, we are traversing over all the cells of the `img` matrix to extract the smoothed value from the encoded value. \n    \n    Hence, the time complexity of the algorithm is $O((m \\cdot n \\cdot 9) + (m \\cdot n))$, which is $O(m \\cdot n)$.\n    \n* Space complexity: $O(1)$\n\n    We are not using any extra space. Smoothened Values are encoded and extracted in the existing integer value of `img`. Hence, the space complexity of the algorithm is $O(1)$.\n        \n---\n\n### Approach 4: Bit Manipulation\n\n#### Intuition\n\nLet's again analyze the constraints given in the problem statement.\n\n> `0 <= img[i][j] <= 255`\n\nAn integer, in most of the programming languages, is represented using 32 bits. The `255` is `11111111` in binary. All numbers from `0` to `255` require at most 8 bits to represent them. \n\nHence, out of these 32 bits, only the least significant 8 bits are used to represent the value of `img[i][j]`. We, to avoid any inconsistency, won't alter the most significant bit, as it is often used to represent the sign of the integer. Hence, the 23 bits are free to use.\n\n![unused](../Figures/661/661_slide_images_used/Slide8.PNG)\n\nThis suggests the idea that in these 23 unused bits, we can store the smoothed value of `img[i][j]`. This we can achieve by using bit-manipulation. In bit manipulation, we use the bit-wise operators. \n\n<details> <summary> <b> For quick review of bit-wise operators, click here </b> </summary>\n\n<p>\n\n- **NOT:** Bitwise NOT is a unary operator that flips the bits of the integer. If the current bit is $0$, it will change it to $1$ and vice versa. The symbol of the bitwise NOT operator is tilde (`~`).\n\n    ```\n    N = 5 = 101 (in binary)\n    ~N = ~(101) = 010 = 2 (in decimal)\n    ```\n\n- **AND:** If both bits in the compared position of the operand are $1$, the bit in the resulting bit pattern is $1$, otherwise $0$. The symbol of the bitwise AND operator is ampersand (`&`).\n\n    ```\n    A = 5 = 101 (in binary) \n    B = 1 = 001 (in binary) \n    A & B = 101 & 001 = 001 = 1 (in decimal)\n    ```\n\n- **OR:** If both bits in the compared position of the operand are $0$, the bit in the resulting bit pattern is $0$, otherwise $1$. The symbol of the bitwise OR operator is pipe (`|`).\n\n    ```\n    A = 5 = 101 (in binary) \n    B = 1 = 001 (in binary) \n    A | B = 101 | 001 = 101 = 5 (in decimal)\n    ```\n\n- **XOR:** In bitwise XOR if both bits are the same, the result will be $0$, otherwise $1$. The symbol of the bitwise XOR operator is caret (`^`).\n\n    ```\n    A = 5 = 101 (in binary) \n    B = 1 = 001 (in binary) \n    A ^ B = 101 ^ 001 = 100 = 4 (in decimal)\n    ```\n\n- **Left Shift:** The Left shift operator is a binary operator that shifts bits to the left by a certain number of positions and appends `0` at the right side. One left shift is equivalent to multiplying the bit pattern with $2$. The symbol of the left shift operator is `<<`.\n\n  `x << y` means left shift `x` by `y` bits, which is equivalent to multiplying `x` with $2^y$.\n\n    ```\n    A = 1 = 001 (in binary) \n    A << 1 = 001 << 1 = 010 = 2 (in decimal)\n    A << 2 = 001 << 2 = 100 = 4 (in decimal)\n    \n    B = 5 = 00101 (in binary)\n    B << 1 = 00101 << 1 = 01010 = 10 (in decimal)\n    B << 2 = 00101 << 2 = 10100 = 20 (in decimal)\n    ```\n\n- **Right Shift:** The Right shift operator is a binary operator that shifts bits to the right by a certain number of positions and appends `0` at the left side. One right shift is equivalent to dividing the bit pattern with $2$. The symbol of the right shift operator is `>>`.\n\n  `x >> y` means right shift `x` by `y` bits, which is equivalent to dividing `x` with $2^y$.\n\n    ```\n    A = 4 = 100 (in binary) \n    A >> 1 = 100 >> 1 = 010 = 2 (in decimal)\n    A >> 2 = 100 >> 2 = 001 = 1 (in decimal)\n    A >> 3 = 100 >> 3 = 000 = 0 (in decimal)\n    \n    B = 5 = 00101 (in binary)\n    B >> 1 = 00101 >> 1 = 00010 = 2 (in decimal)\n    ```\n\n</p>\n\n</details>\n\n<br/>\n  \n$\\downarrow_{\\text{Portion After Review}}$\n\n\nNow the smoothed value is an average of nine values ranging from `0` to `255`. Hence, the average will also lie between `0` to `255`. Thus, the smoothed value will also require at most 8 bits to represent it. This we can store together as follows.\n\n![two_store](../Figures/661/661_slide_images_used/Slide9.PNG)\n\n**How do we store smoothened corresponding values?** Let's see.\n\nInitially, the smoothened corresponding value was a separate integer, as shown in the figure below.   \n![separate](../Figures/661/661_slide_images_used/Slide10.PNG)\n\nWe can left shift (using the `<<` operator ) the integer so that the orientation now looks like as follows.\n![left_shift](../Figures/661/661_slide_images_used/Slide11.PNG)\n\nNow there is a property of bitwise OR (`|`) operator. `x | 0 = x`. In the context of the diagram, doing bitwise OR of both these separate integers\n- The most significant 16 bits will remain 0 because both integers have 0 in those bits.\n- The least significant 8 bits will store the values of `img[i][j]` \n- The remaining 8 bits will store the values of the smoothened corresponding value.   \n\n![or](../Figures/661/661_slide_images_used/Slide12.PNG)\n\n**How can we extract the original value of `img[i][j]` from this mixed integer?** \n\nIn other words, \n\n- We wish to set all except the least significant 8 bits to 0. \n    \n    The bitwise AND (`&`) operator has property of `x & 0 = 0`. Thus to set the first 24 bits to `0`, we can do bitwise AND with an integer that has the first 24 bits as `0`\n    \n- We wish to retain the least significant 8 bits as it is.  \n\n    The bitwise AND (`&`) operator has property of `x & 1 = x`. Thus to retain the last 8 bits as it is, we can do bitwise AND with an integer that has the last 8 bits as `1`.\n\nThus, the integer with which we can do bitwise AND (`&`) to extract the original value of `img[i][j]` is `00000000000000000000000011111111`, which is `255` in decimal, and `11111111` in binary.\n\n![and](../Figures/661/661_slide_images_used/Slide13.PNG)\n\n\n**How can we extract the smoothened value from this mixed integer, after we are done with computing all the smoothened values?**\n\nAs done above, we perhaps can do bitwise AND (`&`) with `00000000000000001111111100000000`, which is `65280` in decimal, and `1111111100000000` in binary. This will retain the smoothened value bits as it is, turning off all other bits.\n\nAfter that, to get the smoothened value, we can right shift (using the`>>` operator ) the integer by 8 bits (To encode, we did a left shift by 8 bits). This will bring the smoothened value to the least significant 8 bits.\n\nHowever, readers can appreciate that only the right shift is sufficient to extract the smoothened value. \n\n![right_shift](../Figures/661/661_slide_images_used/Slide14.PNG)\n\nHence, our algorithm will be\n- For every cell, assume it stores the mixed-integer.\n- Extract the original value of `img[i][j]` using bitwise AND (`&`) with `255`.\n- Compute smoothened value using neighbors of `img[i][j]`. For computing the smoothened value, we need the original value of neighbors as well, which will be extracted using the same logic.\n- Left shift (`<<`) the smoothened value by 8 bits, and encode it in the mixed integer using bitwise OR (`|`) operator.\n- Once every mixed integer of the matrix is encoded with the smoothened value, extract the smoothened value using the right shift (`>>`) operator.\n\n> The bit manipulation works because we have only 8 bits per pixel (abbreviated as \"bpp\"). The \"bpp\" is the number of bits used to represent the color of a single pixel in a bitmapped image or video frame buffer. Hence, we can use the remaining bits to store the smoothened value.\n\nReaders can appreciate the one-to-one correspondence in this approach and [previous approach](#approach-3-constant-space-smoothened-image)\n\n- Bitwise AND (`&`) with `255` $\\equiv$ modulo by `256`\n\n- Left shift (`<<`) by 8 bits $\\equiv$ multiply by `256`\n\n- Bitwise OR (`|`) of smoothened value with `img[i][j]` provided least significant 8 bits of the left-shifted smoothened value are `0` $\\equiv$ add `img[i][j]`\n\n- Right shift (`>>`) by 8 bits $\\equiv$ divide by `256`\n\nThis was hinted at **[Point to Ponder](#implementation-2)** in previous approach.\n\nThe bit-wise operators are faster than arithmetic operators. Hence, this approach is faster than the [previous approach](#approach-3-constant-space-smoothened-image).\n\n#### Algorithm\n\n1. Save the dimensions of the image. Store the number of rows in `m`, and the number of columns in `n`, as convention used in the problem statement as well.\n\n2. Iterate over the cells of the image. Let's call the current cell `img[i][j]`.\n    \n    - Initialize two integer variables `sum` and `count` to `0`.\n\n    - Iterate over all plausible nine indices `(x, y)`. The `(x, y)` are\n      - `(i - 1, j - 1)`\n\n      - `(i - 1, j)`\n      - `(i - 1, j + 1)`\n      - `(i, j - 1)`\n      - `(i, j)`\n      - `(i, j + 1)`\n      - `(i + 1, j - 1)`\n      - `(i + 1, j)`\n      - `(i + 1, j + 1)` \n        \n      If the indices form a valid neighbor, then extract the original value of `img[x][y]` using `img[x][y] & 255`, and add it to `sum`. Increment `count` by `1`.\n            \n    - Encode the smoothed value in `img[i][j]` as `img[i][j] |= (sum / count) << 8 `.\n\n3. Traverse again over the cells of the image. Let's call the current cell `img[i][j]`. Extract the smoothed value from `img[i][j]` using `img[i][j] >> 8`, and store it in `img[i][j]`\n\n4. Return the `img`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/HdLbENr2/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"HdLbENr2\"></iframe>\n\n**Implementation Notes:** Different programming languages have different notations of bitwise operators. For example, for the bitwise NOT operator, we have the following notations:  \n- [C++](https://en.cppreference.com/w/cpp/language/operator_arithmetic) uses `~` \n- [Go](https://go.dev/ref/spec) uses unary `^` operator\n- [Elixir](https://hexdocs.pm/elixir/1.13.0/Bitwise.html) uses `~~~`, or `bnot`\n- [Rust](https://doc.rust-lang.org/book/appendix-02-operators.html) uses `!`\n- In [Kotlin](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/inv.html), we can use `inv()` function\n\n\n#### Complexity Analysis\n\nLet $m$ be the number of rows in the `img` matrix, and $n$ be the number of columns in the `img` matrix.\n\n* Time complexity: $O(m \\cdot n)$\n\n    We are traversing every cell of the `img` matrix. There are $m \\cdot n$ cells in the `img` matrix.\n    \n    For each cell, we are iterating over all plausible nine indices. There are at most nine indices for each cell. At each index, we are doing constant time bitwise operations.\n\n    > We are taking bitwise AND (`&`) of `sum` and `255`. Now there can be at most $32$ (or any other constant number) bits in an integer. Hence, the `&` operator will be done at most $32$ times. Thus, the time complexity of the bitwise AND (`&`) operator is $O(32)$, which is $O(1)$.\n\n    > We are left shifting (`<<`) an integer (`sum / count`) by `8` bits.   \n    > \n    > Left shifting $1$ bit in a signed integer is done by \n    > - Assigning to every non-signed bit the value of the bit to its right side\n    >\n    > - The LSB doesn't have any bit to its right side, so it is assigned `0`\n    > \n    > Hence, there will be at most $31$ such assignments in one left shift, since in a signed integer, the MSB is used to represent the sign of the integer, and it is retained as it is in the left shift. \n    >\n    > Hence, number of assignments in one left shift is $31$, and in $8$ left shifts, it is $31 \\cdot 8 = 248$. Thus, the time complexity of the left shift (`<<`) operator is $O(248)$, which is $O(1)$.\n    \n    > We are also doing bitwise OR (`|`) of two integers `img[i][j]` and `(sum / count) << 8`. Now there can be at most $32$ (or any other constant number) bits in an integer. Hence, the `|` operator will be done at most $32$ times. Thus, the time complexity of the bitwise OR (`|`) operator is $O(32)$, which is $O(1)$.\n\n    Again, we are traversing over all the cells of the `img` matrix to extract the smoothed value from the encoded value using the bitwise operator. \n\n    > We are right shifting (`>>`) an integer (`img[i][j]`) by `8` bits.\n    > \n    > Right shifting $1$ bit in a signed integer is done by\n    > - Assigning to every non-signed bit the value of the bit to its left side, except for the *second most significant bit*\n    > \n    > - The *second most significant bit* has to its left side the *most significant bit*, which is used to represent the sign of the integer. Hence, the *second most significant bit* is assigned the value of `0`\n    > \n    > Hence, there will be at most $31$ such assignments in one right shift, since in a signed integer, the MSB is used to represent the sign of the integer, and it is retained as it is in the right shift.\n    >\n    > Hence, number of assignments in one right shift is $31$, and in $8$ right shifts, it is $31 \\cdot 8 = 248$. Thus, the time complexity of the right shift (`>>`) operator is $O(248)$, which is $O(1)$.\n    \n    Hence, the time complexity of the algorithm is $O((m \\cdot n \\cdot 9) + (m \\cdot n))$, which is $O(m \\cdot n)$.\n    \n* Space complexity: $O(1)$\n\n    We are not using any extra space. Smoothened values are encoded and extracted in the existing integer value of `img`. Hence, the space complexity of the algorithm is $O(1)$.\n        \n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:\n    m = len(M)\n    n = len(M[0])\n    ans = [[0 for j in range(n)] for i in range(m)]\n\n    for i in range(m):\n      for j in range(n):\n        ones = 0\n        count = 0\n        for y in range(max(0, i - 1), min(m, i + 2)):\n          for x in range(max(0, j - 1), min(n, j + 2)):\n            ones += M[y][x]\n            count += 1\n        ans[i][j] = ones // count\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[][] imageSmoother(int[][] M) {\n    final int m = M.length;\n    final int n = M[0].length;\n    int ans[][] = new int[m][n];\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        int ones = 0;\n        int count = 0;\n        for (int y = Math.max(0, i - 1); y < Math.min(m, i + 2); ++y)\n          for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x) {\n            ones += M[y][x];\n            ++count;\n          }\n        ans[i][j] = ones / count;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<vector<int>> imageSmoother(vector<vector<int>>& M) {\n    const int m = M.size();\n    const int n = M[0].size();\n    vector<vector<int>> ans(m, vector<int>(n));\n\n    for (int i = 0; i < m; ++i)\n      for (int j = 0; j < n; ++j) {\n        int ones = 0;\n        int count = 0;\n        for (int x = max(0, i - 1); x < min(m, i + 2); ++x)\n          for (int y = max(0, j - 1); y < min(n, j + 2); ++y) {\n            ones += M[x][y];\n            ++count;\n          }\n        ans[i][j] = ones / count;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/661.html",
    "category": "Algorithms",
    "acceptance_rate": 68.26039216850039,
    "topics": [
      "Array",
      "Matrix"
    ],
    "hints": [],
    "likes": 1190,
    "dislikes": 2966,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"184K\", \"totalSubmission\": \"269.6K\", \"totalAcceptedRaw\": 184014, \"totalSubmissionRaw\": 269576, \"acRate\": \"68.3%\"}",
    "title_pt": "Suavizador de Imagem",
    "description_pt": "<p>Um <strong>suavizador de imagem</strong> é um filtro de tamanho <code>3 x 3</code> que pode ser aplicado a cada célula de uma imagem, arredondando para baixo a média da célula e das oito células ao redor (isto é, a média das nove células no suavizador azul). Se uma ou mais das células ao redor de uma célula não estiverem presentes, não as consideramos na média (isto é, a média das quatro células no suavizador vermelho).</p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smoother-grid.jpg\" style=\"width: 493px; height: 493px;\" />\n<p>Dada uma matriz inteira <code>m x n</code> <code>img</code> representando a escala de cinza de uma imagem, retorne <em>a imagem após aplicar o suavizador em cada célula dela</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smooth-grid.jpg\" style=\"width: 613px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> img = [[1,1,1],[1,0,1],[1,1,1]]\n<strong>Saída:</strong> [[0,0,0],[0,0,0],[0,0,0]]\n<strong>Explicação:</strong>\nPara os pontos (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nPara os pontos (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nPara o ponto (1,1): floor(8/9) = floor(0.88888889) = 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/smooth2-grid.jpg\" style=\"width: 613px; height: 253px;\" />\n<pre>\n<strong>Entrada:</strong> img = [[100,200,100],[200,50,200],[100,200,100]]\n<strong>Saída:</strong> [[137,141,137],[141,138,141],[137,141,137]]\n<strong>Explicação:</strong>\nPara os pontos (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nPara os pontos (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nPara o ponto (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == img.length</code></li>\n\t<li><code>n == img[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 200</code></li>\n\t<li><code>0 &lt;= img[i][j] &lt;= 255</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "662",
    "paidOnly": false,
    "title": "Maximum Width of Binary Tree",
    "titleSlug": "maximum-width-of-binary-tree",
    "url": "https://leetcode.com/problems/maximum-width-of-binary-tree",
    "description_url": "https://leetcode.com/problems/maximum-width-of-binary-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>\n\n<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>\n\n<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.</p>\n\n<p>It is <strong>guaranteed</strong> that the answer will in the range of a <strong>32-bit</strong> signed integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/width1-tree.jpg\" style=\"width: 359px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [1,3,2,5,3,null,9]\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> The maximum width exists in the third level with length 4 (5,3,null,9).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/14/maximum-width-of-binary-tree-v3.jpg\" style=\"width: 442px; height: 422px;\" />\n<pre>\n<strong>Input:</strong> root = [1,3,2,5,null,null,9,6,null,7]\n<strong>Output:</strong> 7\n<strong>Explanation:</strong> The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/width3-tree.jpg\" style=\"width: 289px; height: 299px;\" />\n<pre>\n<strong>Input:</strong> root = [1,3,2,5]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The maximum width exists in the second level with length 2 (3,2).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-width-of-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int widthOfBinaryTree(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n\n    long ans = 0;\n    dfs(root, 0, 1, {}, ans);\n    return ans;\n  }\n\n private:\n  void dfs(TreeNode* root, int level, long index, vector<long>&& startOfLevel,\n           long& ans) {\n    if (root == nullptr)\n      return;\n    if (startOfLevel.size() == level)\n      startOfLevel.push_back(index);\n\n    ans = max(ans, index - startOfLevel[level] + 1);\n    dfs(root->left, level + 1, index * 2, move(startOfLevel), ans);\n    dfs(root->right, level + 1, index * 2 + 1, move(startOfLevel), ans);\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int widthOfBinaryTree(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    int ans = 0;\n    Deque<Pair<TreeNode, Integer>> q = new ArrayDeque<>(); // {node, index}\n    q.offer(new Pair<>(root, 1));\n\n    while (!q.isEmpty()) {\n      final int offset = q.peekFirst().getValue() * 2;\n      ans = Math.max(ans, q.peekLast().getValue() - q.peekFirst().getValue() + 1);\n      for (int sz = q.size(); sz > 0; --sz) {\n        final TreeNode node = q.peekFirst().getKey();\n        final int index = q.pollFirst().getValue();\n        if (node.left != null)\n          q.offer(new Pair<>(node.left, index * 2 - offset));\n        if (node.right != null)\n          q.offer(new Pair<>(node.right, index * 2 + 1 - offset));\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int widthOfBinaryTree(TreeNode* root) {\n    if (root == nullptr)\n      return 0;\n\n    int ans = 0;\n    queue<pair<TreeNode*, int>> q{{{root, 1}}};  // {node, index}\n\n    while (!q.empty()) {\n      const int offset = q.front().second * 2;\n      ans = max(ans, q.back().second - q.front().second + 1);\n      for (int sz = q.size(); sz > 0; --sz) {\n        const auto [node, index] = q.front();\n        q.pop();\n        if (node->left)\n          q.emplace(node->left, index * 2 - offset);\n        if (node->right)\n          q.emplace(node->right, index * 2 + 1 - offset);\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/662.html",
    "category": "Algorithms",
    "acceptance_rate": 43.99908344712937,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Breadth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 9178,
    "dislikes": 1260,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"474.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 474281, \"totalSubmissionRaw\": 1077933, \"acRate\": \"44.0%\"}",
    "title_pt": "Largura Máxima de uma Árvore Binária",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>a <strong>largura máxima</strong> da árvore dada</em>.</p>\n\n<p>A <strong>largura máxima</strong> de uma árvore é a largura máxima entre todos os níveis.</p>\n\n<p>A <strong>largura</strong> de um nível é definida como o comprimento entre os nós extremos (o nó mais à esquerda e o nó mais à direita não nulos), onde os nós nulos entre os nós extremos que estariam presentes em uma árvore binária completa estendendo-se até esse nível também são contados no cálculo do comprimento.</p>\n\n<p>É <strong>garantido</strong> que a resposta estará no intervalo de um inteiro com sinal de <strong>32 bits</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/width1-tree.jpg\" style=\"width: 359px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,3,2,5,3,null,9]\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> A largura máxima existe no terceiro nível com comprimento 4 (5,3,null,9).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2022/03/14/maximum-width-of-binary-tree-v3.jpg\" style=\"width: 442px; height: 422px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,3,2,5,null,null,9,6,null,7]\n<strong>Saída:</strong> 7\n<strong>Explicação:</strong> A largura máxima existe no quarto nível com comprimento 7 (6,null,null,null,null,null,7).\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/03/width3-tree.jpg\" style=\"width: 289px; height: 299px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,3,2,5]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A largura máxima existe no segundo nível com comprimento 2 (3,2).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 3000]</code>.</li>\n\t<li><code>-100 &lt;= Node.val &lt;= 100</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "664",
    "paidOnly": false,
    "title": "Strange Printer",
    "titleSlug": "strange-printer",
    "url": "https://leetcode.com/problems/strange-printer",
    "description_url": "https://leetcode.com/problems/strange-printer/description/",
    "description": "<p>There is a strange printer with the following two special properties:</p>\n\n<ul>\n\t<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>\n\t<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>\n</ul>\n\n<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aaabbb&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;bbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aba&quot;\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;b&quot; from the second place of the string, which will cover the existing character &#39;a&#39;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/strange-printer/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview  \n\nWe have a printer designed to produce a string of lowercase English characters and we want to return the least number of turns it would take to print a given string. Normally, you would think the number of turns would be the number of characters in the string, but this printer has some bonus features that will let us reduce the number of turns. Instead of counting each key stroke as a turn, we count each time we change the character we are printing as a turn, and we can go back over what we've already typed.\n\nThe wording of the problem description, \"The printer can **only** print a sequence of the same character each time.\", makes it sound like a weird restriction, but it's really a loophole that will let us reduce the number of turns it takes to print the string when we combine it with the override feature. \n\nThe second bullet point from the problem description is basically saying that we can go back and write over characters we have already printed in previous steps. You could think about it like using an old school typewriter: it always moves left to right, you have unlimited white-out, and for some reason you want to switch keys as few times as possible. \n\nAs people have pointed out, no one wants to use this printer but we'll have to work with what we have. \n\nFor example, consider the string `s` = `aba`. We can print it in two ways:\n\nMethod 1:\n- Turn 1: Print `a`.\n- Turn 2: Print `b` after `a`.\n- Turn 3: Print `a` after `b`.\n\nMethod 2:\n- Turn 1: Print `aaa`.\n- Turn 2: Print `b` in the middle.\n\nIn this case, we'll return `2` as the least number of steps required.\n\nOur clue to use dynamic programming is the requirement to find the least number of turns to achieve a goal. This suggests both optimal substructure and overlapping subproblems, where finding the minimum turns for different parts of the string often requires repeated calculations. Defining a state to represent the minimum turns needed to print a substring enables us to efficiently build the solution.\n\nThis is a difficult problem to solve, even after we understand what it's asking, so don't worry if it takes time to understand how to solve it. If you're not familiar with dynamic programming concepts, we recommend exploring the LeetCode Dynamic Programming [Explore Card](https://leetcode.com/explore/learn/card/dynamic-programming/630/an-introduction-to-dynamic-programming/4034/) and solving some beginner level problems before returning to this editorial. \n\n---\n\n### Approach 1: Top Down Dynamic Programming (Memoization)\n\n#### Intuition\n\nInstead of analyzing the string from left to right, we want to consider the entire string and identify segments we can print in one turn. If the character at the end of one segment matches the start of the next, you can potentially print them in one turn and then override the middle character(s) in a later turn. We can see this done in Example 2 of the problem description. We'll explore all possible ways to split the string and find the combination that requires the fewest turns.\n\nThis decision-making process suggests a recursive structure for our solution. The recursive function will break down the string into smaller substrings and determine the minimum number of turns required for each substring. We will consider different ways of breaking the string and choose the most efficient option. For example:\n\n```\ns = \"cabad\"\nTwo possible ways to split this string are:\n1. \"c\" + \"aba\" + \"d\"\n2. \"cab\" + \"ad\"\nIn option (1), the \"c\" and \"d\" each take 1 turn to print, while \"aba\" takes 2 turns (as previously explained), resulting in a total of 4 turns.\nIn option (2), \"cab\" takes 3 turns, and \"ad\" takes 2 turns, totaling 5 turns.\nThus, the recursive function will prefer the first option.\n```\n\nWith this understanding, we develop our algorithm step by step. To optimize runtime, we first remove consecutive duplicate characters in the input string. This reduction doesn't change the minimum number of turns needed but can significantly decrease the problem size. For example, it only takes one turn to print \"a\" when printing \"aaabbb\" since consecutive identical characters can be printed in a single turn.\n\nWe define a function `minimumTurns` that calculates the minimum number of turns needed to print the substring from index `start` to `end`. The recursive relation is as follows:\n\n- **Base Case**: If `start` > `end`, the substring is empty and requires 0 turns.\n- **Initial Case**: Start with the worst-case scenario: `1 + minimumTurns(start + 1, end)`. This means printing the first character separately and then printing the rest with no optimization applied. We initially set `minTurns` to this result.\n- **Optimization Case**: To optimize, we look for matching characters. We break down the substring into two parts. If the first and last characters of the first part match, we can use the printer’s first property to save one turn by printing them together. If this approach results in fewer turns than `minTurns`, we update `minTurns`. Finally, `minTurns` will reflect the minimum turns required for the substring between `start` and `end`.\n\nCheck out this slideshow to visualize how matching first and last characters helps us save 1 turn:\n\n!?!../Documents/664_re/slideshow.json:1022,782!?!\n\nWhile the recursive solution alone has exponential time complexity, dynamic programming can optimize this approach. We avoid redundant computations by storing the results of sub-problems in a cache (a technique known as memoization).\n\n```\ns = \"leetcode\"\nTwo possible ways to split s are:\n\"le\"|\"et\"|\"co\"|\"de\" and \"l\"|\"eet\"|\"co\"|\"de\"\nNotice that \"co\"|\"de\" is common in both cases, indicating an overlapping subproblem.\n```\n\nWe use a 2-D array `memo`, where `memo[start][end]` stores the minimum turns for the substring from `start` to `end`. This ensures that previously evaluated sub-problems are quickly accessed from the cache, saving computation time.\n\nFinally, we call `minimumTurns` with the endpoints of the input string `s`, providing the required minimum number of turns to print the string.\n\n#### Algorithm\n\nMain method `strangePrinter`:\n\n- Call the `removeDuplicates` method to remove consecutive duplicate characters from the string `s`.\n- Set a variable `n` to the length of `s`.\n- Initialize a 2-D array `memo` to store the minimum number of turns required to print substrings of `s`.\n- Call the `minimumTurns` recursive method with arguments `start` = `0` and `end` = `n - 1`. Return the result.\n\nHelper method `minimumTurns`:\n\n- Define a method `minimumTurns` with parameters: `start`, `end`, the string `s`, and 2-D dp array `memo`.\n- Check if the `start` index is greater than the `end` index. If true, return `0`.\n- Check if `memo[start][end]` already contains a result. If so, return the result.\n- Initialize a variable `minTurns` to to `1 + minimumTurns(start + 1, end)`, which is the worst-case scenario.\n- Iterate through the substring from `start + 1` to `end`. For each index `k`:\n  - Check if the character `s[k]` matches the character at `s[start]`. If so:\n    - Calculate `turnsWithMatch` as the sum of `minimumTurns(start, k - 1)` and `minimumTurns(k + 1, end)`.\n    - Update `minTurns` to be the minimum of its current value and `turnsWithMatch`.\n- Store the computed `minTurns` value in `memo[start][end]`.\n- Return `minTurns`.\n\nHelper method `removeDuplicates`:\n\n- Define a method `removeDuplicates` with the string `s` as a parameter.\n- Create a string `uniqueChars` to store characters without consecutive duplicates.\n- Iterate each character of `s`. For each index `i`:\n  - Add the `currentChar` to `uniqueChars`.\n  - Increment `i` till `s[i]` is not equal to `currentChar`.\n- Return `uniqueChars`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5fu8xCML/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5fu8xCML\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string `s`. \n\n- Time complexity: $O(n^3)$\n\n    The `removeDuplicates` method iterates through the string once, resulting in a time complexity of $O(n)$. However, the main complexity arises from the recursive `minimumTurns` function. \n\n    In the worst case, the algorithm considers all possible substrings of the input string. For a string of length $n$, there are $\\frac{n(n+1)}{2}$ possible substrings. For each substring, the algorithm iterates through it once to find matching characters, which is $O(n)$. Thus, the overall time complexity is $O\\left(n \\cdot \\frac{n(n+1)}{2}\\right)$, which simplifies to $O(n^3)$.\n\n    Therefore, the total time complexity of the algorithm is $O(n) + O(n^3) = O(n^3)$.\n\n- Space complexity: $O(n^2)$\n\n    The 2-D array `minTurns` has dimensions $n \\times n$, requiring $O(n^2)$ space. Additionally, in the worst case, the depth of the recursive call stack can reach up to $n$.\n\n    Hence, the overall space complexity of the algorithm is $O(n^2) + O(n) = O(n^2)$.\n\n---\n\n### Approach 2: Bottom Up Dynamic Programming (Tabulation)\n\n#### Intuition\n\nIn our previous approach, we used a top down recursive solution with memoization, which, while effective, can lead to stack overflow issues with very large inputs due to deep recursion. To optimize further, we’ll switch to a bottom up dynamic programming approach to eliminate recursion.\n\nInstead of solving the problem from the top down (starting with the entire string and recursively breaking it into smaller parts), we will build our solution from the bottom up. This involves solving the smallest sub-problems first and progressively combining their solutions to address larger sub-problems until we solve the full problem.\n\nWe’ll use a 2-D array `minTurns` of size `n x n`, where `minTurns[i][j]` represents the minimum number of turns needed to print the substring from index `i` to `j` (inclusive).\n\nFirst, we set up the base case: substrings of length 1 require 1 turn to print a single character.\n\nNext, we address substrings of all possible lengths from 2 to `n`. For each length, we examine all possible starting positions for substrings of that length. We explore all possible ways to split each substring to determine the minimum number of turns required.\n\nWhen considering a split, if the character at the split matches the character at the end of the substring, we can reduce the number of turns needed by printing these characters together. The minimum number of turns required for each substring is derived from the smallest value obtained across all possible splits.\n\nAfter populating the table, the minimum number of turns needed to print the entire input string `s` will be stored in `minTurns[0][n-1]`.\n\n#### Algorithm\n\nMain method `strangePrinter`:\n\n- Call the `removeDuplicates` method to remove consecutive duplicate characters from the string `s`.\n- Set a variable `n` to the length of the `s`.\n- Initialize a 2-D array `minTurns` to store the minimum number of turns required to print substrings of `s`.\n- To set the base case, iterate `i` from `0` to `n`:\n  - Set `minTurns[i][i]` to `1`.\n- Use a loop to iterate over increasing lengths of substrings, starting from `2` and going up to `n`:\n  - For each substring `length`, iterate over possible starting indices `start` from `0` to `n - length + 1`:\n    - Calculate the ending index `end` as `start + length - 1`.\n    - Set `minTurns[start][end]` to `length`, assuming the worst case where each character is printed separately.\n    - Try all splits of the substring between `0` to `length-2`:\n      - Initialize `totalTurns` as the sum of `minTurns[start][start + split]` and`minTurns[start + split + 1][end]`.\n      - If the character at the split position `s[start + split]` matches the character at the end `s[end]`, reduce `totalTurns` by `1`.\n      - Update `minTurns[start][end]` to be the minimum of its current value and `totalTurns`.\n- Return `minTurns[0][n - 1]` as our answer.\n\nHelper method `removeDuplicates`:\n\n- Define a method `removeDuplicates` with the input string `s` as a parameter.\n- Initialize a string `uniqueChars` to store characters without consecutive duplicates.\n- Loop through each character of `s`. For each index `i`:\n  - Add the `currentChar` to `uniqueChars`.\n  - Increment `i` till `s[i]` is not equal to `currentChar`.\n- Return `uniqueChars`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/ivdnsqVH/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"ivdnsqVH\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string `s`.\n\n* Time complexity: $O(n^3)$\n\n    The initialization of the `minTurns` 2-D array and setting up base cases both take $O(n)$ time. Filling the DP table involves three nested loops:\n\n    1. The outer loop iterates over substring lengths from 2 to $n$, running $n−1$ times.\n    2. The second loop iterates over possible starting indices for each substring, running up to $n$ times.\n    3. The innermost loop iterates over possible split points, also running up to $n$ times.\n\n    As a result, the time complexity for filling the DP table is $O((n-1) \\cdot n \\cdot n)$, which simplifies to $O(n^3)$. Additionally, the `removeDuplicates` method, which iterates through the string `s` once, has a linear complexity of $O(n)$. \n\n    Therefore, the overall time complexity of the algorithm is $2 \\cdot O(n) + O(n^3) = O(n^3)$.\n\n* Space complexity: $O(n^2)$\n\n    The `minTurns` 2-D array, with dimensions $n \\times n$, requires $O(n^2)$ space. The processed string `s` (after removing duplicates) takes up $O(n)$ space. \n\n    Consequently, the overall space complexity of the algorithm is $O(n^2) + O(n) = O(n^2)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution {\n public:\n  int strangePrinter(string s) {\n    if (s.empty())\n      return 0;\n\n    const int n = s.size();\n    // dp[i][j] := min # of turns to print s[i..j]\n    vector<vector<int>> dp(n, vector<int>(n, n));\n\n    for (int i = 0; i < n; ++i)\n      dp[i][i] = 1;\n\n    for (int j = 0; j < n; ++j)\n      for (int i = j; i >= 0; --i)\n        for (int k = i; k < j; ++k)\n          dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] - (s[k] == s[j]));\n\n    return dp[0][n - 1];\n  }\n};",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int strangePrinter(String s) {\n    final int n = s.length();\n    // dp[i][j] := min # of turns to print s[i..j]\n    dp = new int[n][n];\n    return strangePrinter(s, 0, n - 1);\n  }\n\n  private int[][] dp;\n\n  private int strangePrinter(final String s, int i, int j) {\n    if (i > j)\n      return 0;\n    if (dp[i][j] > 0)\n      return dp[i][j];\n\n    // Print s[i]\n    dp[i][j] = strangePrinter(s, i + 1, j) + 1;\n\n    for (int k = i + 1; k <= j; ++k)\n      if (s.charAt(k) == s.charAt(i))\n        dp[i][j] = Math.min(dp[i][j], strangePrinter(s, i, k - 1) + strangePrinter(s, k + 1, j));\n\n    return dp[i][j];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int strangePrinter(string s) {\n    const int n = s.length();\n    // dp[i][j] := min # of turns to print s[i..j]\n    dp.resize(n, vector<int>(n));\n    return strangePrinter(s, 0, n - 1);\n  }\n\n private:\n  vector<vector<int>> dp;\n\n  int strangePrinter(const string& s, int i, int j) {\n    if (i > j)\n      return 0;\n    if (dp[i][j])\n      return dp[i][j];\n\n    // Print s[i]\n    dp[i][j] = strangePrinter(s, i + 1, j) + 1;\n\n    for (int k = i + 1; k <= j; ++k)\n      if (s[k] == s[i])\n        dp[i][j] = min(dp[i][j], strangePrinter(s, i, k - 1) +\n                                     strangePrinter(s, k + 1, j));\n\n    return dp[i][j];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/664.html",
    "category": "Algorithms",
    "acceptance_rate": 60.784767313859064,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 2694,
    "dislikes": 284,
    "similar_questions": "[{\"title\": \"Remove Boxes\", \"titleSlug\": \"remove-boxes\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Strange Printer II\", \"titleSlug\": \"strange-printer-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"152.4K\", \"totalSubmission\": \"250.7K\", \"totalAcceptedRaw\": 152402, \"totalSubmissionRaw\": 250724, \"acRate\": \"60.8%\"}",
    "title_pt": "Impressora Estranha",
    "description_pt": "<p>Há uma impressora estranha com as seguintes duas propriedades especiais:</p>\n\n<ul>\n\t<li>A impressora só pode imprimir uma sequência do <strong>mesmo caractere</strong> cada vez.</li>\n\t<li>A cada turno, a impressora pode imprimir novos caracteres começando e terminando em qualquer lugar e cobrirá os caracteres existentes originais.</li>\n</ul>\n\n<p>Dada uma string <code>s</code>, retorne <em>o número mínimo de turnos que a impressora precisou para imprimi-la</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aaabbb&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Imprima &quot;aaa&quot; primeiro e depois imprima &quot;bbb&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aba&quot;\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> Imprima &quot;aaa&quot; primeiro e depois imprima &quot;b&quot; na segunda posição da string, o que cobrirá o caractere existente &#39;a&#39;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> consiste de letras minúsculas do alfabeto ইংlês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "665",
    "paidOnly": false,
    "title": "Non-decreasing Array",
    "titleSlug": "non-decreasing-array",
    "url": "https://leetcode.com/problems/non-decreasing-array",
    "description_url": "https://leetcode.com/problems/non-decreasing-array/description/",
    "description": "<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying <strong>at most one element</strong>.</p>\n\n<p>We define an array is non-decreasing if <code>nums[i] &lt;= nums[i + 1]</code> holds for every <code>i</code> (<strong>0-based</strong>) such that (<code>0 &lt;= i &lt;= n - 2</code>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,2,3]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You could modify the first 4 to 1 to get a non-decreasing array.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,2,1]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> You cannot get a non-decreasing array by modifying at most one element.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/non-decreasing-array/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkPossibility(self, nums: List[int]) -> bool:\n    j = None\n\n    for i in range(len(nums) - 1):\n      if nums[i] > nums[i + 1]:\n        if j is not None:\n          return False\n        j = i\n\n    return j is None or j == 0 or j == len(nums) - 2 or \\\n        nums[j - 1] <= nums[j + 1] or nums[j] <= nums[j + 2]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkPossibility(int[] nums) {\n    int j = -1;\n\n    for (int i = 0; i + 1 < nums.length; ++i)\n      if (nums[i] > nums[i + 1]) {\n        if (j != -1)\n          return false;\n        j = i;\n      }\n\n    return j == -1 || j == 0 || j == nums.length - 2\n        || nums[j - 1] <= nums[j + 1]\n        || nums[j] <= nums[j + 2];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkPossibility(vector<int>& nums) {\n    bool modified = false;\n\n    for (int i = 1; i < nums.size(); ++i)\n      if (nums[i] < nums[i - 1]) {\n        if (modified)\n          return false;\n        if (i == 1 || nums[i] >= nums[i - 2])\n          nums[i - 1] = nums[i];  // Decrease previous value\n        else\n          nums[i] = nums[i - 1];  // Increase current value\n        modified = true;\n      }\n\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/665.html",
    "category": "Algorithms",
    "acceptance_rate": 25.046998695473473,
    "topics": [
      "Array"
    ],
    "hints": [],
    "likes": 5804,
    "dislikes": 786,
    "similar_questions": "[{\"title\": \"Make Array Non-decreasing or Non-increasing\", \"titleSlug\": \"make-array-non-decreasing-or-non-increasing\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find Good Days to Rob the Bank\", \"titleSlug\": \"find-good-days-to-rob-the-bank\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Non-Decreasing Subarrays After K Operations\", \"titleSlug\": \"count-non-decreasing-subarrays-after-k-operations\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"280.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 280321, \"totalSubmissionRaw\": 1119180, \"acRate\": \"25.0%\"}",
    "title_pt": "Array Não Decrescente",
    "description_pt": "<p>Dado um array <code>nums</code> com <code>n</code> inteiros, sua tarefa é verificar se ele poderia se tornar não decrescente modificando <strong>no máximo um elemento</strong>.</p>\n\n<p>Definimos que um array é não decrescente se <code>nums[i] &lt;= nums[i + 1]</code> valer para todo <code>i</code> (<strong>indexado em 0</strong>) tal que (<code>0 &lt;= i &lt;= n - 2</code>).</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,2,3]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Você poderia modificar o primeiro 4 para 1 para obter um array não decrescente.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,2,1]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> Você não pode obter um array não decrescente modificando no máximo um elemento.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "667",
    "paidOnly": false,
    "title": "Beautiful Arrangement II",
    "titleSlug": "beautiful-arrangement-ii",
    "url": "https://leetcode.com/problems/beautiful-arrangement-ii",
    "description_url": "https://leetcode.com/problems/beautiful-arrangement-ii/description/",
    "description": "<p>Given two integers <code>n</code> and <code>k</code>, construct a list <code>answer</code> that contains <code>n</code> different positive integers ranging from <code>1</code> to <code>n</code> and obeys the following requirement:</p>\n\n<ul>\n\t<li>Suppose this list is <code>answer =&nbsp;[a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>, then the list <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> has exactly <code>k</code> distinct integers.</li>\n</ul>\n\n<p>Return <em>the list</em> <code>answer</code>. If there multiple valid answers, return <strong>any of them</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, k = 1\n<strong>Output:</strong> [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, k = 2\n<strong>Output:</strong> [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt; n &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/beautiful-arrangement-ii/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1: Brute Force [Time Limit Exceeded]\n\n#### Intuition\n\nFor each permutation of $$\\text{[1, 2, ..., n]}$$, let's look at the set of differences of the adjacent elements.\n\n#### Algorithm\n\nFor each permutation, we find the number of unique differences of adjacent elements. If it is the desired number, we'll return that permutation.\n\nTo enumerate each permutation without using library functions, we use a recursive algorithm, where `permute` is responsible for permuting the indexes of $$\\text{nums}$$ in the interval $$\\text{[start, nums.length)}$$.\n\n<iframe src=\"https://leetcode.com/playground/W4qmyVMQ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"W4qmyVMQ\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$O(n!)$$ to generate every permutation in the outer loop, then $$O(n)$$ work to check differences. In total taking $$O(n* n!)$$ time.\n\n* Space Complexity: $$O(n)$$. We use $$\\text{seen}$$ to store whether we've seen the differences, and each generated permutation has a length equal to $$\\text{n}$$.\n\n---\n\n### Approach #2: Construction [Accepted]\n\n#### Intuition\n\nWhen $$\\text{k = n-1}$$, a valid construction is $$\\text{[1, n, 2, n-1, 3, n-2, ....]}$$. One way to see this is that we need to have a difference of $$\\text{n-1}$$, which means we need $$\\text{1}$$ and $$\\text{n}$$ adjacent; then, we need a difference of $$\\text{n-2}$$, etc.\n\nAlso, when $$\\text{k = 1}$$, a valid construction is $$\\text{[1, 2, 3, ..., n]}$$. So we have a construction when $$\\text{n-k}$$ is tiny, and when it is large.  This leads to the idea that we can stitch together these two constructions: we can put $$\\text{[1, 2, ..., n-k-1]}$$ first so that $$\\text{n}$$ is effectively $$\\text{k+1}$$, and then finish the construction with the first $$\\text{\"k = n-1\"}$$ method.\n\nFor example, when $$\\text{n = 6}$$ and $$\\text{k = 3}$$, we will construct the array as $$\\text{[1, 2, 3, 6, 4, 5]}$$. This consists of two parts: a construction of $$\\text{[1, 2]}$$ and a construction of $$\\text{[1, 4, 2, 3]}$$ where every element had $$\\text{2}$$ added to it (i.e. $$\\text{[3, 6, 4, 5]}$$).\n\n#### Algorithm\n\nAs before, write $$\\text{[1, 2, ..., n-k-1]}$$ first.  The remaining $$\\text{k+1}$$ elements to be written are $$\\text{[n-k, n-k+1, ..., n]}$$, and we'll write them in alternating head and tail order.\n\nWhen we are writing the $$i^{th}$$ element from the remaining $$\\text{k+1}$$, every even $$i$$ is going to be chosen from the head, and will have value $$\\text{n-k + i//2}$$.  Every odd $$i$$ is going to be chosen from the tail and will have value $$\\text{n - i//2}$$.\n\n<iframe src=\"https://leetcode.com/playground/5qFVzdoP/shared\" frameBorder=\"0\" width=\"100%\" height=\"293\" name=\"5qFVzdoP\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the size of the array to be constructed, and let $k$ be the number of distinct absolute differences required.\n\n- Time complexity: $O(n)$\n\n    The algorithm consists of two loops:\n    1. The first loop runs for $(n - k - 1)$ iterations, assigning values from $1$ to $(n - k - 1)$ to the array.\n    2. The second loop runs for $(k + 1)$ iterations, assigning values in a specific pattern to create $k$ distinct absolute differences.\n\n    Since both loops run in linear time with respect to $n$, the overall time complexity is $O(n)$.\n\n* Space complexity: $O(1)$\n    \n    The algorithm uses a constant amount of extra space, including variables like `c`, `v`, and `i`. No additional data structures are used that scale with $n$. Therefore, the space complexity is $O(1)$ (excluding the output array). \n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def constructArray(self, n: int, k: int) -> List[int]:\n    ans = list(range(1, n - k + 1))\n\n    for i in range(k):\n      if i % 2 == 0:\n        ans.append(n - i // 2)\n      else:\n        ans.append(n - k + (i + 1) // 2)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] constructArray(int n, int k) {\n    int[] ans = new int[n];\n\n    for (int i = 0; i < n - k; ++i)\n      ans[i] = i + 1;\n\n    for (int i = 0; i < k; ++i) {\n      if (i % 2 == 0)\n        ans[n - k + i] = n - i / 2;\n      else\n        ans[n - k + i] = n - k + (i + 1) / 2;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> constructArray(int n, int k) {\n    vector<int> ans;\n\n    for (int i = 0; i < n - k; ++i)\n      ans.push_back(i + 1);\n\n    for (int i = 0; i < k; ++i)\n      if (i % 2 == 0)\n        ans.push_back(n - i / 2);\n      else\n        ans.push_back(n - k + (i + 1) / 2);\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/667.html",
    "category": "Algorithms",
    "acceptance_rate": 60.37821418777818,
    "topics": [
      "Array",
      "Math"
    ],
    "hints": [],
    "likes": 805,
    "dislikes": 1058,
    "similar_questions": "[{\"title\": \"Beautiful Arrangement\", \"titleSlug\": \"beautiful-arrangement\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"57.2K\", \"totalSubmission\": \"94.8K\", \"totalAcceptedRaw\": 57247, \"totalSubmissionRaw\": 94814, \"acRate\": \"60.4%\"}",
    "title_pt": "Arranjo Bonito II",
    "description_pt": "<p>Dados dois inteiros <code>n</code> e <code>k</code>, construa uma lista <code>answer</code> que contenha <code>n</code> inteiros positivos diferentes variando de <code>1</code> a <code>n</code> e obedeça ao seguinte requisito:</p>\n\n<ul>\n\t<li>Suponha que essa lista seja <code>answer =&nbsp;[a<sub>1</sub>, a<sub>2</sub>, a<sub>3</sub>, ... , a<sub>n</sub>]</code>; então a lista <code>[|a<sub>1</sub> - a<sub>2</sub>|, |a<sub>2</sub> - a<sub>3</sub>|, |a<sub>3</sub> - a<sub>4</sub>|, ... , |a<sub>n-1</sub> - a<sub>n</sub>|]</code> tem exatamente <code>k</code> inteiros distintos.</li>\n</ul>\n\n<p>Retorne <em>a lista</em> <code>answer</code>. Se houver múltiplas respostas válidas, retorne <strong>qualquer uma delas</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, k = 1\n<strong>Saída:</strong> [1,2,3]\nExplicação: A [1,2,3] tem três inteiros positivos diferentes variando de 1 a 3, e a [1,1] tem exatamente 1 inteiro distinto: 1\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, k = 2\n<strong>Saída:</strong> [1,3,2]\nExplicação: A [1,3,2] tem três inteiros positivos diferentes variando de 1 a 3, e a [2,1] tem exatamente 2 inteiros distintos: 1 e 2.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt; n &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "668",
    "paidOnly": false,
    "title": "Kth Smallest Number in Multiplication Table",
    "titleSlug": "kth-smallest-number-in-multiplication-table",
    "url": "https://leetcode.com/problems/kth-smallest-number-in-multiplication-table",
    "description_url": "https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/description/",
    "description": "<p>Nearly everyone has used the <a href=\"https://en.wikipedia.org/wiki/Multiplication_table\" target=\"_blank\">Multiplication Table</a>. The multiplication table of size <code>m x n</code> is an integer matrix <code>mat</code> where <code>mat[i][j] == i * j</code> (<strong>1-indexed</strong>).</p>\n\n<p>Given three integers <code>m</code>, <code>n</code>, and <code>k</code>, return <em>the </em><code>k<sup>th</sup></code><em> smallest element in the </em><code>m x n</code><em> multiplication table</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg\" style=\"width: 500px; height: 254px;\" />\n<pre>\n<strong>Input:</strong> m = 3, n = 3, k = 5\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The 5<sup>th</sup> smallest number is 3.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg\" style=\"width: 493px; height: 293px;\" />\n<pre>\n<strong>Input:</strong> m = 2, n = 3, k = 6\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The 6<sup>th</sup> smallest number is 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= m * n</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n### Approach #1: Brute Force [Memory Limit Exceeded]\n\n**Intuition and Algorithm**\n\nCreate the multiplication table and sort it, then take the $$k^{th}$$ element.\n\n<iframe src=\"https://leetcode.com/playground/JNTnTCLa/shared\" frameBorder=\"0\" name=\"JNTnTCLa\" width=\"100%\" height=\"258\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(m*n)$$ to create the table, and $$O(m*n\\log(m*n))$$ to sort it.\n\n* Space Complexity:  $$O(m*n)$$ to store the table.\n\n---\n### Approach #2: Next Heap [Time Limit Exceeded]\n\n**Intuition**\n\nMaintain a heap of the smallest unused element of each row. Then, finding the next element is a pop operation on the heap.\n\n**Algorithm**\n\nOur `heap` is going to consist of elements $$\\text{(val, root)}$$, where $$\\text{val}$$ is the next unused value of that row, and $$\\text{root}$$ was the starting value of that row.\n\nWe will repeatedly find the next lowest element in the table. To do this, we pop from the heap. Then, if there's a next lowest element in that row, we'll put that element back on the heap.\n\n<iframe src=\"https://leetcode.com/playground/Evrh9ssK/shared\" frameBorder=\"0\" name=\"Evrh9ssK\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(k * m \\log m) = O(m^2 n \\log m)$$.  Our initial heapify operation is $$O(m)$$.  Afterwards, each pop and push is $$O(m \\log m)$$, and our outer loop is $$O(k) = O(m*n)$$\n\n* Space Complexity: $$O(m)$$. Our heap is implemented as an array with $$m$$ elements.\n\n---\n### Approach #3: Binary Search [Accepted]\n\n**Intuition**\n\nAs $$\\text{k}$$ and $$\\text{m*n}$$ are up to $$9 * 10^8$$, linear solutions will not work. This motivates solutions with $$\\log$$ complexity, such as binary search.\n\n**Algorithm**\n\nLet's do the binary search for the answer $$\\text{A}$$.\n\nSay `enough(x)` is true if and only if there are $$\\text{k}$$ or more values in the multiplication table that are less than or equal to $$\\text{x}$$.  Colloquially, `enough` describes whether $$\\text{x}$$ is large enough to be the $$k^{th}$$ value in the multiplication table.\n\nThen (for our answer $$\\text{A}$$), whenever $$\\text{x}$$ &geq; $$\\text{A}$$, `enough(x)` is `True`; and whenever $$\\text{x < A}$$, `enough(x)` is `False`.\n\nIn our binary search, our loop invariant is `enough(hi) = True`. In the beginning, `enough(m*n) = True`, and whenever `hi` is set, it is set to a value that is \"enough\" (`enough(mi) = True`). That means `hi` will be the lowest such value at the end of our binary search.\n\nThis leaves us with the task of counting how many values are less than or equal to $$\\text{x}$$. For each of $$\\text{m}$$ rows, the $$i^{th}$$ row looks like $$\\text{[i, 2*i, 3*i, ..., n*i]}$$. The largest possible $$\\text{k*i &leq; x}$$ that could appear is $$\\text{k = x // i}$$. However, if $$\\text{x}$$ is really big, then perhaps $$\\text{k > n}$$, so in total there are $$\\text{min(k, n) = min(x // i, n)}$$ values in that row that are less than or equal to $$\\text{x}$$.\n\nAfter we have the count of how many values in the table are less than or equal to $$\\text{x}$$, by the definition of `enough(x)`, we want to know if that count is greater than or equal to $$\\text{k}$$.\n\n<iframe src=\"https://leetcode.com/playground/4ankdsg9/shared\" frameBorder=\"0\" name=\"4ankdsg9\" width=\"100%\" height=\"377\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(m * \\log (m*n))$$. Our binary search divides the interval $$\\text{[lo, hi]}$$ into half at each step. At each step, we call `enough` which requires $$O(m)$$ time.\n\n* Space Complexity: $$O(1)$$. We only keep integers in memory during our intermediate calculations.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findKthNumber(int m, int n, int k) {\n    int l = 1;\n    int r = m * n;\n\n    while (l < r) {\n      final int mid = (l + r) / 2;\n      if (numsNoGreaterThan(m, n, mid) >= k)\n        r = mid;\n      else\n        l = mid + 1;\n    }\n\n    return l;\n  }\n\n  private int numsNoGreaterThan(int m, int n, int target) {\n    int count = 0;\n    // For each row i, count # of numbers <= target\n    for (int i = 1; i <= m; ++i)\n      count += Math.min(target / i, n);\n    return count;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findKthNumber(int m, int n, int k) {\n    int l = 1;\n    int r = m * n;\n\n    auto numsNoGreaterThan = [&](int target) {\n      int count = 0;\n      // For each row i, count # of numbers <= target\n      for (int i = 1; i <= m; ++i)\n        count += min(target / i, n);\n      return count;\n    };\n\n    while (l < r) {\n      const int mid = (l + r) / 2;\n      if (numsNoGreaterThan(mid) >= k)\n        r = mid;\n      else\n        l = mid + 1;\n    }\n\n    return l;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/668.html",
    "category": "Algorithms",
    "acceptance_rate": 52.72868504318578,
    "topics": [
      "Math",
      "Binary Search"
    ],
    "hints": [],
    "likes": 2205,
    "dislikes": 60,
    "similar_questions": "[{\"title\": \"Kth Smallest Element in a Sorted Matrix\", \"titleSlug\": \"kth-smallest-element-in-a-sorted-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K-th Smallest Pair Distance\", \"titleSlug\": \"find-k-th-smallest-pair-distance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"K-th Smallest Prime Fraction\", \"titleSlug\": \"k-th-smallest-prime-fraction\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Time to Eat All Grains\", \"titleSlug\": \"minimum-time-to-eat-all-grains\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Amount With Single Denomination Combination\", \"titleSlug\": \"kth-smallest-amount-with-single-denomination-combination\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"74K\", \"totalSubmission\": \"140.3K\", \"totalAcceptedRaw\": 73991, \"totalSubmissionRaw\": 140324, \"acRate\": \"52.7%\"}",
    "title_pt": "K-ésimo Menor Número na Tabela de Multiplicação",
    "description_pt": "<p>Quase todo mundo já usou a <a href=\"https://en.wikipedia.org/wiki/Multiplication_table\" target=\"_blank\">Tabela de Multiplicação</a>. A tabela de multiplicação de tamanho <code>m x n</code> é uma matriz inteira <code>mat</code> na qual <code>mat[i][j] == i * j</code> (<strong>indexado em 1</strong>).</p>\n\n<p>Dados três inteiros <code>m</code>, <code>n</code> e <code>k</code>, retorne <em>o </em><code>k<sup>th</sup></code><em> menor elemento na </em><code>m x n</code><em> tabela de multiplicação</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/multtable1-grid.jpg\" style=\"width: 500px; height: 254px;\" />\n<pre>\n<strong>Entrada:</strong> m = 3, n = 3, k = 5\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> O 5<sup>th</sup> menor número é 3.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/multtable2-grid.jpg\" style=\"width: 493px; height: 293px;\" />\n<pre>\n<strong>Entrada:</strong> m = 2, n = 3, k = 6\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> O 6<sup>th</sup> menor número é 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= m * n</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "669",
    "paidOnly": false,
    "title": "Trim a Binary Search Tree",
    "titleSlug": "trim-a-binary-search-tree",
    "url": "https://leetcode.com/problems/trim-a-binary-search-tree",
    "description_url": "https://leetcode.com/problems/trim-a-binary-search-tree/description/",
    "description": "<p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node&#39;s descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>\n\n<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg\" style=\"width: 450px; height: 126px;\" />\n<pre>\n<strong>Input:</strong> root = [1,0,2], low = 1, high = 2\n<strong>Output:</strong> [1,null,2]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg\" style=\"width: 450px; height: 277px;\" />\n<pre>\n<strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3\n<strong>Output:</strong> [3,2,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>The value of each node in the tree is <strong>unique</strong>.</li>\n\t<li><code>root</code> is guaranteed to be a valid binary search tree.</li>\n\t<li><code>0 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/trim-a-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode trimBST(TreeNode root, int low, int high) {\n    if (root == null)\n      return null;\n    if (root.val < low)\n      return trimBST(root.right, low, high);\n    if (root.val > high)\n      return trimBST(root.left, low, high);\n    root.left = trimBST(root.left, low, high);\n    root.right = trimBST(root.right, low, high);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* trimBST(TreeNode* root, int L, int R) {\n    if (root == nullptr)\n      return nullptr;\n    if (root->val < L)\n      return trimBST(root->right, L, R);\n    if (root->val > R)\n      return trimBST(root->left, L, R);\n    root->left = trimBST(root->left, L, R);\n    root->right = trimBST(root->right, L, R);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/669.html",
    "category": "Algorithms",
    "acceptance_rate": 66.36605819365406,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 5966,
    "dislikes": 264,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"320.1K\", \"totalSubmission\": \"482.4K\", \"totalAcceptedRaw\": 320119, \"totalSubmissionRaw\": 482354, \"acRate\": \"66.4%\"}",
    "title_pt": "Podar uma Árvore Binária de Busca",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária de busca e os limites inferior e superior como <code>low</code> e <code>high</code>, pode a árvore de modo que todos os seus elementos estejam em <code>[low, high]</code>. Podar a árvore <strong>não</strong> deve alterar a estrutura relativa dos elementos que permanecerão na árvore (ou seja, qualquer descendente de um nó deve permanecer um descendente). Pode-se provar que existe uma <strong>única resposta</strong>.</p>\n\n<p>Retorne <em>a raiz da árvore binária de busca podada</em>. Observe que a raiz pode mudar dependendo dos limites fornecidos.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg\" style=\"width: 450px; height: 126px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,0,2], low = 1, high = 2\n<strong>Saída:</strong> [1,null,2]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg\" style=\"width: 450px; height: 277px;\" />\n<pre>\n<strong>Entrada:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3\n<strong>Saída:</strong> [3,2,null,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 10<sup>4</sup>]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>\n\t<li>O valor de cada nó na árvore é <strong>único</strong>.</li>\n\t<li><code>root</code> é garantidamente uma árvore binária de busca válida.</li>\n\t<li><code>0 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "670",
    "paidOnly": false,
    "title": "Maximum Swap",
    "titleSlug": "maximum-swap",
    "url": "https://leetcode.com/problems/maximum-swap",
    "description_url": "https://leetcode.com/problems/maximum-swap/description/",
    "description": "<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>\n\n<p>Return <em>the maximum valued number you can get</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 2736\n<strong>Output:</strong> 7236\n<strong>Explanation:</strong> Swap the number 2 and the number 7.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> num = 9973\n<strong>Output:</strong> 9973\n<strong>Explanation:</strong> No swap.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 10<sup>8</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-swap/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nWe need to maximize the value of a given integer by swapping any two digits, but we can do this only once. We aim to figure out the best two digits to swap so that the resulting number is as large as possible.\n\n---\n\n### Approach 1: Brute Force\n\n#### Intuition\n\nOne approach would be to consider all possible swaps by swapping each pair of digits and returning the largest resulting integer. \n\nWe convert the number to a string so that individual digits can be easily accessed and manipulated. This allows us to treat the number as an array of characters, making it easier to swap positions without the complexities involved in extracting digits mathematically. Once in string form, we swap every digit with each digit after it to check all possible outcomes. After each swap, we convert the modified string back to an integer and keep track of the largest value we encounter.\n\n#### Algorithm\n\n- Convert the integer `num` to a string `numStr` for easy manipulation of its digits.\n- Determine the size of `numStr` and initialize `maxNum` to `num` to track the maximum number found.\n\n- Use a nested loop to try all possible swaps of digits in `numStr`:\n  - The outer loop iterates through each digit with index `i`.\n  - The inner loop iterates through the subsequent digits with index `j` (starting from `i + 1`).\n\n  - Inside the inner loop:\n    - Swap the digits at indices `i` and `j` in `numStr`.\n    - Convert the modified `numStr` back to an integer and update `maxNum` if the new number is larger.\n    - Swap the digits back to restore the original string for the next iteration.\n\n- After exploring all possible swaps, return `maxNum`, which contains the largest number achievable through any single swap of digits.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/UwhBWNQw/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"UwhBWNQw\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of digits in the input number.\n\n- Time complexity: $O(n^2)$\n\n    The outer loop iterates through each digit (from 0 to $n-1$), and for each digit, the inner loop also iterates through the remaining digits (from $i+1$ to $n-1$). This results in $\\frac{n(n-1)}{2}$ possible swaps, leading to quadratic time complexity. Each swap involves:\n    - Performing a swap operation (constant time).\n    - Converting the modified string back to an integer takes $O(n)$ time due to the length of the string.\n    \n    Therefore, the total time complexity combines these two aspects, resulting in $O(n^2 \\cdot n) = O(n^3)$ for this specific implementation. However, since the main constraint is derived from the nested loops alone, the simplified consideration will generally focus on $O(n^2)$.\n\n- Space complexity: $O(n)$\n\n    The space complexity arises from converting the integer to a string, which requires additional space proportional to the number of digits $n$ in the number. No additional data structures that grow with input size are used, hence the overall space complexity is primarily determined by this string conversion. Thus, it is $O(n)$. \n  \n---\n\n\n### Approach 2: Greedy Two-Pass\n\n#### Intuition\n\nApproach 1 is inefficient because not all swaps are worth making. Let's consider an approach where we focus only on swaps that will give us the biggest improvement.\n\nCan we identify a pattern in the results that will help us identify the best swap? If we think through some examples, it can be observed that in each example the optimal swap involves moving the largest digit we can move forward to replace a smaller one. \n\nTo achieve this, we make two passes over the number. In the first pass, we scan from right to left to identify and store the largest digit we find and its position.\n\nIn the second pass, we move from left to right. Now that we know, for each position, the largest digit that appears after it, we check if we can make a swap. The first time we find a digit that is smaller than the largest one that comes after it, we swap them. Since we’re always looking for the largest possible swap, this guarantees that we’ll maximize the number.\n\n<details>\n  <summary>Inductive Proof for the Two-Pass Greedy</summary>\n\n\n##### Base Case:\nFor a one-digit number $N = d_0$, no swaps are possible, so the number itself is the maximum. The approach is trivially correct here.\n\n##### Inductive Hypothesis:\nAssume the two-pass method works for any number with $k$ digits, yielding the maximum possible number after making the best swap.\n\n##### Inductive Step:\nConsider a number with $k+1$ digits, represented as $d_0, d_1, \\dots, d_k$.\n\n1. First Pass (Right-to-Left):\n    As we move from $d_k$ to $d_0$, we track the largest digit found so far on the right and store its position. For any position $i$, let $M_i$ be the largest digit to the right of $d_i$.\n\n2. Second Pass (Left-to-Right):\n    We then move from $d_0$ to $d_k$, and for each $d_i$, check if $d_i < M_i$. If so, we swap $d_i$ with $M_i$, giving us the largest possible improvement. Since we make the first maximizing swap, this guarantees that the result is the maximum possible number after one swap.\n\nSince our hypothesis holds for $k$ digits, and the two-pass strategy maximizes the number for $k+1$ digits, the method works for all $n$-digit numbers by induction.\n\nThus, the two-pass greedy approach will always yield the maximum possible number in a single swap.\n\n</details>\n\n#### Algorithm\n\n- Convert the integer `num` to a string `numStr` to facilitate digit manipulation.\n- Determine the length `n` of the string representation.\n\n- Initialize an array `maxRightIndex` of size `n` to store the index of the largest digit from the current position to the end of the string.\n\n- Populate `maxRightIndex` in a single backward pass:\n  - Set `maxRightIndex[n - 1]` to `n - 1`, as the last digit is the largest in its own right.\n  - Iterate from the second last digit to the beginning of the string:\n    - If the current digit `numStr[i]` is greater than the digit at the index stored in `maxRightIndex[i + 1]`, update `maxRightIndex[i]` to `i`.\n    - Otherwise, keep `maxRightIndex[i]` as `maxRightIndex[i + 1]`.\n\n- In a second pass, check for the first opportunity to swap for maximum value:\n  - Iterate through each digit in `numStr`:\n    - If the current digit `numStr[i]` is less than the digit at the index `maxRightIndex[i]`, a beneficial swap can be made.\n      - Swap `numStr[i]` with `numStr[maxRightIndex[i]]` to maximize the number.\n      - Convert the modified string back to an integer and return it immediately.\n\n- If no beneficial swap is found throughout the iterations, return the original number `num`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/fgDJok4g/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"fgDJok4g\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of digits in the input number.\n\n- Time complexity: $O(n)$\n\n    Converting the integer `num` to its string representation takes $O(n)$.\n  \n    We iterate through the digits from right to left, making one comparison per digit. This pass takes $O(n)$ time.\n\n    We iterate from left to right, checking whether the current digit is smaller than the maximum digit to its right. This also takes $O(n)$ time.\n\n    Converting the modified string back to an integer takes $O(n)$ time.\n\n    Overall, each operation in the algorithm takes linear time, so the total time complexity is $O(n)$.\n\n- Space complexity: $O(n)$\n  \n    We store the string representation of the number, which requires $O(n)$ space.\n\n    We maintain an array `maxRightIndex` of size $n$, which also takes $O(n)$ space.\n\n    The space used by simple variables like `num` and loop counters is constant, i.e., $O(1)$.\n\n    Thus, the total space complexity is $O(n)$.\n\n---\n\n### Approach 3: Suboptimal Greedy\n\n#### Intuition\n\nA natural follow-up question is: can we simplify this even more? Let's see if we can reduce our approach by using a pass to record the last occurrence of each digit in the given integer, and then use that information to find an optimal swap (if one exists).\n\nLet's walk through what this would look like using Example 1 from the problem description: \n\nWe'll do one scan from left to right, noting the positions of the digits in the number (2, 7, 3, and 6):\n- Last occurrence of 2: index 0\n- Last occurrence of 7: index 1\n- Last occurrence of 3: index 2\n- Last occurrence of 6: index 3\n\nNext, we'll use the stored values to check if there are any small values with larger values that follow:\n\n- We start with '2' and check if any larger digits appear later in the number. In the case of 2736, we compare '2' with '7', '3', and '6'.\n- Since '7' is the largest digit that appears after '2', we choose '7' as the best swap.\n\n<details>\n<summary>Inductive Proof for Suboptimal Greedy</summary>\n\n\n#### Base Case:\nFor a single-digit number $N = d_0$, no swaps are possible, so the number itself is the maximum. Therefore, the approach is trivially correct here.\n\n#### Inductive Hypothesis:\nAssume that for any $k$-digit number, the Suboptimal method will yield the maximum possible number by identifying the optimal swap or determining that no swap can improve the result.\n\n#### Inductive Step:\nNow, consider a number with $k+1$ digits represented as $d_0, d_1, \\dots, d_k$.\n\n1. Record the Last Occurrence of Each Digit:\n   We first perform a single pass over the number to store the last occurrence of each digit in an array `lastOccurrence`. This way, for each digit $d_i$, we can quickly look up whether a larger digit appears later in the number.\n\n2. Find the Optimal Swap:\n   As we scan from left to right, we check each digit $d_i$ to see if a larger digit appears later in the sequence by looking up the last occurrence of digits from 9 down to $d_i + 1$. If we find such a digit, we swap $d_i$ with the rightmost largest possible digit that improves the number. This ensures the largest possible improvement as soon as we encounter the first digit that can be swapped for a higher value.\n\n3. Optimality of the First Swap:\n   By following this process, we always select the first digit that can be maximized with a single swap. Since we’re making the swap at the leftmost possible position where an improvement can occur, we ensure that the resulting number is maximized in the most significant digit first. Consequently, any swap we make will yield the highest possible value at the earliest digit position, thereby producing the maximum number achievable by one swap.\n\n#### Conclusion:\nSince the approach works for $k$-digit numbers and we’ve shown that it holds for $k+1$ digits as well, the principle of induction confirms that this Suboptimal method will always yield the maximum number for any integer length.\n\n</details>\n\n\n#### Algorithm\n\n- Convert the input integer `num` to a string `numStr` to facilitate digit manipulation.\n- Get the length `n` of `numStr`.\n- Initialize an array `lastSeen` of size 10, filled with `-1`, to store the last occurrence index of each digit (0-9).\n\n- Record the last occurrence of each digit:\n  - For each index `i` in `numStr`, update `lastSeen[numStr[i] - '0']` to `i`, which stores the last position of each digit.\n\n- Traverse the digits in `numStr` to find the first digit that can be swapped with a larger one:\n  - For each index `i`, iterate `d` from `9` down to `numStr[i] - '0'`:\n    - If `lastSeen[d] > i`, it means there exists a larger digit `d` that can be swapped with `numStr[i]`.\n      - Perform the swap between `numStr[i]` and `numStr[lastSeen[d]]`.\n      - Immediately return the integer value of the modified string using `stoi(numStr)`.\n\n- If no swap has been performed throughout the iteration, return the original number `num` since it is already maximized.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/RmFoFW64/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"RmFoFW64\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of digits in the input number.\n\n- Time complexity: $O(n)$\n\n    Converting the integer `num` to its string representation takes $O(n)$.\n    \n    We loop through the string `numStr` to fill the `lastSeen` array, which takes $O(n)$ time.\n    \n    The outer loop runs $n$ times (once for each digit), and for each digit, the inner loop runs at most 9 times (since there are at most 9 different digits larger than the current one to check). Thus, the traversal and comparison step takes $O(9n) = O(n)$ time.\n    \n    Converting the modified string back to an integer takes $O(n)$ time.\n\n    Overall, all steps are bounded by $O(n)$, so the total time complexity is $O(n)$.\n\n- Space complexity: $O(n)$\n\n    The string `numStr` requires $O(n)$ space to store the digits of the integer `num`.\n    \n    The array `lastSeen` is of fixed size 10 (for digits 0 through 9), so it takes $O(1)$ space.\n    \n    No other significant additional space is used.\n\n    Thus, the overall space complexity is dominated by the space needed to store the string, which is $O(n)$.\n  \n---\n\n\n### Approach 4: Space Optimized Greedy\n\n#### Intuition\n\nAs we move through the number, we don’t need to know the position of every digit—we only need to know the position of the largest digit we’ve seen so far.\n\nWe start by scanning the number from right to left. As we move, we keep track of the largest digit we’ve encountered. Whenever we come across a smaller digit, we consider it a candidate for swapping with the largest one we’ve seen.\n\nSo we compare each digit with the maximum digit to its right. If it’s smaller, we mark it for swapping. By the time we finish scanning the number, we’ll know the best swap to make. If we find a smaller digit and a larger one to swap it with, we perform the swap. Otherwise, we leave the number unchanged.\n\nThis way we can save space by not needing to track all positions, and it works because, as we move from right to left, we are always aware of the largest possible swap we could make.\n\nThe algorithm is visualized below:\n\n!?!../Documents/670/approach4.json:960,500!?!\n\n#### Algorithm\n\n- Convert the integer `num` to a string `numStr` for easier manipulation of individual digits.\n- Initialize variables:\n  - `n` to store the length of `numStr`.\n  - `maxDigitIndex` to track the index of the maximum digit encountered (initialized to `-1`).\n  - `swapIdx1` and `swapIdx2` to track the indices of the digits to be swapped (both initialized to `-1`).\n\n- Traverse the string `numStr` from right to left:\n  - If `maxDigitIndex` is `-1` or the current digit `numStr[i]` is greater than the digit at `maxDigitIndex`, update `maxDigitIndex` to `i` (indicating a new maximum digit has been found).\n  - If `numStr[i]` is less than the digit at `maxDigitIndex`, mark `swapIdx1` as `i` (the smaller digit to be swapped) and `swapIdx2` as `maxDigitIndex` (the larger digit to swap with).\n\n- After completing the traversal, check if a valid swap has been identified:\n  - If both `swapIdx1` and `swapIdx2` are not `-1`, perform the swap between `numStr[swapIdx1]` and `numStr[swapIdx2]`.\n\n- Convert the modified string back to an integer and return it. If no swap occurred, return the original number.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/9qirzKnf/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"9qirzKnf\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of digits in the input number.\n\n- Time complexity: $O(n)$\n\n    Converting the integer `num` to its string representation takes $O(n)$.\n\n    The loop iterates over the string once from right to left, performing constant-time operations for each character, making the loop cost $O(n)$.\n\n    Swap runs in constant time $O(1)$.\n\n    Converting the modified string back to an integer takes $O(n)$ time.\n\n    Thus, the overall time complexity is dominated by the traversal and conversions, giving us $O(n)$.\n\n- Space complexity: $O(n)$\n\n    The `numStr` variable is a string representation of the input number, which requires $O(n)$ space to store.\n\n    The other variables (`maxDigitIndex`, `swapIdx1`, `swapIdx2`) require $O(1)$ space since they are just integer indices.\n\n    Therefore, the overall space complexity is $O(n)$, mainly due to the string representation of the number.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maximumSwap(self, num: int) -> int:\n    s = list(str(num))\n    dict = {c: i for i, c in enumerate(s)}\n\n    for i, c in enumerate(s):\n      for digit in reversed(string.digits):\n        if digit <= c:\n          break\n        if digit in dict and dict[digit] > i:\n          s[i], s[dict[digit]] = digit, s[i]\n          return int(''.join(s))\n\n    return num",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maximumSwap(int num) {\n    char[] s = Integer.toString(num).toCharArray();\n    int[] lastIndex = new int[10]; // {digit: last index}\n\n    for (int i = 0; i < s.length; ++i)\n      lastIndex[s[i] - '0'] = i;\n\n    for (int i = 0; i < s.length; ++i)\n      for (int d = 9; d > s[i] - '0'; --d)\n        if (lastIndex[d] > i) {\n          s[lastIndex[d]] = s[i];\n          s[i] = (char) ('0' + d);\n          return Integer.parseInt(new String(s));\n        }\n\n    return num;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maximumSwap(int num) {\n    string s = to_string(num);\n    vector<int> lastIndex(10, -1);  // {digit: last index}\n\n    for (int i = 0; i < s.length(); ++i)\n      lastIndex[s[i] - '0'] = i;\n\n    for (int i = 0; i < s.length(); ++i)\n      for (int d = 9; d > s[i] - '0'; --d)\n        if (lastIndex[d] > i) {\n          swap(s[i], s[lastIndex[d]]);\n          return stoi(s);\n        }\n\n    return num;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/670.html",
    "category": "Algorithms",
    "acceptance_rate": 51.807501331010656,
    "topics": [
      "Math",
      "Greedy"
    ],
    "hints": [],
    "likes": 4166,
    "dislikes": 263,
    "similar_questions": "[{\"title\": \"Create Maximum Number\", \"titleSlug\": \"create-maximum-number\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"465.1K\", \"totalSubmission\": \"897.8K\", \"totalAcceptedRaw\": 465133, \"totalSubmissionRaw\": 897812, \"acRate\": \"51.8%\"}",
    "title_pt": "Troca Máxima",
    "description_pt": "<p>Você recebe um inteiro <code>num</code>. Você pode trocar dois dígitos no máximo uma vez para obter o número de maior valor possível.</p>\n\n<p>Retorne <em>o número de maior valor que você pode obter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 2736\n<strong>Saída:</strong> 7236\n<strong>Explicação:</strong> Troque o número 2 e o número 7.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> num = 9973\n<strong>Saída:</strong> 9973\n<strong>Explicação:</strong> Nenhuma troca.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= num &lt;= 10<sup>8</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "671",
    "paidOnly": false,
    "title": "Second Minimum Node In a Binary Tree",
    "titleSlug": "second-minimum-node-in-a-binary-tree",
    "url": "https://leetcode.com/problems/second-minimum-node-in-a-binary-tree",
    "description_url": "https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/",
    "description": "<p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node&#39;s value is the smaller value among its two sub-nodes. More formally, the property&nbsp;<code>root.val = min(root.left.val, root.right.val)</code>&nbsp;always holds.</p>\n\n<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes&#39; value in the whole tree.</p>\n\n<p>If no such second minimum value exists, output -1 instead.</p>\n\n<p>&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg\" style=\"width: 431px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [2,2,5,null,null,5,7]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg\" style=\"width: 321px; height: 182px;\" />\n<pre>\n<strong>Input:</strong> root = [2,2,2]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> The smallest value is 2, but there isn&#39;t any second smallest value.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>root.val == min(root.left.val, root.right.val)</code>&nbsp;for each internal node of the tree.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findSecondMinimumValue(TreeNode root) {\n    if (root == null)\n      return -1;\n    return findSecondMinimumValue(root, root.val);\n  }\n\n  private int findSecondMinimumValue(TreeNode root, int min) {\n    if (root == null)\n      return -1;\n    if (root.val > min)\n      return root.val;\n\n    final int leftMin = findSecondMinimumValue(root.left, min);\n    final int rightMin = findSecondMinimumValue(root.right, min);\n\n    if (leftMin == -1 || rightMin == -1)\n      return Math.max(leftMin, rightMin);\n    return Math.min(leftMin, rightMin);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findSecondMinimumValue(TreeNode* root) {\n    if (root == nullptr)\n      return -1;\n    return findSecondMinimumValue(root, root->val);\n  }\n\n private:\n  int findSecondMinimumValue(TreeNode* root, int mini) {\n    if (root == nullptr)\n      return -1;\n    if (root->val > mini)\n      return root->val;\n\n    const int leftMin = findSecondMinimumValue(root->left, mini);\n    const int rightMin = findSecondMinimumValue(root->right, mini);\n\n    if (leftMin == -1 || rightMin == -1)\n      return max(leftMin, rightMin);\n    return min(leftMin, rightMin);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/671.html",
    "category": "Algorithms",
    "acceptance_rate": 45.27876088804678,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 1935,
    "dislikes": 1897,
    "similar_questions": "[{\"title\": \"Kth Smallest Element in a BST\", \"titleSlug\": \"kth-smallest-element-in-a-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"218.9K\", \"totalSubmission\": \"483.4K\", \"totalAcceptedRaw\": 218897, \"totalSubmissionRaw\": 483443, \"acRate\": \"45.3%\"}",
    "title_pt": "Segundo Menor Nó em uma Árvore Binária",
    "description_pt": "<p>Dada uma árvore binária especial não vazia, composta por nós com valor não negativo, em que cada nó desta árvore tem exatamente <code>two</code> ou <code>zero</code> subnós. Se o nó tiver dois subnós, então o valor deste nó é o menor valor entre seus dois subnós. Mais formalmente, a propriedade&nbsp;<code>root.val = min(root.left.val, root.right.val)</code>&nbsp;sempre se mantém.</p>\n\n<p>Dada essa árvore binária, você precisa retornar o valor do <b>segundo menor</b> no conjunto formado pelos valores de todos os nós de toda a árvore.</p>\n\n<p>Se tal segundo menor valor não existir, retorne -1 em vez disso.</p>\n\n<p>&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg\" style=\"width: 431px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,2,5,null,null,5,7]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> O menor valor é 2, o segundo menor valor é 5.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg\" style=\"width: 321px; height: 182px;\" />\n<pre>\n<strong>Entrada:</strong> root = [2,2,2]\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong> O menor valor é 2, mas não existe nenhum segundo menor valor.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 25]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>\n\t<li><code>root.val == min(root.left.val, root.right.val)</code>&nbsp;para cada nó interno da árvore.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "672",
    "paidOnly": false,
    "title": "Bulb Switcher II",
    "titleSlug": "bulb-switcher-ii",
    "url": "https://leetcode.com/problems/bulb-switcher-ii",
    "description_url": "https://leetcode.com/problems/bulb-switcher-ii/description/",
    "description": "<p>There is a room with <code>n</code> bulbs labeled from <code>1</code> to <code>n</code> that all are turned on initially, and <strong>four buttons</strong> on the wall. Each of the four buttons has a different functionality where:</p>\n\n<ul>\n\t<li><strong>Button 1:</strong> Flips the status of all the bulbs.</li>\n\t<li><strong>Button 2:</strong> Flips the status of all the bulbs with even labels (i.e., <code>2, 4, ...</code>).</li>\n\t<li><strong>Button 3:</strong> Flips the status of all the bulbs with odd labels (i.e., <code>1, 3, ...</code>).</li>\n\t<li><strong>Button 4:</strong> Flips the status of all the bulbs with a label <code>j = 3k + 1</code> where <code>k = 0, 1, 2, ...</code> (i.e., <code>1, 4, 7, 10, ...</code>).</li>\n</ul>\n\n<p>You must make <strong>exactly</strong> <code>presses</code> button presses in total. For each press, you may pick <strong>any</strong> of the four buttons to press.</p>\n\n<p>Given the two integers <code>n</code> and <code>presses</code>, return <em>the number of <strong>different possible statuses</strong> after performing all </em><code>presses</code><em> button presses</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, presses = 1\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 2, presses = 1\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, presses = 1\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= presses &lt;= 1000</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/bulb-switcher-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def flipLights(self, n: int, m: int) -> int:\n    n = min(n, 3)\n\n    if m == 0:\n      return 1\n    if m == 1:\n      return [2, 3, 4][n - 1]\n    if m == 2:\n      return [2, 4, 7][n - 1]\n\n    return [2, 4, 8][n - 1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int flipLights(int n, int m) {\n    n = Math.min(n, 3);\n\n    if (m == 0)\n      return 1;\n    if (m == 1)\n      return new int[] {2, 3, 4}[n - 1];\n    if (m == 2)\n      return new int[] {2, 4, 7}[n - 1];\n\n    return (int) Math.pow(2, n);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int flipLights(int n, int m) {\n    n = min(n, 3);\n\n    if (m == 0)\n      return 1;\n    if (m == 1)\n      return vector{2, 3, 4}[n - 1];\n    if (m == 2)\n      return vector{2, 4, 7}[n - 1];\n\n    return pow(2, n);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/672.html",
    "category": "Algorithms",
    "acceptance_rate": 49.47604370972261,
    "topics": [
      "Math",
      "Bit Manipulation",
      "Depth-First Search",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 179,
    "dislikes": 234,
    "similar_questions": "[{\"title\": \"Bulb Switcher\", \"titleSlug\": \"bulb-switcher\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Times Binary String Is Prefix-Aligned\", \"titleSlug\": \"number-of-times-binary-string-is-prefix-aligned\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"26.5K\", \"totalSubmission\": \"53.5K\", \"totalAcceptedRaw\": 26487, \"totalSubmissionRaw\": 53535, \"acRate\": \"49.5%\"}",
    "title_pt": "Interruptor de Lâmpadas II",
    "description_pt": "<p>Há uma sala com <code>n</code> lâmpadas rotuladas de <code>1</code> a <code>n</code> que estão todas ligadas inicialmente, e <strong>quatro botões</strong> na parede. Cada um dos quatro botões tem uma funcionalidade diferente, onde:</p>\n\n<ul>\n\t<li><strong>Botão 1:</strong> Alterna o estado de todas as lâmpadas.</li>\n\t<li><strong>Botão 2:</strong> Alterna o estado de todas as lâmpadas com rótulos pares (isto é, <code>2, 4, ...</code>).</li>\n\t<li><strong>Botão 3:</strong> Alterna o estado de todas as lâmpadas com rótulos ímpares (isto é, <code>1, 3, ...</code>).</li>\n\t<li><strong>Botão 4:</strong> Alterna o estado de todas as lâmpadas com rótulo <code>j = 3k + 1</code> onde <code>k = 0, 1, 2, ...</code> (isto é, <code>1, 4, 7, 10, ...</code>).</li>\n</ul>\n\n<p>Você deve fazer <strong>exatamente</strong> <code>presses</code> pressionamentos de botão no total. Em cada pressionamento, você pode escolher <strong>qualquer</strong> um dos quatro botões para pressionar.</p>\n\n<p>Dados os dois inteiros <code>n</code> e <code>presses</code>, retorne <em>o número de <strong>diferentes estados possíveis</strong> após realizar todos os </em><code>presses</code><em> pressionamentos de botão</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, presses = 1\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> O estado pode ser:\n- [off] pressionando o botão 1\n- [on] pressionando o botão 2\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 2, presses = 1\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> O estado pode ser:\n- [off, off] pressionando o botão 1\n- [on, off] pressionando o botão 2\n- [off, on] pressionando o botão 3\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, presses = 1\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> O estado pode ser:\n- [off, off, off] pressionando o botão 1\n- [off, on, off] pressionando o botão 2\n- [on, off, on] pressionando o botão 3\n- [off, on, on] pressionando o botão 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 1000</code></li>\n\t<li><code>0 &lt;= presses &lt;= 1000</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "673",
    "paidOnly": false,
    "title": "Number of Longest Increasing Subsequence",
    "titleSlug": "number-of-longest-increasing-subsequence",
    "url": "https://leetcode.com/problems/number-of-longest-increasing-subsequence",
    "description_url": "https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/",
    "description": "<p>Given an integer array&nbsp;<code>nums</code>, return <em>the number of longest increasing subsequences.</em></p>\n\n<p><strong>Notice</strong> that the sequence has to be <strong>strictly</strong> increasing.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,5,4,7]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,2,2,2,2]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2000</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>The answer is guaranteed to fit inside a 32-bit integer.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-longest-increasing-subsequence/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n>**Note.** For this problem, we assume that you already know the fundamentals of dynamic programming and are figuring out how to apply it to a wide range of problems, such as this one. If you are not yet at this stage, we recommend checking out our relevant [Explore Card content on dynamic programming](https://leetcode.com/explore/featured/card/dynamic-programming/) before returning to this article.\n\n### Approach 1: Bottom-up Dynamic Programming\n\n#### Intuition\n\nBefore attempting this problem, please first solve [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/), which this problem is a follow up to.\n\nConsider an array $\\text{nums}$ of length $n$ representing a sequence of numbers. To find the number of longest increasing subsequences (LISs) in this array, we introduce two dynamic programming (DP) arrays: $\\text{length}$ and $\\text{count}$.\n\n$\\text{length}[i]$ represents the length of the LIS ending at index $i$ in the $\\text{nums}$ array, while $\\text{count}[i]$ denotes the count of LISs ending at index $i$.\n\nNotice that $\\text{length}$ here represents the answer to **Longest Increasing Subsequence** and $\\text{count}$ represents the answer to this problem.\n\n!?!../Documents/673/slideshow.json:1000,500!?!\n\nFor instance, given $\\text{nums} = [1, 3, 2, 4]$, we can illustrate the purpose of these arrays. Here, $\\text{length}[0] = 1$ because the longest increasing subsequence ending at index $0$ is the number $1$ itself. Similarly, $\\text{length}[1] = 2$ as the LIS ending at index $1$ is $[1, 3]$. Continuing, $\\text{length}[2] = 2$ since the LIS ending at index $2$ is $[1, 2]$. Finally, $\\text{length}[3] = 3$ as the LIS ending at index $3$ is either $[1, 3, 4]$ or $[1, 2, 4]$.\n\nIn addition, we use $\\text{count}$ to keep track of the count of the longest increasing subsequences. In the example above, $\\text{count}[0] = 1$ because only one LIS ends at index $0$. Similarly, $\\text{count}[1] = 1$ and $\\text{count}[2] = 1$ since one LIS is ending at each of those indices. $\\text{count}[3] = 2$ because there are two LISs ending at index $3$.\n\nBy utilizing these two DP arrays, we can efficiently compute the count of the LISs in the given $\\text{nums}$ array.\n\nInitially, every subsequence consisting of a single element is increasing. Therefore, we initialize $\\text{length}[i] = 1$ and $\\text{count}[i] = 1$ for all indices $i$ in the array. As we iterate through the array, if we encounter a longer subsequence ending at index $i$, we update the values of $\\text{length}[i]$ and $\\text{count}[i]$ accordingly.\n\nTo compute the DP values for index $i$, we first calculate the values for all positions $j < i$.\n\nFor each index $j$ such that $j < i$ and $\\text{nums}[j] < \\text{nums}[i]$, we can extend any increasing subsequence that ends at index $j$ by adding the element at index $i$. The length of the LIS ending at position $j$ is $\\text{length}[j]$. By extending the subsequence, we obtain a new subsequence of length $\\text{length}[j] + 1$ that ends at index $i$. We update the $\\text{length}[i]$ value to be the maximum length of an increasing subsequence ending at index $i$ seen so far.\n\nIf $\\text{length}[j] + 1 > \\text{length}[i]$, it means we have found a longer subsequence ending at index $i$. In this case, we update $\\text{length}[i]$ to $\\text{length}[j] + 1$. Additionally, we discard any subsequences we saw earlier since they are no longer LIS: reset $\\text{count}[i]$ to zero.\n\nNext, we check the equality $\\text{length}[j] + 1 = \\text{length}[i]$. If $\\text{length}[j] + 1 = \\text{length}[i]$, it implies that we can extend every LIS ending at index $j$ with the element $\\text{nums}[i]$ to create new longest increasing subsequences ending at index $i$. Therefore, we add $\\text{count}[j]$ to $\\text{count}[i]$ to count all subsequences that include both indices $j$ and $i$. Note that $\\text{length}[i]$ might have just become $\\text{length}[j] + 1$ during the previous step.\n\nLet's consider the length of the LIS of the entire array $\\text{nums}$, denoted as $\\text{maxLength}$, which equals the maximum $\\text{length}[i]$. By finding $\\text{maxLength}$, we determine the target length we aim to achieve for our subsequences.\n\nTo calculate $\\text{result}$, the total number of LISs in the array, we need to sum up the $\\text{count}[i]$ values for all indices $i$ where the length of the subsequence, $\\text{length}[i]$, is equal to $\\text{maxLength}$. These indices represent the endpoints of the longest increasing subsequences in the array. By adding up their corresponding $\\text{count}[i]$ values, we account for all possible LISs.\n\n#### Algorithm\n\n1. Declare two DP arrays $\\text{length}$ and $\\text{count}$, and initialize $\\text{length}[i] = 1$, $\\text{count}[i] = 1$.\n2. Iterate $i$ from $0$ to $n - 1$.\n\t* Iterate $j$ from $0$ to $i - 1$.\n\t\t* If $\\text{nums}[j] < \\text{nums}[i]$.\n\t\t\t* If $\\text{length}[j] + 1 > \\text{length}[i]$, update $\\text{length}[i]$ with $\\text{length}[j] + 1$ and set $\\text{count}[i]$ to zero.\n\t\t\t* If $\\text{length}[j] + 1 = \\text{length}[i]$, add $\\text{count}[j]$ to $\\text{count}[i]$.\n3. Let $\\text{maxLength}$ be the maximum value in the array $\\text{length}$.\n4. Initialize $\\text{result} = 0$.\n5. Iterate $i$ from $0$ to $n - 1$.\n\t* If $\\text{length}[i] = \\text{maxLength}$, add $\\text{count}[i]$ to $\\text{result}$.\n6. Return $\\text{result}$.\n\n#### Implementation\n\n\n<iframe src=\"https://leetcode.com/playground/Q6GAPagG/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Q6GAPagG\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time Complexity: $O(n^2)$.\n\nThe nested loops iterate over the input array $\\text{nums}$, resulting in an overall time complexity of $O(n^2)$, where $n$ is the array length. The outer loop iterates $n$ times, and the inner loop iterates up to $i$ times, where $i$ ranges from $0$ to $n-1$.\n\n* Space Complexity: $O(n)$.\n\nWe store two DP arrays: $\\text{length}$ and $\\text{count}$, each with a length of $n$. Therefore, the space required to store these arrays is $O(n)$.\n\n---\n\n### Approach 2: Top-down Dynamic Programming (Memoization)\n\n#### Intuition\n\nIn this approach, we will calculate the DP arrays $\\text{length}$ and $\\text{count}$ using the same recurrence relation as in the previous one, but the organization of computations will be different.\n\nWe will utilize a recursive function called $\\text{calculateDP}(i)$ that computes the DP values $\\text{length}[i]$ and $\\text{count}[i]$ when called for the first time with a particular $i$ value. Once the values $\\text{length}[i]$ and $\\text{count}[i]$ are computed, subsequent calls to $\\text{calculateDP}(i)$ will terminate immediately.\n\nFor example, when we first call $\\text{calculateDP}(4)$, it computes $\\text{length}[4]$ and $\\text{count}[4]$. When we make subsequent calls to $\\text{calculateDP}(4)$, it returns immediately.\n\nThis approach ensures that we calculate the DP value for each state (each $i$) only once.\n\nTo compute $\\text{length}[i]$ and $\\text{count}[i]$, we will follow the same steps as in the previous approach: iterate over $j$ such that $j < i$ and $\\text{nums}[j] < \\text{nums}[i]$, and update the DP values for $i$ using the DP values for $j$.\n\nTo determine whether we need to compute the DP values for $i$ or return immediately, we can initialize the DP arrays $\\text{length}$ and $\\text{count}$ with zeros. Thus, $\\text{length}[i] = 0$ will indicate that we have not yet computed the DP values for $i$. Once we find the result for $i$, we will update $\\text{length}[i]$ and $\\text{count}[i]$, and $\\text{length}[i]$ will no longer be zero, indicating that we have computed the values.\n\n#### Algorithm\n\nThe function $\\text{calculateDP}$ takes a parameter $i$.\n1. If $\\text{length}[i] \\ne 0$ (which means that we found this value earlier), return from the function.\n2. Assign $\\text{length}[i] = 1$, $\\text{count}[i] = 1$ (the DP initialization).\n3. Iterate $j$ from $0$ to $i - 1$.\n\t* If $\\text{nums}[j] < \\text{nums}[i]$.\n\t\t* Call $\\text{calculateDP}(j)$ recursively to ensure that $\\text{length}[j]$ and $\\text{count}[j]$ are calculated.\n\t\t* If $\\text{length}[j] + 1 > \\text{length}[i]$, update $\\text{length}[i]$ with $\\text{length}[j] + 1$ and set $\\text{count}[i]$ to zero.\n\t\t* If $\\text{length}[j] + 1 = \\text{length}[i]$, add $\\text{count}[j]$ to $\\text{count}[i]$.\n\nIn the main function, one needs to do the following.\n1. Initialize $\\text{maxLength} = 0$ and $\\text{result} = 0$.\n2. Iterate $i$ from $0$ to $n - 1$.\n\t* Call $\\text{calculateDP}(i)$.\n\t* Assign $\\text{maxLength} = \\max(\\text{maxLength}, \\text{length}[i])$.\n3. Iterate $i$ from $0$ to $n - 1$.\n\t* If $\\text{length}[i] = \\text{maxLength}$, add $\\text{count}[i]$ to $\\text{result}$.\n4. Return $\\text{result}$.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/eWJZudA2/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"eWJZudA2\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time Complexity: $O(n^2)$.\n\nEven though we changed the order in which we calculate DP, the time complexity is the same as in the previous approach: for each $i$, we compute $\\text{length}[i]$ and $\\text{count}[i]$ in $O(n)$. \n\n* Space Complexity: $O(n)$.\n\nWe store the DP arrays $\\text{length}$ and $\\text{count}$ of size $n$, as in the previous approach.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findNumberOfLIS(self, nums: List[int]) -> int:\n    ans = 0\n    maxLength = 0\n    length = [1] * len(nums)  # length[i] := LIS's length ending w/ nums[i]\n    count = [1] * len(nums)  # count[i] := # Of the LIS ending w/ nums[i]\n\n    # Calculate length and count arrays\n    for i, num in enumerate(nums):\n      for j in range(i):\n        if nums[j] < num:\n          if length[i] < length[j] + 1:\n            length[i] = length[j] + 1\n            count[i] = count[j]\n          elif length[i] == length[j] + 1:\n            count[i] += count[j]\n\n    # Get # Of LIS\n    for i, l in enumerate(length):\n      if l > maxLength:\n        maxLength = l\n        ans = count[i]\n      elif l == maxLength:\n        ans += count[i]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findNumberOfLIS(int[] nums) {\n    final int n = nums.length;\n    int ans = 0;\n    int maxLength = 0;\n    int[] length = new int[n]; // length[i] := LIS's length ending w/ nums[i]\n    int[] count = new int[n];  // count[i] := # of the LIS ending w/ nums[i]\n\n    Arrays.fill(length, 1);\n    Arrays.fill(count, 1);\n\n    // Calculate length and count arrays\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < i; ++j)\n        if (nums[j] < nums[i])\n          if (length[i] < length[j] + 1) {\n            length[i] = length[j] + 1;\n            count[i] = count[j];\n          } else if (length[i] == length[j] + 1) {\n            count[i] += count[j];\n          }\n\n    // Get # of LIS\n    for (int i = 0; i < n; ++i)\n      if (length[i] > maxLength) {\n        maxLength = length[i];\n        ans = count[i];\n      } else if (length[i] == maxLength) {\n        ans += count[i];\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findNumberOfLIS(vector<int>& nums) {\n    const int n = nums.size();\n    int ans = 0;\n    int maxLength = 0;\n    vector<int> length(n, 1);  // length[i] := LIS's length ending w/ nums[i]\n    vector<int> count(n, 1);   // count[i] := # of the LIS ending w/ nums[i]\n\n    // Calculate length and count arrays\n    for (int i = 0; i < n; ++i)\n      for (int j = 0; j < i; ++j)\n        if (nums[j] < nums[i])\n          if (length[i] < length[j] + 1) {\n            length[i] = length[j] + 1;\n            count[i] = count[j];\n          } else if (length[i] == length[j] + 1) {\n            count[i] += count[j];\n          }\n\n    // Get # of LIS\n    for (int i = 0; i < n; ++i)\n      if (length[i] > maxLength) {\n        maxLength = length[i];\n        ans = count[i];\n      } else if (length[i] == maxLength) {\n        ans += count[i];\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/673.html",
    "category": "Algorithms",
    "acceptance_rate": 49.68966327664302,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Binary Indexed Tree",
      "Segment Tree"
    ],
    "hints": [],
    "likes": 7026,
    "dislikes": 279,
    "similar_questions": "[{\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Continuous Increasing Subsequence\", \"titleSlug\": \"longest-continuous-increasing-subsequence\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Longest Increasing Subsequence II\", \"titleSlug\": \"longest-increasing-subsequence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"279.1K\", \"totalSubmission\": \"561.6K\", \"totalAcceptedRaw\": 279077, \"totalSubmissionRaw\": 561640, \"acRate\": \"49.7%\"}",
    "title_pt": "Número de Subsequências Crescentes Mais Longas",
    "description_pt": "<p>Dado um array de inteiros&nbsp;<code>nums</code>, retorne <em>o número de subsequências crescentes mais longas.</em></p>\n\n<p><strong>Observe</strong> que a sequência precisa ser <strong>estritamente</strong> crescente.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,5,4,7]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> As duas subsequências crescentes mais longas são [1, 3, 4, 7] e [1, 3, 5, 7].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,2,2,2,2]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> O comprimento da subsequência crescente mais longa é 1, e há 5 subsequências crescentes de comprimento 1, então retorne 5.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2000</code></li>\n\t<li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li>A resposta é garantida para caber em um inteiro de 32 bits.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "674",
    "paidOnly": false,
    "title": "Longest Continuous Increasing Subsequence",
    "titleSlug": "longest-continuous-increasing-subsequence",
    "url": "https://leetcode.com/problems/longest-continuous-increasing-subsequence",
    "description_url": "https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/",
    "description": "<p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest <strong>continuous increasing subsequence</strong> (i.e. subarray)</em>. The subsequence must be <strong>strictly</strong> increasing.</p>\n\n<p>A <strong>continuous increasing subsequence</strong> is defined by two indices <code>l</code> and <code>r</code> (<code>l &lt; r</code>) such that it is <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> and for each <code>l &lt;= i &lt; r</code>, <code>nums[i] &lt; nums[i + 1]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,5,4,7]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,2,2,2,2]\n<strong>Output:</strong> 1\n<strong>Explanation:</strong> The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-continuous-increasing-subsequence/solutions/",
    "solution": "[TOC]\n\n\n### Approach #1: Sliding Window [Accepted]\n\n**Intuition and Algorithm**\n\nEvery (continuous) increasing subsequence is disjoint, and the boundary of each such subsequence occurs whenever `nums[i-1] >= nums[i]`. When it does, it marks the start of a new increasing subsequence at `nums[i]`, and we store such `i` in the variable `anchor`.\n\nFor example, if `nums = [7, 8, 9, 1, 2, 3]`, then `anchor` starts at `0` (`nums[anchor] = 7`) and gets set again to `anchor = 3` (`nums[anchor] = 1`). Regardless of the value of `anchor`, we record a candidate answer of `i - anchor + 1`, the length of the subarray `nums[anchor], nums[anchor+1], ..., nums[i]`, and our answer gets updated appropriately.\n\n<iframe src=\"https://leetcode.com/playground/aQJp75Ls/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"aQJp75Ls\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `nums`. We perform one loop through `nums`.\n\n* Space Complexity: $$O(1)$$, the space used by `anchor` and `ans`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLengthOfLCIS(self, nums: List[int]) -> int:\n    ans = 0\n    j = 0\n\n    for i in range(len(nums)):\n      if i > 0 and nums[i] <= nums[i - 1]:\n        j = i\n      ans = max(ans, i - j + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findLengthOfLCIS(int[] nums) {\n    int ans = 0;\n\n    for (int l = 0, r = 0; r < nums.length; ++r) {\n      if (r > 0 && nums[r] <= nums[r - 1])\n        l = r;\n      ans = Math.max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLengthOfLCIS(vector<int>& nums) {\n    int ans = 0;\n\n    for (int l = 0, r = 0; r < nums.size(); ++r) {\n      if (r > 0 && nums[r] <= nums[r - 1])\n        l = r;\n      ans = max(ans, r - l + 1);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/674.html",
    "category": "Algorithms",
    "acceptance_rate": 51.06865425147588,
    "topics": [
      "Array"
    ],
    "hints": [],
    "likes": 2397,
    "dislikes": 185,
    "similar_questions": "[{\"title\": \"Number of Longest Increasing Subsequence\", \"titleSlug\": \"number-of-longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Window Subsequence\", \"titleSlug\": \"minimum-window-subsequence\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Consecutive Characters\", \"titleSlug\": \"consecutive-characters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Longest Increasing Subsequence II\", \"titleSlug\": \"longest-increasing-subsequence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"306.7K\", \"totalSubmission\": \"600.7K\", \"totalAcceptedRaw\": 306747, \"totalSubmissionRaw\": 600657, \"acRate\": \"51.1%\"}",
    "title_pt": "Maior Subsequência Crescente Contínua",
    "description_pt": "<p>Dado um array desordenado de inteiros <code>nums</code>, retorne <em>o comprimento da maior <strong>subsequência crescente contínua</strong> (isto é, subarray)</em>. A subsequência deve ser <strong>estritamente</strong> crescente.</p>\n\n<p>Uma <strong>subsequência crescente contínua</strong> é definida por dois índices <code>l</code> e <code>r</code> (<code>l &lt; r</code>) tais que ela seja <code>[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]</code> e, para cada <code>l &lt;= i &lt; r</code>, <code>nums[i] &lt; nums[i + 1]</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,5,4,7]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> A maior subsequência crescente contínua é [1,3,5] com comprimento 3.\nEmbora [1,3,5,7] seja uma subsequência crescente, ela não é contínua, pois os elementos 5 e 7 são separados pelo elemento\n4.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,2,2,2,2]\n<strong>Saída:</strong> 1\n<strong>Explicação:</strong> A maior subsequência crescente contínua é [2] com comprimento 1. Note que ela deve ser estritamente\ncrescente.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "675",
    "paidOnly": false,
    "title": "Cut Off Trees for Golf Event",
    "titleSlug": "cut-off-trees-for-golf-event",
    "url": "https://leetcode.com/problems/cut-off-trees-for-golf-event",
    "description_url": "https://leetcode.com/problems/cut-off-trees-for-golf-event/description/",
    "description": "<p>You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an <code>m x n</code> matrix. In this matrix:</p>\n\n<ul>\n\t<li><code>0</code> means the cell cannot be walked through.</li>\n\t<li><code>1</code> represents an empty cell that can be walked through.</li>\n\t<li>A number greater than <code>1</code> represents a tree in a cell that can be walked through, and this number is the tree&#39;s height.</li>\n</ul>\n\n<p>In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.</p>\n\n<p>You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes <code>1</code> (an empty cell).</p>\n\n<p>Starting from the point <code>(0, 0)</code>, return <em>the minimum steps you need to walk to cut off all the trees</em>. If you cannot cut off all the trees, return <code>-1</code>.</p>\n\n<p><strong>Note:</strong> The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Input:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> The trees in the bottom row cannot be accessed as the middle row is blocked.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]\n<strong>Output:</strong> 6\n<b>Explanation:</b> You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == forest.length</code></li>\n\t<li><code>n == forest[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>0 &lt;= forest[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>Heights of all trees are <strong>distinct</strong>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/cut-off-trees-for-golf-event/solutions/",
    "solution": "[TOC]\n\n\n### Approach Framework\n\n**Explanation**\n\nStarting from `(0, 0)`, for each tree in height order, we will calculate the distance from where we are to the next tree (and move there), adding that distance to the answer.\n\nWe frame the problem as providing some distance function `dist(forest, sr, sc, tr, tc)` that calculates the path distance from source `(sr, sc)` to target `(tr, tc)` through obstacles `dist[i][j] == 0`. (This distance function will return `-1` if the path is impossible.)\n\nWhat follows is code and complexity analysis that is common to all three approaches. After, the algorithms presented in our approaches will focus on only providing our `dist` function.\n\n\n**Python**\n```python\nclass Solution(object):\n    def cutOffTree(self, forest):\n        trees = sorted((v, r, c) for r, row in enumerate(forest)\n                       for c, v in enumerate(row) if v > 1)\n        sr = sc = ans = 0\n        for _, tr, tc in trees:\n            d = dist(forest, sr, sc, tr, tc)\n            if d < 0: return -1\n            ans += d\n            sr, sc = tr, tc\n        return ans\n```\n\n**Java**\n```java\nclass Solution {\n    int[] dr = {-1, 1, 0, 0};\n    int[] dc = {0, 0, -1, 1};\n\n    public int cutOffTree(List<List<Integer>> forest) {\n        List<int[]> trees = new ArrayList();\n        for (int r = 0; r < forest.size(); ++r) {\n            for (int c = 0; c < forest.get(0).size(); ++c) {\n                int v = forest.get(r).get(c);\n                if (v > 1) trees.add(new int[]{v, r, c});\n            }\n        }\n\n        Collections.sort(trees, (a, b) -> Integer.compare(a[0], b[0]));\n\n        int ans = 0, sr = 0, sc = 0;\n        for (int[] tree: trees) {\n            int d = dist(forest, sr, sc, tree[1], tree[2]);\n            if (d < 0) return -1;\n            ans += d;\n            sr = tree[1]; sc = tree[2];\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\nAll three algorithms have similar worst-case complexities, but in practice, each successive algorithm presented performs faster on random data.\n\n* Time Complexity: $$O((RC)^2)$$ where there are $$R$$ rows and $$C$$ columns in the given `forest`. We walk to $$R*C$$ trees, and each walk could spend $$O(R*C)$$ time searching for the tree.\n\n* Space Complexity: $$O(R*C)$$, the maximum size of the data structures used.\n\n---\n### Approach #1: BFS [Accepted]\n\n**Intuition and Algorithm**\n\nWe perform a breadth-first-search, processing nodes (grid positions) in a queue. `seen` keeps track of nodes that have already been added to the queue at some point - those nodes will be already processed or are in the queue awaiting processing.\n\nFor each node next to be processed, we look at its neighbors. If they are in the forest (grid), they haven't been enqueued, and they aren't an obstacle, we will enqueue that neighbor.\n\nWe also keep a side count of the distance traveled for each node. If the node we are processing is our destination 'target' `(tr, tc)`, we'll return the answer.\n\n**Python**\n```python\ndef bfs(forest, sr, sc, tr, tc):\n    R, C = len(forest), len(forest[0])\n    queue = collections.deque([(sr, sc, 0)])\n    seen = {(sr, sc)}\n    while queue:\n        r, c, d = queue.popleft()\n        if r == tr and c == tc:\n            return d\n        for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)):\n            if (0 <= nr < R and 0 <= nc < C and\n                    (nr, nc) not in seen and forest[nr][nc]):\n                seen.add((nr, nc))\n                queue.append((nr, nc, d+1))\n    return -1\n```\n\n**Java**\n```java\npublic int bfs(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {\n    int R = forest.size(), C = forest.get(0).size();\n    Queue<int[]> queue = new LinkedList();\n    queue.add(new int[]{sr, sc, 0});\n    boolean[][] seen = new boolean[R][C];\n    seen[sr][sc] = true;\n    while (!queue.isEmpty()) {\n        int[] cur = queue.poll();\n        if (cur[0] == tr && cur[1] == tc) return cur[2];\n        for (int di = 0; di < 4; ++di) {\n            int r = cur[0] + dr[di];\n            int c = cur[1] + dc[di];\n            if (0 <= r && r < R && 0 <= c && c < C &&\n                    !seen[r][c] && forest.get(r).get(c) > 0) {\n                seen[r][c] = true;\n                queue.add(new int[]{r, c, cur[2]+1});\n            }\n        }\n    }\n    return -1;\n}\n```\n\n---\n\n### Approach #2: A* Search [Accepted]\n\n**Intuition and Algorithm**\n\nThe A* star algorithm is another path-finding algorithm.  For every node at position `(r, c)`, we have some estimated cost `node.f = node.g + node.h`, where `node.g` is the actual distance from `(sr, sc)` to `(r, c)`, and `node.h` is our *heuristic* (guess) of the distance from `(r, c)` to `(tr, tc)`.  In this case, our guess will be the taxicab distance, `node.h = abs(r-tr) + abs(c-tc)`.\n\nWe keep a priority queue to decide what node to search in (*expand*) next. We can prove that if we find the target node, we must have traveled the lowest possible distance `node.g`. By considering the last time when two backward paths are the same, without loss of generality we could suppose the penultimate square of the two paths are different, and then in this case `node.f = node.g + 1`, showing the path with less actual distance travelled is expanded first as desired.\n\nIt might be useful for solvers familiar with *Dijkstra's Algorithm* to know that Dijkstra's algorithm is a special case of *A\\* Search* with `node.h = 0` always.\n\n**Python**\n```python\ndef astar(forest, sr, sc, tr, tc):\n    R, C = len(forest), len(forest[0])\n    heap = [(0, 0, sr, sc)]\n    cost = {(sr, sc): 0}\n    while heap:\n        f, g, r, c = heapq.heappop(heap)\n        if r == tr and c == tc: return g\n        for nr, nc in ((r-1,c), (r+1,c), (r,c-1), (r,c+1)):\n            if 0 <= nr < R and 0 <= nc < C and forest[nr][nc]:\n                ncost = g + 1 + abs(nr - tr) + abs(nc - tc)\n                if ncost < cost.get((nr, nc), 9999):\n                    cost[nr, nc] = ncost\n                    heapq.heappush(heap, (ncost, g+1, nr, nc))\n    return -1\n```\n\n**Java**\n```java\npublic int cutOffTree(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {\n    int R = forest.size(), C = forest.get(0).size();\n    PriorityQueue<int[]> heap = new PriorityQueue<int[]>(\n        (a, b) -> Integer.compare(a[0], b[0]));\n    heap.offer(new int[]{0, 0, sr, sc});\n\n    HashMap<Integer, Integer> cost = new HashMap();\n    cost.put(sr * C + sc, 0);\n\n    while (!heap.isEmpty()) {\n        int[] cur = heap.poll();\n        int g = cur[1], r = cur[2], c = cur[3];\n        if (r == tr && c == tc) return g;\n        for (int di = 0; di < 4; ++di) {\n            int nr = r + dr[di], nc = c + dc[di];\n            if (0 <= nr && nr < R && 0 <= nc && nc < C && forest.get(nr).get(nc) > 0) {\n                int ncost = g + 1 + Math.abs(nr-tr) + Math.abs(nc-tr);\n                if (ncost < cost.getOrDefault(nr * C + nc, 9999)) {\n                    cost.put(nr * C + nc, ncost);\n                    heap.offer(new int[]{ncost, g+1, nr, nc});\n                }\n            }\n        }\n    }\n    return -1;\n}\n```\n\n---\n### Approach #3: Hadlock's Algorithm [Accepted]\n\n**Intuition**\n\nWithout any obstacles, the distance from `source = (sr, sc)` to `target = (tr, tc)` is simply `taxi(source, target) = abs(sr-tr) + abs(sc-tc)`. This represents a sort of minimum distance that must be traveled. Whenever we walk \"away\" from the target, we increase this minimum by 2, as we stepped 1 move, plus the taxicab distance from our new location has increased by one.\n\nLet's call such a move that walks away from the target a *detour*. It can be proven that the distance from source to target is simply `taxi(source, target) + 2 * detours`, where `detours` is the smallest number of detours in any path from `source` to `target`.\n\n**Algorithm**\n\nWith respect to a `source` and `target`, call the *detour number* of a square to be the lowest number of detours possible in any path from `source` to that square.  (Here, detours are defined with respect to `target` - the number of away steps from that target.)\n\nWe will perform a priority-first search in order of detour number. If the target is found, it was found with the lowest detour number and therefore the lowest corresponding distance.  This motivates using `processed`, keeping track of when nodes are expanded, not visited - nodes could potentially be visited twice.\n\nAs each neighboring node can only have the same detour number or a detour number one higher, we will only consider at most 2 priority classes at a time. Thus, we can use a deque (double-ended queue) to perform this implementation.  We will place nodes with the same detour number to be expanded first, and nodes with a detour number one higher to be expanded after all nodes with the current number are done.\n\n**Python**\n```python\ndef hadlocks(forest, sr, sc, tr, tc):\n    R, C = len(forest), len(forest[0])\n    processed = set()\n    deque = collections.deque([(0, sr, sc)])\n    while deque:\n        detours, r, c = deque.popleft()\n        if (r, c) not in processed:\n            processed.add((r, c))\n            if r == tr and c == tc:\n                return abs(sr-tr) + abs(sc-tc) + 2*detours\n            for nr, nc, closer in ((r-1, c, r > tr), (r+1, c, r < tr),\n                                   (r, c-1, c > tc), (r, c+1, c < tc)):\n                if 0 <= nr < R and 0 <= nc < C and forest[nr][nc]:\n                    if closer:\n                        deque.appendleft((detours, nr, nc))\n                    else:\n                        deque.append((detours+1, nr, nc))\n    return -1\n```\n\n**Java**\n```java\npublic int hadlocks(List<List<Integer>> forest, int sr, int sc, int tr, int tc) {\n    int R = forest.size(), C = forest.get(0).size();\n    Set<Integer> processed = new HashSet();\n    Deque<int[]> deque = new ArrayDeque();\n    deque.offerFirst(new int[]{0, sr, sc});\n    while (!deque.isEmpty()) {\n        int[] cur = deque.pollFirst();\n        int detours = cur[0], r = cur[1], c = cur[2];\n        if (!processed.contains(r*C + c)) {\n            processed.add(r*C + c);\n            if (r == tr && c == tc) {\n                return Math.abs(sr-tr) + Math.abs(sc-tc) + 2 * detours;\n            }\n            for (int di = 0; di < 4; ++di) {\n                int nr = r + dr[di];\n                int nc = c + dc[di];\n                boolean closer;\n                if (di <= 1) closer = di == 0 ? r > tr : r < tr;\n                else closer = di == 2 ? c > tc : c < tc;\n                if (0 <= nr && nr < R && 0 <= nc && nc < C && forest.get(nr).get(nc) > 0) {\n                    if (closer) deque.offerFirst(new int[]{detours, nr, nc});\n                    else deque.offerLast(new int[]{detours+1, nr, nc});\n                }\n            }\n        }\n    }\n    return -1;\n}\n```",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass T {\n  public int i;\n  public int j;\n  public int height;\n  public T(int i, int j, int height) {\n    this.i = i;\n    this.j = j;\n    this.height = height;\n  }\n}\n\nclass Solution {\n  public int cutOffTree(List<List<Integer>> forest) {\n    Queue<T> minHeap = new PriorityQueue<>((a, b) -> a.height - b.height);\n\n    for (int i = 0; i < forest.size(); ++i)\n      for (int j = 0; j < forest.get(0).size(); ++j)\n        if (forest.get(i).get(j) > 1)\n          minHeap.offer(new T(i, j, forest.get(i).get(j)));\n\n    int ans = 0;\n    int x = 0;\n    int y = 0;\n\n    while (!minHeap.isEmpty()) {\n      final int i = minHeap.peek().i;\n      final int j = minHeap.poll().j;\n      // Walk from (x, y) to (i, j)\n      final int steps = bfs(forest, x, y, i, j);\n      if (steps < 0)\n        return -1;\n      ans += steps;\n      x = i;\n      y = j;\n    }\n\n    return ans;\n  }\n\n  private static final int[] dirs = {0, 1, 0, -1, 0};\n\n  private int bfs(List<List<Integer>> forest, int si, int sj, int ei, int ej) {\n    final int m = forest.size();\n    final int n = forest.get(0).size();\n    int steps = 0;\n    Queue<int[]> q = new ArrayDeque<>(Arrays.asList(new int[] {si, sj}));\n    boolean[][] seen = new boolean[m][n];\n    seen[si][sj] = true;\n\n    while (!q.isEmpty()) {\n      for (int sz = q.size(); sz > 0; --sz) {\n        final int i = q.peek()[0];\n        final int j = q.poll()[1];\n        if (i == ei && j == ej)\n          return steps;\n        for (int k = 0; k < 4; ++k) {\n          final int x = i + dirs[k];\n          final int y = j + dirs[k + 1];\n          if (x < 0 || x == m || y < 0 || y == n)\n            continue;\n          if (seen[x][y] || forest.get(x).get(y) == 0)\n            continue;\n          q.offer(new int[] {x, y});\n          seen[x][y] = true;\n        }\n      }\n      ++steps;\n    }\n\n    return -1;\n  };\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct T {\n  int i;\n  int j;\n  int height;\n  T(int i, int j, int height) : i(i), j(j), height(height) {}\n};\n\nclass Solution {\n public:\n  int cutOffTree(vector<vector<int>>& forest) {\n    auto compare = [&](const T& a, const T& b) { return a.height > b.height; };\n    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);\n\n    for (int i = 0; i < forest.size(); ++i)\n      for (int j = 0; j < forest[0].size(); ++j)\n        if (forest[i][j] > 1)\n          minHeap.emplace(i, j, forest[i][j]);\n\n    int ans = 0;\n    int x = 0;\n    int y = 0;\n\n    while (!minHeap.empty()) {\n      const auto [i, j, _] = minHeap.top();\n      minHeap.pop();\n      // Walk from (x, y) to (i, j)\n      const int steps = bfs(forest, x, y, i, j);\n      if (steps < 0)\n        return -1;\n      ans += steps;\n      x = i;\n      y = j;\n    }\n\n    return ans;\n  }\n\n private:\n  const vector<int> dirs{0, 1, 0, -1, 0};\n\n  int bfs(const vector<vector<int>>& forest, int si, int sj, int ei, int ej) {\n    const int m = forest.size();\n    const int n = forest[0].size();\n    int steps = 0;\n    queue<pair<int, int>> q{{{si, sj}}};\n    vector<vector<bool>> seen(m, vector<bool>(n));\n    seen[si][sj] = true;\n\n    while (!q.empty()) {\n      for (int s = q.size(); s > 0; --s) {\n        const auto [i, j] = q.front();\n        q.pop();\n        if (i == ei && j == ej)\n          return steps;\n        for (int k = 0; k < 4; ++k) {\n          const int x = i + dirs[k];\n          const int y = j + dirs[k + 1];\n          if (x < 0 || x == m || y < 0 || y == n)\n            continue;\n          if (seen[x][y] || forest[x][y] == 0)\n            continue;\n          q.emplace(x, y);\n          seen[x][y] = true;\n        }\n      }\n      ++steps;\n    }\n\n    return -1;\n  };\n};",
    "solution_code_url": "https://leetcodehelp.github.io/675.html",
    "category": "Algorithms",
    "acceptance_rate": 35.24325808001098,
    "topics": [
      "Array",
      "Breadth-First Search",
      "Heap (Priority Queue)",
      "Matrix"
    ],
    "hints": [],
    "likes": 1257,
    "dislikes": 686,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"77K\", \"totalSubmission\": \"218.6K\", \"totalAcceptedRaw\": 77040, \"totalSubmissionRaw\": 218595, \"acRate\": \"35.2%\"}",
    "title_pt": "Cortar Árvores para o Evento de Golfe",
    "description_pt": "<p>Você deve cortar todas as árvores em uma floresta para um evento de golfe. A floresta é representada por uma matriz <code>m x n</code>. Nesta matriz:</p>\n\n<ul>\n\t<li><code>0</code> significa que a célula não pode ser atravessada.</li>\n\t<li><code>1</code> representa uma célula vazia que pode ser atravessada.</li>\n\t<li>Um número maior que <code>1</code> representa uma árvore em uma célula que pode ser atravessada, e esse número é a altura da árvore.</li>\n</ul>\n\n<p>Em um passo, você pode andar em qualquer uma das quatro direções: norte, leste, sul e oeste. Se você estiver em uma célula com uma árvore, você pode escolher cortá-la ou não.</p>\n\n<p>Você deve cortar as árvores na ordem da mais baixa para a mais alta. Quando você corta uma árvore, o valor em sua célula se torna <code>1</code> (uma célula vazia).</p>\n\n<p>Começando do ponto <code>(0, 0)</code>, retorne <em>o número mínimo de passos que você precisa andar para cortar todas as árvores</em>. Se você não conseguir cortar todas as árvores, retorne <code>-1</code>.</p>\n\n<p><strong>Nota:</strong> A entrada é gerada de modo que nenhuma duas árvores tenham a mesma altura, e há pelo menos uma árvore que precisa ser cortada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/trees1.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> forest = [[1,2,3],[0,0,4],[7,6,5]]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Seguir o caminho acima permite que você corte as árvores da mais baixa para a mais alta em 6 passos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/11/26/trees2.jpg\" style=\"width: 242px; height: 242px;\" />\n<pre>\n<strong>Entrada:</strong> forest = [[1,2,3],[0,0,0],[7,6,5]]\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong> As árvores na linha inferior não podem ser acessadas, pois a linha do meio está bloqueada.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> forest = [[2,3,4],[0,0,5],[8,7,6]]\n<strong>Saída:</strong> 6\n<b>Explicação:</b> Você pode seguir o mesmo caminho do Exemplo 1 para cortar todas as árvores.\nObserve que você pode cortar a primeira árvore em (0, 0) antes de fazer qualquer passo.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == forest.length</code></li>\n\t<li><code>n == forest[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>0 &lt;= forest[i][j] &lt;= 10<sup>9</sup></code></li>\n\t<li>As alturas de todas as árvores são <strong>distintas</strong>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "676",
    "paidOnly": false,
    "title": "Implement Magic Dictionary",
    "titleSlug": "implement-magic-dictionary",
    "url": "https://leetcode.com/problems/implement-magic-dictionary",
    "description_url": "https://leetcode.com/problems/implement-magic-dictionary/description/",
    "description": "<p>Design a data structure that is initialized with a list of <strong>different</strong> words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.</p>\n\n<p>Implement the&nbsp;<code>MagicDictionary</code>&nbsp;class:</p>\n\n<ul>\n\t<li><code>MagicDictionary()</code>&nbsp;Initializes the object.</li>\n\t<li><code>void buildDict(String[]&nbsp;dictionary)</code>&nbsp;Sets the data structure&nbsp;with an array of distinct strings <code>dictionary</code>.</li>\n\t<li><code>bool search(String searchWord)</code> Returns <code>true</code> if you can change <strong>exactly one character</strong> in <code>searchWord</code> to match any string in the data structure, otherwise returns <code>false</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MagicDictionary&quot;, &quot;buildDict&quot;, &quot;search&quot;, &quot;search&quot;, &quot;search&quot;, &quot;search&quot;]\n[[], [[&quot;hello&quot;, &quot;leetcode&quot;]], [&quot;hello&quot;], [&quot;hhllo&quot;], [&quot;hell&quot;], [&quot;leetcoded&quot;]]\n<strong>Output</strong>\n[null, null, false, true, false, false]\n\n<strong>Explanation</strong>\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([&quot;hello&quot;, &quot;leetcode&quot;]);\nmagicDictionary.search(&quot;hello&quot;); // return False\nmagicDictionary.search(&quot;hhllo&quot;); // We can change the second &#39;h&#39; to &#39;e&#39; to match &quot;hello&quot; so we return True\nmagicDictionary.search(&quot;hell&quot;); // return False\nmagicDictionary.search(&quot;leetcoded&quot;); // return False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;dictionary.length &lt;= 100</code></li>\n\t<li><code>1 &lt;=&nbsp;dictionary[i].length &lt;= 100</code></li>\n\t<li><code>dictionary[i]</code> consists of only lower-case English letters.</li>\n\t<li>All the strings in&nbsp;<code>dictionary</code>&nbsp;are <strong>distinct</strong>.</li>\n\t<li><code>1 &lt;=&nbsp;searchWord.length &lt;= 100</code></li>\n\t<li><code>searchWord</code>&nbsp;consists of only lower-case English letters.</li>\n\t<li><code>buildDict</code>&nbsp;will be called only once before <code>search</code>.</li>\n\t<li>At most <code>100</code> calls will be made to <code>search</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/implement-magic-dictionary/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass MagicDictionary:\n  def __init__(self):\n    self.dict = {}\n\n  def buildDict(self, dictionary: List[str]) -> None:\n    for word in dictionary:\n      for i, c in enumerate(word):\n        replaced = self._getReplaced(word, i)\n        self.dict[replaced] = '*' if replaced in self.dict else c\n\n  def search(self, searchWord: str) -> bool:\n    for i, c in enumerate(searchWord):\n      replaced = self._getReplaced(searchWord, i)\n      if self.dict.get(replaced, c) != c:\n        return True\n    return False\n\n  def _getReplaced(self, s: str, i: int) -> str:\n    return s[:i] + '*' + s[i + 1:]",
    "solution_code_java": "\t\t\t\n\nclass MagicDictionary {\n  public void buildDict(String[] dictionary) {\n    for (final String word : dictionary)\n      for (int i = 0; i < word.length(); ++i) {\n        final String replaced = getReplaced(word, i);\n        dict.put(replaced, dict.containsKey(replaced) ? '*' : word.charAt(i));\n      }\n  }\n\n  public boolean search(String searchWord) {\n    for (int i = 0; i < searchWord.length(); ++i) {\n      final String replaced = getReplaced(searchWord, i);\n      if (dict.getOrDefault(replaced, searchWord.charAt(i)) != searchWord.charAt(i))\n        return true;\n    }\n    return false;\n  }\n\n  private Map<String, Character> dict = new HashMap<>();\n\n  private String getReplaced(final String s, int i) {\n    return s.substring(0, i) + '*' + s.substring(i + 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MagicDictionary {\n public:\n  void buildDict(vector<string> dictionary) {\n    for (const string& word : dictionary)\n      for (int i = 0; i < word.length(); ++i) {\n        const string replaced = getReplaced(word, i);\n        dict[replaced] = dict.count(replaced) ? '*' : word[i];\n      }\n  }\n\n  bool search(string searchWord) {\n    for (int i = 0; i < searchWord.length(); ++i) {\n      const string replaced = getReplaced(searchWord, i);\n      if (dict.count(replaced) && dict[replaced] != searchWord[i])\n        return true;\n    }\n    return false;\n  }\n\n private:\n  unordered_map<string, char> dict;\n\n  string getReplaced(const string& s, int i) {\n    return s.substr(0, i) + '*' + s.substr(i + 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/676.html",
    "category": "Algorithms",
    "acceptance_rate": 56.549709023314584,
    "topics": [
      "Hash Table",
      "String",
      "Depth-First Search",
      "Design",
      "Trie"
    ],
    "hints": [],
    "likes": 1429,
    "dislikes": 212,
    "similar_questions": "[{\"title\": \"Implement Trie (Prefix Tree)\", \"titleSlug\": \"implement-trie-prefix-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Word in Dictionary\", \"titleSlug\": \"longest-word-in-dictionary\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"93.1K\", \"totalSubmission\": \"164.6K\", \"totalAcceptedRaw\": 93091, \"totalSubmissionRaw\": 164618, \"acRate\": \"56.5%\"}",
    "title_pt": "Implementar Dicionário Mágico",
    "description_pt": "<p>Projete uma estrutura de dados que seja inicializada com uma lista de palavras <strong>diferentes</strong>. Dada uma string, você deve determinar se é possível alterar exatamente um caractere nessa string para corresponder a qualquer palavra na estrutura de dados.</p>\n\n<p>Implemente a&nbsp;<code>MagicDictionary</code>&nbsp;class:</p>\n\n<ul>\n\t<li><code>MagicDictionary()</code>&nbsp;Inicializa o objeto.</li>\n\t<li><code>void buildDict(String[]&nbsp;dictionary)</code>&nbsp;Define a estrutura de dados&nbsp;com um array de strings distintas <code>dictionary</code>.</li>\n\t<li><code>bool search(String searchWord)</code> Retorna <code>true</code> se você puder alterar <strong>exatamente um caractere</strong> em <code>searchWord</code> para corresponder a qualquer string na estrutura de dados; caso contrário, retorna <code>false</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MagicDictionary&quot;, &quot;buildDict&quot;, &quot;search&quot;, &quot;search&quot;, &quot;search&quot;, &quot;search&quot;]\n[[], [[&quot;hello&quot;, &quot;leetcode&quot;]], [&quot;hello&quot;], [&quot;hhllo&quot;], [&quot;hell&quot;], [&quot;leetcoded&quot;]]\n<strong>Saída</strong>\n[null, null, false, true, false, false]\n\n<strong>Explicação</strong>\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict([&quot;hello&quot;, &quot;leetcode&quot;]);\nmagicDictionary.search(&quot;hello&quot;); // retorna False\nmagicDictionary.search(&quot;hhllo&quot;); // Podemos alterar o segundo &#39;h&#39; para &#39;e&#39; para corresponder a &quot;hello&quot;, então retornamos True\nmagicDictionary.search(&quot;hell&quot;); // retorna False\nmagicDictionary.search(&quot;leetcoded&quot;); // retorna False\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;=&nbsp;dictionary.length &lt;= 100</code></li>\n\t<li><code>1 &lt;=&nbsp;dictionary[i].length &lt;= 100</code></li>\n\t<li><code>dictionary[i]</code> consiste apenas de letras minúsculas do inglês.</li>\n\t<li>Todas as strings em&nbsp;<code>dictionary</code>&nbsp;são <strong>distintas</strong>.</li>\n\t<li><code>1 &lt;=&nbsp;searchWord.length &lt;= 100</code></li>\n\t<li><code>searchWord</code>&nbsp;consiste apenas de letras minúsculas do inglês.</li>\n\t<li><code>buildDict</code>&nbsp;será chamado apenas uma vez antes de <code>search</code>.</li>\n\t<li>No máximo <code>100</code> chamadas serão feitas para <code>search</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "677",
    "paidOnly": false,
    "title": "Map Sum Pairs",
    "titleSlug": "map-sum-pairs",
    "url": "https://leetcode.com/problems/map-sum-pairs",
    "description_url": "https://leetcode.com/problems/map-sum-pairs/description/",
    "description": "<p>Design a map that allows you to do the following:</p>\n\n<ul>\n\t<li>Maps a string key to a given value.</li>\n\t<li>Returns the sum of the values that have a key with a prefix equal to a given string.</li>\n</ul>\n\n<p>Implement the <code>MapSum</code> class:</p>\n\n<ul>\n\t<li><code>MapSum()</code> Initializes the <code>MapSum</code> object.</li>\n\t<li><code>void insert(String key, int val)</code> Inserts the <code>key-val</code> pair into the map. If the <code>key</code> already existed, the original <code>key-value</code> pair will be overridden to the new one.</li>\n\t<li><code>int sum(string prefix)</code> Returns the sum of all the pairs&#39; value whose <code>key</code> starts with the <code>prefix</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MapSum&quot;, &quot;insert&quot;, &quot;sum&quot;, &quot;insert&quot;, &quot;sum&quot;]\n[[], [&quot;apple&quot;, 3], [&quot;ap&quot;], [&quot;app&quot;, 2], [&quot;ap&quot;]]\n<strong>Output</strong>\n[null, null, 3, null, 5]\n\n<strong>Explanation</strong>\nMapSum mapSum = new MapSum();\nmapSum.insert(&quot;apple&quot;, 3);  \nmapSum.sum(&quot;ap&quot;);           // return 3 (<u>ap</u>ple = 3)\nmapSum.insert(&quot;app&quot;, 2);    \nmapSum.sum(&quot;ap&quot;);           // return 5 (<u>ap</u>ple + <u>ap</u>p = 3 + 2 = 5)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= key.length, prefix.length &lt;= 50</code></li>\n\t<li><code>key</code> and <code>prefix</code> consist of only lowercase English letters.</li>\n\t<li><code>1 &lt;= val &lt;= 1000</code></li>\n\t<li>At most <code>50</code> calls will be made to <code>insert</code> and <code>sum</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/map-sum-pairs/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Brute Force [Accepted]\n\n**Intuition and Algorithm**\n\nFor each key in the map, if that key starts with the given prefix, then add it to the answer.\n\n<iframe src=\"https://leetcode.com/playground/jNhyy639/shared\" frameBorder=\"0\" name=\"jNhyy639\" width=\"100%\" height=\"360\"></iframe>\n**Complexity Analysis**\n\n* Time Complexity: Every insert operation is $$O(1)$$. Every sum operation is $$O(N * P)$$ where $$N$$ is the number of items in the map, and $$P$$ is the length of the input prefix.\n\n* Space Complexity: The space used by `map` is linear in the size of all input `key` and `val` values combined.\n\n---\n\n### Approach #2: Prefix Hashmap [Accepted]\n\n**Intuition and Algorithm**\n\nWe can remember the answer for all possible prefixes in a HashMap `score`. When we get a new `(key, val)` pair, we update every prefix of `key` appropriately: each prefix will be changed by `delta = val - map[key]`, where `map` is the previously associated value of `key` (zero if undefined.)\n\n\n<iframe src=\"https://leetcode.com/playground/QYzALHGM/shared\" frameBorder=\"0\" name=\"QYzALHGM\" width=\"100%\" height=\"394\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: Every insert operation is $$O(K^2)$$, where $$K$$ is the length of the key, as $$K$$ strings are made of an average length of $$K$$.  Every sum operation is $$O(1)$$.\n\n* Space Complexity: The space used by `map` and `score` is linear in the size of all input `key` and `val` values combined.\n\n---\n\n### Approach #3: Trie [Accepted]\n\n**Intuition and Algorithm**\n\nSince we are dealing with prefixes, a Trie (prefix tree) is a natural data structure to approach this problem. For every node of the trie corresponding to some prefix, we will remember the desired answer (score) and store it at this node.  As in *Approach #2*, this involves modifying each node by `delta = val - map[key]`.\n\n<iframe src=\"https://leetcode.com/playground/FbmbbgFJ/shared\" frameBorder=\"0\" name=\"FbmbbgFJ\" width=\"100%\" height=\"513\"></iframe>\n\n\n\n**Complexity Analysis**\n\n* Time Complexity: Every insert operation is $$O(K)$$, where $$K$$ is the length of the key. Every sum operation is $$O(K)$$.\n\n* Space Complexity: The space used is linear in the size of the total input.",
    "solution_code_python": "\t\t\t\n\nclass TrieNode:\n  def __init__(self):\n    self.children: Dict[str, TrieNode] = defaultdict(TrieNode)\n    self.sum = 0\n\n\nclass MapSum:\n  def __init__(self):\n    self.root = TrieNode()\n    self.keyToVal = {}\n\n  def insert(self, key: str, val: int) -> None:\n    diff = val - self.keyToVal.get(key, 0)\n    node: TrieNode = self.root\n    for c in key:\n      if c not in node.children:\n        node.children[c] = TrieNode()\n      node = node.children[c]\n      node.sum += diff\n    self.keyToVal[key] = val\n\n  def sum(self, prefix: str) -> int:\n    node: TrieNode = self.root\n    for c in prefix:\n      if c not in node.children:\n        return 0\n      node = node.children[c]\n    return node.sum",
    "solution_code_java": "\t\t\t\n\nclass TrieNode {\n  public TrieNode[] children = new TrieNode[26];\n  public int sum = 0;\n}\n\nclass MapSum {\n  public void insert(String key, int val) {\n    final int diff = val - keyToVal.getOrDefault(key, 0);\n    TrieNode node = root;\n    for (final char c : key.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n      node.sum += diff;\n    }\n    keyToVal.put(key, val);\n  }\n\n  public int sum(String prefix) {\n    TrieNode node = root;\n    for (final char c : prefix.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        return 0;\n      node = node.children[i];\n    }\n    return node.sum;\n  }\n\n  private TrieNode root = new TrieNode();\n  private Map<String, Integer> keyToVal = new HashMap<>();\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  int sum = 0;\n  TrieNode() : children(26) {}\n};\n\nclass MapSum {\n public:\n  void insert(string key, int val) {\n    const int diff = val - keyToVal[key];\n    shared_ptr<TrieNode> node = root;\n    for (const char c : key) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n      node->sum += diff;\n    }\n    keyToVal[key] = val;\n  }\n\n  int sum(string prefix) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : prefix) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        return 0;\n      node = node->children[i];\n    }\n    return node->sum;\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n  unordered_map<string, int> keyToVal;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/677.html",
    "category": "Algorithms",
    "acceptance_rate": 56.70556490047659,
    "topics": [
      "Hash Table",
      "String",
      "Design",
      "Trie"
    ],
    "hints": [],
    "likes": 1689,
    "dislikes": 161,
    "similar_questions": "[{\"title\": \"Sort the Jumbled Numbers\", \"titleSlug\": \"sort-the-jumbled-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Prefix Scores of Strings\", \"titleSlug\": \"sum-of-prefix-scores-of-strings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"129.5K\", \"totalSubmission\": \"228.3K\", \"totalAcceptedRaw\": 129452, \"totalSubmissionRaw\": 228288, \"acRate\": \"56.7%\"}",
    "title_pt": "Pares de Soma de Mapa",
    "description_pt": "<p>Projete um mapa que permita fazer o seguinte:</p>\n\n<ul>\n\t<li>Mapeia uma chave de string para um valor dado.</li>\n\t<li>Retorna a soma dos valores que têm uma chave com um prefixo igual a uma string dada.</li>\n</ul>\n\n<p>Implemente a classe <code>MapSum</code>:</p>\n\n<ul>\n\t<li><code>MapSum()</code> Inicializa o objeto <code>MapSum</code>.</li>\n\t<li><code>void insert(String key, int val)</code> Insere o par <code>key-val</code> no mapa. Se a <code>key</code> já existia, o par original <code>key-value</code> será substituído pelo novo.</li>\n\t<li><code>int sum(string prefix)</code> Retorna a soma do valor de todos os pares cujo <code>key</code> começa com o <code>prefix</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MapSum&quot;, &quot;insert&quot;, &quot;sum&quot;, &quot;insert&quot;, &quot;sum&quot;]\n[[], [&quot;apple&quot;, 3], [&quot;ap&quot;], [&quot;app&quot;, 2], [&quot;ap&quot;]]\n<strong>Saída</strong>\n[null, null, 3, null, 5]\n\n<strong>Explicação</strong>\nMapSum mapSum = new MapSum();\nmapSum.insert(&quot;apple&quot;, 3);  \nmapSum.sum(&quot;ap&quot;);           // retorna 3 (<u>ap</u>ple = 3)\nmapSum.insert(&quot;app&quot;, 2);    \nmapSum.sum(&quot;ap&quot;);           // retorna 5 (<u>ap</u>ple + <u>ap</u>p = 3 + 2 = 5)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= key.length, prefix.length &lt;= 50</code></li>\n\t<li><code>key</code> e <code>prefix</code> consistem apenas de letras minúsculas do alfabeto inglês.</li>\n\t<li><code>1 &lt;= val &lt;= 1000</code></li>\n\t<li>No máximo <code>50</code> chamadas serão feitas a <code>insert</code> e <code>sum</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "678",
    "paidOnly": false,
    "title": "Valid Parenthesis String",
    "titleSlug": "valid-parenthesis-string",
    "url": "https://leetcode.com/problems/valid-parenthesis-string",
    "description_url": "https://leetcode.com/problems/valid-parenthesis-string/description/",
    "description": "<p>Given a string <code>s</code> containing only three types of characters: <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> and <code>&#39;*&#39;</code>, return <code>true</code> <em>if</em> <code>s</code> <em>is <strong>valid</strong></em>.</p>\n\n<p>The following rules define a <strong>valid</strong> string:</p>\n\n<ul>\n\t<li>Any left parenthesis <code>&#39;(&#39;</code> must have a corresponding right parenthesis <code>&#39;)&#39;</code>.</li>\n\t<li>Any right parenthesis <code>&#39;)&#39;</code> must have a corresponding left parenthesis <code>&#39;(&#39;</code>.</li>\n\t<li>Left parenthesis <code>&#39;(&#39;</code> must go before the corresponding right parenthesis <code>&#39;)&#39;</code>.</li>\n\t<li><code>&#39;*&#39;</code> could be treated as a single right parenthesis <code>&#39;)&#39;</code> or a single left parenthesis <code>&#39;(&#39;</code> or an empty string <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<pre><strong>Input:</strong> s = \"()\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 2:</strong></p>\n<pre><strong>Input:</strong> s = \"(*)\"\n<strong>Output:</strong> true\n</pre><p><strong class=\"example\">Example 3:</strong></p>\n<pre><strong>Input:</strong> s = \"(*))\"\n<strong>Output:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s[i]</code> is <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> or <code>&#39;*&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-parenthesis-string/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a string `s`, and the task is to check whether the string consisting of only `'('`, `')'` and `'*'` characters forms a valid sequence of parentheses. We consider `'*'` as a wildcard that can represent either `'('`, `')'` or an empty string.\n\n**Key Observations:**\n1. While traversing the string, the order of parentheses matters. `'('` must come before `')'` for a valid sequence.\n2. The number of left parentheses `'('` and right parentheses `')'` must be the same, including considering `'*'`.\n3. Using `'*'` optimally can help maintain the balance between open and closed parentheses.\n\n> Note: The term \"opening bracket\" refers to the left parenthesis `'('` and \"closing bracket\" refers to the right parenthesis `')'`.\n\n---\n\n### Approach 1: Top-Down Dynamic Programming - Memoization\n\n#### Intuition\n\nOne way to check if a given string of parentheses is valid is to use a stack. Whenever we encounter an opening bracket, we push it onto the stack. Whenever we encounter a closing bracket, we pop an opening bracket from the stack. If the stack is empty at the end of the string, then the string is valid. This is similar to problem [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/).\n\nHowever, the introduction of the wildcard character (`'*'`) complicates this approach. When dealing with the wildcard character (`'*'`), each `'*'` can represent an opening bracket, a closing bracket, or an empty string, leading to multiple branching possibilities.\n\nWe can explore all possible combinations in branching scenarios by applying recursive solutions.\n\nWe can track whether a string is valid by counting opening brackets:\n- When we encounter an opening bracket, we increment the count of opening brackets by 1.\n- Conversely, for a closing bracket, we decrement the count by 1.\n- After processing a valid string, the count of opening brackets is 0, indicating proper closure by corresponding closing brackets.\n\nNow, let's adapt our recursive solution based on these insights:\n- The base case occurs when the index reaches the end of the string. At this point, we return true if the count of opening brackets is 0, indicating a valid string, otherwise, we return false.\n- If the character at `s[index]` is not `'*'`, we adjust the count of opening brackets accordingly:\n  - If `s[index]` is `'('`, we increment the count of opening brackets by 1 and move to `index + 1`.\n  - If `s[index]` is `')'`, we decrement the count of opening brackets by 1 if it is positive, then move to `index + 1`.\n- If `s[index]` is `'*'`, we explore all possible scenarios:\n  - We can add an opening bracket (increment the count of opening brackets by 1) and move to `index + 1`.\n  - We can add a closing bracket (decrement the count of opening brackets by 1), if the count is positive, then move to `index + 1`.\n  - We can add an empty string and keep the count of opening brackets the same, then move to `index + 1`.\n\nThe recursive approach will result in Time Limit Exceeded (TLE) issues due to the exponential nature of possibilities ($3^{100}$ is a huge number).\n\nTo tackle this issue, we'll use dynamic programming (DP) with a two-dimensional table.\n\nThe DP table caches the results of subproblems, with rows representing different indices of the string `s` and columns representing different counts of opening brackets. Each cell stores a boolean value indicating whether the string from the current index with the given count of opening brackets is valid or not.\n\nBy caching the calculated states in the dp table, we can avoid recalculating the result for the same combination of index and opening bracket count. When encountering a state that has already been computed and stored in the dp table, instead of recursively exploring further, we can directly retrieve the cached result, significantly reducing the time complexity of the algorithm.\n\n#### Algorithm\n\n**`checkValidString` main function:**\n- Initialize a 2D vector `memo` of size `s.size() x s.size() - 1`, representing an uninitialized state.\n- Call the helper function `isValidString` with initial parameters `index = 0`, `openCount = 0`, and the given string `s`.\n- Return the result of `isValidString`.\n\n**`isValidString` helper function:**\n- Base case: If `index` reaches the end of the string (`index == s.size()`), return true if `openCount` is 0 (all brackets are balanced), and false otherwise.\n- Check if the result for the current `index` and `openCount` has already been computed (memoized) in `memo`. If so, return the memoized result.\n- Initialize `isValid` to false.\n- If the current character `s[index]` is `'*'`:\n  - Try treating `'*'` as `'('`:\n    - Call `isValidString` recursively with `index + 1` and `openCount + 1`.\n    - If the recursive call returns true, update `isValid` to true.\n  - If `openCount` is non-zero, try treating `'*'` as `')'`:\n    - Call `isValidString` recursively with `index + 1` and `openCount - 1`.\n    - If the recursive call returns true, update `isValid` to true.\n  - Try treating `'*'` as an empty character:\n    - Call `isValidString` recursively with `index + 1` and the same `openCount`.\n    - If the recursive call returns true, update `isValid` to true.\n- If the current character `s[index]` is `'('`:\n  - Call `isValidString` recursively with `index + 1` and `openCount + 1`.\n  - Update `isValid` with the result of the recursive call.\n- If the current character `s[index]` is `')'`:\n  - If `openCount` is non-zero (there are open parentheses):\n    - Call `isValidString` recursively with `index + 1` and `openCount - 1`.\n    - Update `isValid` with the result of the recursive call.\n- Memoize the result of `isValid` in `memo[index][openCount]`.\n- Return `isValid`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/76A7zEs3/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"76A7zEs3\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n- Time complexity: $O(n \\cdot n)$\n\n    The time complexity of the `isValidString` function can be analyzed by considering the number of unique subproblems that need to be solved. Since there are at most $n \\cdot n$ unique subproblems (indexed by `index` and `openCount`), where `n` is the length of the input string, and each subproblem is computed only once (due to memoization), the time complexity is bounded by the number of unique subproblems. Therefore, the time complexity can be stated as $O(n \\cdot n)$.\n\n- Space complexity: $O(n \\cdot n)$\n\n    The space complexity of the algorithm is primarily determined by two factors: the auxiliary space used for memoization and the recursion stack space. The memoization table, denoted as `memo`, consumes $O(n \\cdot n)$ space due to its size being proportional to the square of the length of the input string. Additionally, the recursion stack space can grow up to $O(n)$ in the worst case, constrained by the length of the input string, as each recursive call may add a frame to the stack. Therefore, the overall space complexity is the sum of these two components, resulting in $O(n \\cdot n) + O(n)$, which simplifies to $O(n \\cdot n)$.\n\n---\n\n### Approach 2: Bottom-Up Dynamic Programming - Tabulation\n\n#### Intuition\n\nTabulation is a dynamic programming technique that involves systematically iterating through all possible combinations of changing parameters. Since tabulation operates iteratively, rather than recursively, it does not require overhead for the recursive stack space, making it more efficient than memoization. We have two variables that change as we progress through the string: the current index we're considering and the count of open brackets encountered so far. To thoroughly explore the combinations, we use two nested loops to iterate through these variables.\n\nFirst, let's establish the base case:\n\n```java\nif (index == s.size()) return (openingBracket == 0);\n```\n\nWe represent this base case in our tabulation matrix as `dp[s.size()][0] = true`, indicating that a string with no brackets is valid.\n\nOur ultimate goal is to determine whether a valid parenthesis sequence can be achieved, and this information will be stored in `dp[0][0]`. To accomplish this, we traverse through every combination of index and open bracket count using the two nested loops. The outer loop iterates over the index, while the inner loop iterates over the count of open brackets (`openBracket`).\n\nThroughout this traversal, we evaluate each state and update our tabulation matrix accordingly. Upon completing the traversal of the entire string, if `dp[0][0]` evaluates to true, it signifies that there exists a valid parenthesis sequence.\n\n#### Algorithm\n\n- Initialize a 2D boolean vector `dp` of size `(n + 1) x (n + 1)`, where `n` is the length of the input string `s`. The `dp[index][openBracket]` represents whether the substring starting from index `i` is valid with `j` opening brackets.\n- Set the base case `dp[n][0]` as true, as an empty string with no opening brackets is always valid.\n- Iterate through the string from the end to the beginning (reverse order) using a nested loop:\n  - Outer loop: Iterate over the indices of the string from `n - 1` to `0`.\n  - Inner loop: Iterate over the number of opening brackets from `0` to `n`.\n  - For each character at index `index` and the current number of opening brackets `openBracket`, determine if the substring starting from `index` is valid with `openBracket` opening brackets:\n    - If the character is `'*'`:\n      - Try treating `'*'` as `'('`: Check if the substring starting from `index + 1` is valid with `openBracket + 1` opening brackets (`dp[index + 1][openBracket + 1]`).\n      - Try treating `'*'` as `')'`: If `openBracket > 0`, check if the substring starting from `index + 1` is valid with `openBracket - 1` opening brackets (`dp[index + 1][openBracket - 1]`).\n      - Try ignoring `'*'`: Check if the substring starting from `index + 1` is valid with the same number of opening brackets (`dp[index + 1][openBracket]`).\n    - If the character is `'('`:\n      - Try treating `'('` as an opening bracket: Check if the substring starting from `index + 1` is valid with `openBracket + 1` opening brackets (`dp[index + 1][openBracket + 1]`).\n    - If the character is `')'`:\n      - Try treating `')'` as a closing bracket: If `openBracket > 0`, check if the substring starting from `index + 1` is valid with `openBracket - 1` opening brackets (`dp[index + 1][openBracket - 1]`).\n    - Update the `dp[index][openBracket]` value based on the result of the above checks.\n- After completing the nested loops, the `dp[0][0]` value represents whether the entire input string is valid with no excess opening brackets.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/652HyVYi/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"652HyVYi\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n* Time complexity: $O(n \\cdot n)$\n\n    This is due to the nested loop structure, where the outer loop iterates over each character of the string, and the inner loop iterates over all possible counts of opening brackets.\n\n* Space complexity: $O(n \\cdot n)$\n\n    This is primarily due to the 2D array dp, which has dimensions $(n + 1) \\cdot (n + 1)$.\n\n---\n\n### Approach 3: Using Two Stacks\n\n#### Intuition\n\nIn Approach 1, we discussed how stacks can be used to solve brackets matching problems, but the wildcard `'*'` complicates this problem. We can tweak the stack method by creating two stacks: one for open brackets and another for the wildcard `'*'`.\n\nThis way, we maintain two stacks to process the string. The first stack keeps track of the indices of encountered open brackets, while the second stack is dedicated to storing the indices of asterisks.\n\nAs we traverse through the input string, every time we encounter an open bracket or an asterisk, we record its index by pushing it onto the respective stack.\n\nWhen we encounter a right bracket, we first attempt to balance this right bracket with an open bracket. To do so, we peek into our open bracket stack. If it's not empty, indicating that there's a matching open bracket available, we pop the index from this stack and proceed.\n\nHowever, if the open bracket stack is empty, we resort to using an asterisk. In this scenario, we peek into our asterisk stack and check if it contains any available asterisks. If so, we pop the index from this stack and proceed. This dynamic selection process ensures that we exhaust all possible options for balancing the right bracket.\n\nIf both the open bracket and asterisk stacks are empty, we return false, as this indicates an unmatched right bracket.\n\nOnce we've processed the whole string, our attention shifts to the remaining elements in the open bracket and asterisk stacks. Here, we check their positions relative to each other. We recognize that if an open bracket appears after the last encountered asterisk, there's no viable way to balance it because we have no available right brackets. Therefore, we return false. However, if no such mismatch is detected, we proceed to empty both stacks.\n\nHere we used a greedy strategy, prioritizing the use of open brackets over asterisks whenever possible to balance the right brackets. This ensures that we exhaust all available options for balancing before resorting to using asterisks. \n\nThe following is an illustration demonstrating the stack solution:\n\n!?!../Documents/678/stack_solution.json:961,446!?!\n\n#### Algorithm\n \n- Initialize two stacks: `openBrackets` to store indices of open brackets `'('`, and `asterisks` to store indices of asterisks `'*'`.\n- Iterate through the string `s` character by character:\n  - If the current character is `'('`, push its index onto the `openBrackets` stack.\n  - If the current character is `'*'`, push its index onto the `asterisks` stack.\n  - If the current character is `')'`:\n    - If `openBrackets` is not empty, pop an element from it (removing the matching open bracket).\n    - If `asterisks` is not empty, pop an element from `asterisks` (using an asterisk to balance the closing bracket).\n    - If neither an open bracket nor an asterisk is available, return false.\n- After iterating through the entire string, check if any remaining open brackets and asterisks can balance each other:\n  - While both `openBrackets` and `asterisks` are not empty:\n    - If the top element of `openBrackets` (representing an open bracket index) is greater than the top element of `asterisks` (representing an asterisk index), it means the open bracket appears after the asterisk, which cannot be balanced, so return false.\n    - Otherwise, pop elements from both `openBrackets` and `asterisks` stacks (matching an open bracket with an asterisk).\n- If after the above step, `openBrackets` is empty, it means all open brackets have been matched or balanced, so return true. Otherwise, return false (unmatched open brackets are remaining).\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/FMuDohBp/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"FMuDohBp\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n* Time complexity: $O(n)$\n\n    The algorithm iterates through the entire string once, taking $O(n)$ time. Additionally, in the worst case, it may need to traverse both the `openBrackets` and `asterisks` stacks simultaneously to check for balanced parentheses, which also takes $O(n)$ time. Thus, the overall time complexity is $O(n)$.\n\n* Space complexity: $O(n)$\n\n    The algorithm uses two stacks, `openBrackets`, and `asterisks`, which could potentially hold up to $O(n)$ elements combined in the worst case. Additionally, there are a few extra variables and loop counters, which require constant space. Therefore, the overall space complexity is $O(n)$.\n\n---\n\n### Approach 4: Two Pointer\n\n#### Intuition\n\nThe above approaches all use significant extra space to solve the problem. Let's develop an approach that uses constant space.\n\nWe can use a two-pointer greedy approach, which checks the balance between open and closed brackets from both ends of the array simultaneously, ensuring that no surplus or deficit of brackets occurs at any point during the iteration.\n\nWe initiate two pointers, one starting from the left and the other from the right of the array.\n\nStarting from the left, we iterate through the array, counting the occurrences of open brackets `'('` and asterisks `'*'`. Whenever we encounter a closed bracket `')'`, we decrement the count of open brackets. This decrement operation mimics the process of matching an open bracket with a closed one.\n\nSimultaneously, we traverse from the right of the array, counting the occurrences of closed brackets `')'` and asterisks `'*'`. Whenever we encounter an open bracket `'('`, we decrement the count of closed brackets. This simulates the process of matching a closed bracket with an open one.\n\nThroughout this process, if either the count of open brackets or the count of closed brackets falls below zero (i.e., becomes negative), we immediately conclude that the sequence is invalid, as it indicates a surplus of closed brackets without corresponding open ones, or vice versa.\n\nIf neither of the counters becomes negative throughout the iteration, the sequence is valid, and we return true.\n\nThe following is an illustration demonstrating the two pointer solution:\n\n!?!../Documents/678/twopointer.json:960,352!?!\n\n#### Algorithm\n \n- Initialize two variables, `openCount` and `closeCount`, to keep track of the number of open and close parentheses (or asterisks) encountered so far.\n- Calculate the length of the input string `s` and store it in the variable `length`.\n- Traverse the string from both ends simultaneously using a single loop:\n  - Iterate over the indices `i` from 0 to `length` (inclusive).\n  - For each index `i`:\n    - If the character at index `i` is `'('` or `'*'`, increment `openCount`.\n    - Otherwise, decrement `openCount`.\n    - If the character at index `length - i` is `')'` or `'*'`, increment `closeCount`.\n    - Otherwise, decrement `closeCount`.\n  - If at any point during the loop, either `openCount` or `closeCount` becomes negative, it means there are more closing parentheses than open parentheses (or asterisks), which makes the string invalid. In this case, return false.\n- After the loop finishes traversing the entire string without returning, `openCount` and `closeCount` are non-negative, which means that the string is valid, so return true.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/UGc495d9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"UGc495d9\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input string.\n\n* Time complexity: $O(n)$\n\n    The time complexity is $O(n)$, as we iterate through the string once.\n\n* Space complexity: $O(1)$\n\n    The space complexity is $O(1)$, as we use a constant amount of extra space to store the `openCount` and `closeCount` variables.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def checkValidString(self, s: str) -> bool:\n    low = 0\n    high = 0\n\n    for c in s:\n      if c == '(':\n        low += 1\n        high += 1\n      elif c == ')':\n        if low > 0:\n          low -= 1\n        high -= 1\n      else:\n        if low > 0:\n          low -= 1\n        high += 1\n      if high < 0:\n        return False\n\n    return low == 0",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean checkValidString(final String s) {\n    int low = 0;  // Lower bound of valid '(' count\n    int high = 0; // Upper bound of valid '(' count\n\n    for (final char c : s.toCharArray()) {\n      switch (c) {\n        case '(':\n          ++low;\n          ++high;\n          break;\n        case ')':\n          low = Math.max(0, --low);\n          --high;\n          break;\n        case '*':\n          low = Math.max(0, --low);\n          ++high;\n          break;\n      }\n      if (high < 0)\n        return false;\n    }\n\n    return low == 0;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool checkValidString(const string& s) {\n    int low = 0;   // Lower bound of valid '(' count\n    int high = 0;  // Upper bound of valid '(' count\n\n    for (const char c : s) {\n      switch (c) {\n        case '(':\n          ++low;\n          ++high;\n          break;\n        case ')':\n          low = max(0, --low);\n          --high;\n          break;\n        case '*':\n          low = max(0, --low);\n          ++high;\n          break;\n      }\n      if (high < 0)\n        return false;\n    }\n\n    return low == 0;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/678.html",
    "category": "Algorithms",
    "acceptance_rate": 38.790029090945296,
    "topics": [
      "String",
      "Dynamic Programming",
      "Stack",
      "Greedy"
    ],
    "hints": [
      "Use backtracking to explore all possible combinations of treating '*' as either '(', ')', or an empty string. If any combination leads to a valid string, return true.",
      "DP[i][j] represents whether the substring s[i:j] is valid.",
      "Keep track of the count of open parentheses encountered so far. If you encounter a close parenthesis, it should balance with an open parenthesis. Utilize a stack to handle this effectively.",
      "How about using 2 stacks instead of 1? Think about it."
    ],
    "likes": 6522,
    "dislikes": 203,
    "similar_questions": "[{\"title\": \"Special Binary String\", \"titleSlug\": \"special-binary-string\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Check if a Parentheses String Can Be Valid\", \"titleSlug\": \"check-if-a-parentheses-string-can-be-valid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"467.5K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 467486, \"totalSubmissionRaw\": 1205172, \"acRate\": \"38.8%\"}",
    "title_pt": "String de Parênteses Válida",
    "description_pt": "<p>Dada uma string <code>s</code> contendo apenas três tipos de caracteres: <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> e <code>&#39;*&#39;</code>, retorne <code>true</code> <em>se</em> <code>s</code> <em>for <strong>válida</strong></em>.</p>\n\n<p>As regras a seguir definem uma string <strong>válida</strong>:</p>\n\n<ul>\n\t<li>Qualquer parêntese esquerdo <code>&#39;(&#39;</code> deve ter um parêntese direito correspondente <code>&#39;)&#39;</code>.</li>\n\t<li>Qualquer parêntese direito <code>&#39;)&#39;</code> deve ter um parêntese esquerdo correspondente <code>&#39;(&#39;</code>.</li>\n\t<li>O parêntese esquerdo <code>&#39;(&#39;</code> deve vir antes do parêntese direito correspondente <code>&#39;)&#39;</code>.</li>\n\t<li><code>&#39;*&#39;</code> pode ser tratado como um único parêntese direito <code>&#39;)&#39;</code> ou um único parêntese esquerdo <code>&#39;(&#39;</code> ou uma string vazia <code>&quot;&quot;</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<pre><strong>Entrada:</strong> s = \"()\"\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 2:</strong></p>\n<pre><strong>Entrada:</strong> s = \"(*)\"\n<strong>Saída:</strong> true\n</pre><p><strong class=\"example\">Exemplo 3:</strong></p>\n<pre><strong>Entrada:</strong> s = \"(*))\"\n<strong>Saída:</strong> true\n</pre>\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s[i]</code> é <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> ou <code>&#39;*&#39;</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Use backtracking para explorar todas as combinações possíveis de tratar '*' como '(', ')', ou uma string vazia. Se qualquer combinação levar a uma string válida, retorne true.",
      "Dica 2: DP[i][j] representa se a substring s[i:j] é válida.",
      "Dica 3: Mantenha o controle da contagem de parênteses de abertura encontrados até agora. Se você encontrar um parêntese de fechamento, ele deve ser balanceado com um parêntese de abertura. Utilize uma pilha para lidar com isso de forma eficaz.",
      "Dica 4: Que tal usar 2 pilhas em vez de 1? Pense nisso."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "679",
    "paidOnly": false,
    "title": "24 Game",
    "titleSlug": "24-game",
    "url": "https://leetcode.com/problems/24-game",
    "description_url": "https://leetcode.com/problems/24-game/description/",
    "description": "<p>You are given an integer array <code>cards</code> of length <code>4</code>. You have four cards, each containing a number in the range <code>[1, 9]</code>. You should arrange the numbers on these cards in a mathematical expression using the operators <code>[&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;]</code> and the parentheses <code>&#39;(&#39;</code> and <code>&#39;)&#39;</code> to get the value 24.</p>\n\n<p>You are restricted with the following rules:</p>\n\n<ul>\n\t<li>The division operator <code>&#39;/&#39;</code> represents real division, not integer division.\n\n\t<ul>\n\t\t<li>For example, <code>4 / (1 - 2 / 3) = 4 / (1 / 3) = 12</code>.</li>\n\t</ul>\n\t</li>\n\t<li>Every operation done is between two numbers. In particular, we cannot use <code>&#39;-&#39;</code> as a unary operator.\n\t<ul>\n\t\t<li>For example, if <code>cards = [1, 1, 1, 1]</code>, the expression <code>&quot;-1 - 1 - 1 - 1&quot;</code> is <strong>not allowed</strong>.</li>\n\t</ul>\n\t</li>\n\t<li>You cannot concatenate numbers together\n\t<ul>\n\t\t<li>For example, if <code>cards = [1, 2, 1, 2]</code>, the expression <code>&quot;12 + 12&quot;</code> is not valid.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>Return <code>true</code> if you can get such expression that evaluates to <code>24</code>, and <code>false</code> otherwise.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> cards = [4,1,8,7]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> (8-4) * (7-1) = 24\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> cards = [1,2,1,2]\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>cards.length == 4</code></li>\n\t<li><code>1 &lt;= cards[i] &lt;= 9</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/24-game/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def judgePoint24(self, nums: List[int]) -> bool:\n    def generate(a: float, b: float) -> List[float]:\n      return [a * b,\n              math.inf if b == 0 else a / b,\n              math.inf if a == 0 else b / a,\n              a + b, a - b, b - a]\n\n    def dfs(nums: List[float]) -> bool:\n      if len(nums) == 1:\n        return abs(nums[0] - 24.0) < 0.001\n\n      for i in range(len(nums)):\n        for j in range(i + 1, len(nums)):\n          for num in generate(nums[i], nums[j]):\n            nextRound = [num]\n            for k in range(len(nums)):\n              if k == i or k == j:\n                continue\n              nextRound.append(nums[k])\n            if dfs(nextRound):\n              return True\n\n      return False\n\n    return dfs(nums)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean judgePoint24(int[] nums) {\n    List<Double> doubleNums = new ArrayList<>();\n\n    for (final int num : nums)\n      doubleNums.add((double) num);\n\n    return dfs(doubleNums);\n  }\n\n  private boolean dfs(List<Double> nums) {\n    if (nums.size() == 1)\n      return Math.abs(nums.get(0) - 24.0) < 0.001;\n\n    for (int i = 0; i < nums.size(); ++i)\n      for (int j = i + 1; j < nums.size(); ++j)\n        for (final double num : generate(nums.get(i), nums.get(j))) {\n          List<Double> nextRound = new ArrayList<>(Arrays.asList(num));\n          for (int k = 0; k < nums.size(); ++k) {\n            if (k == i || k == j) // Used in generate()\n              continue;\n            nextRound.add(nums.get(k));\n          }\n          if (dfs(nextRound))\n            return true;\n        }\n\n    return false;\n  }\n\n  private double[] generate(double a, double b) {\n    return new double[] {a * b, a / b, b / a, a + b, a - b, b - a};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool judgePoint24(vector<int>& nums) {\n    vector<double> doubleNums;\n\n    for (const int num : nums)\n      doubleNums.push_back(num);\n\n    return dfs(doubleNums);\n  }\n\n private:\n  bool dfs(vector<double>& nums) {\n    if (nums.size() == 1)\n      return abs(nums[0] - 24) < 0.001;\n\n    for (int i = 0; i < nums.size(); ++i)\n      for (int j = 0; j < i; ++j) {\n        for (const double num : generate(nums[i], nums[j])) {\n          vector<double> nextRound{num};\n          for (int k = 0; k < nums.size(); ++k) {\n            if (k == i || k == j)  // Used in generate()\n              continue;\n            nextRound.push_back(nums[k]);\n          }\n          if (dfs(nextRound))\n            return true;\n        }\n      }\n\n    return false;\n  }\n\n  vector<double> generate(double a, double b) {\n    return {a * b, a / b, b / a, a + b, a - b, b - a};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/679.html",
    "category": "Algorithms",
    "acceptance_rate": 49.92696967093393,
    "topics": [
      "Array",
      "Math",
      "Backtracking"
    ],
    "hints": [],
    "likes": 1509,
    "dislikes": 256,
    "similar_questions": "[]",
    "stats": "{\"totalAccepted\": \"87.2K\", \"totalSubmission\": \"174.6K\", \"totalAcceptedRaw\": 87162, \"totalSubmissionRaw\": 174582, \"acRate\": \"49.9%\"}",
    "title_pt": "Jogo dos 24",
    "description_pt": "<p>Você recebe um array de inteiros <code>cards</code> de comprimento <code>4</code>. Você tem quatro cartas, cada uma contendo um número no intervalo <code>[1, 9]</code>. Você deve organizar os números nessas cartas em uma expressão matemática usando os operadores <code>[&#39;+&#39;, &#39;-&#39;, &#39;*&#39;, &#39;/&#39;]</code> e os parênteses <code>&#39;(&#39;</code> e <code>&#39;)&#39;</code> para obter o valor 24.</p>\n\n<p>Você está restrito pelas seguintes regras:</p>\n\n<ul>\n\t<li>O operador de divisão <code>&#39;/&#39;</code> representa divisão real, não divisão inteira.\n\n\t<ul>\n\t\t<li>Por exemplo, <code>4 / (1 - 2 / 3) = 4 / (1 / 3) = 12</code>.</li>\n\t</ul>\n\t</li>\n\t<li>Toda operação realizada é entre dois números. Em particular, não podemos usar <code>&#39;-&#39;</code> como operador unário.\n\t<ul>\n\t\t<li>Por exemplo, se <code>cards = [1, 1, 1, 1]</code>, a expressão <code>&quot;-1 - 1 - 1 - 1&quot;</code> <strong>não é permitida</strong>.</li>\n\t</ul>\n\t</li>\n\t<li>Você não pode concatenar números juntos\n\t<ul>\n\t\t<li>Por exemplo, se <code>cards = [1, 2, 1, 2]</code>, a expressão <code>&quot;12 + 12&quot;</code> não é válida.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>Retorne <code>true</code> se você puder obter tal expressão que avalie para <code>24</code>, e <code>false</code> caso contrário.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> cards = [4,1,8,7]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> (8-4) * (7-1) = 24\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> cards = [1,2,1,2]\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>cards.length == 4</code></li>\n\t<li><code>1 &lt;= cards[i] &lt;= 9</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "680",
    "paidOnly": false,
    "title": "Valid Palindrome II",
    "titleSlug": "valid-palindrome-ii",
    "url": "https://leetcode.com/problems/valid-palindrome-ii",
    "description_url": "https://leetcode.com/problems/valid-palindrome-ii/description/",
    "description": "<p>Given a string <code>s</code>, return <code>true</code> <em>if the </em><code>s</code><em> can be palindrome after deleting <strong>at most one</strong> character from it</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;aba&quot;\n<strong>Output:</strong> true\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abca&quot;\n<strong>Output:</strong> true\n<strong>Explanation:</strong> You could delete the character &#39;c&#39;.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;abc&quot;\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/valid-palindrome-ii/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def validPalindrome(self, s: str) -> bool:\n    def validPalindrome(l: int, r: int) -> bool:\n      return all(s[i] == s[r - i + l] for i in range(l, (l + r) // 2 + 1))\n\n    n = len(s)\n\n    for i in range(n // 2):\n      if s[i] != s[~i]:\n        return validPalindrome(i + 1, n - 1 - i) or validPalindrome(i, n - 2 - i)\n\n    return True",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean validPalindrome(String s) {\n    for (int l = 0, r = s.length() - 1; l < r; ++l, --r)\n      if (s.charAt(l) != s.charAt(r))\n        return validPalindrome(s, l + 1, r) || validPalindrome(s, l, r - 1);\n    return true;\n  }\n\n  private boolean validPalindrome(final String s, int l, int r) {\n    while (l < r)\n      if (s.charAt(l++) != s.charAt(r--))\n        return false;\n    return true;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool validPalindrome(string s) {\n    for (int l = 0, r = s.length() - 1; l < r; ++l, --r)\n      if (s[l] != s[r])\n        return validPalindrome(s, l + 1, r) ||\n               validPalindrome(s, l, r - 1);\n    return true;\n  }\n\n private:\n  bool validPalindrome(const string& s, int l, int r) {\n    while (l < r)\n      if (s[l++] != s[r--])\n        return false;\n    return true;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/680.html",
    "category": "Algorithms",
    "acceptance_rate": 42.8751512458266,
    "topics": [
      "Two Pointers",
      "String",
      "Greedy"
    ],
    "hints": [],
    "likes": 8572,
    "dislikes": 482,
    "similar_questions": "[{\"title\": \"Valid Palindrome\", \"titleSlug\": \"valid-palindrome\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome III\", \"titleSlug\": \"valid-palindrome-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome IV\", \"titleSlug\": \"valid-palindrome-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"957.1K\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 957099, \"totalSubmissionRaw\": 2232293, \"acRate\": \"42.9%\"}",
    "title_pt": "Validar Palíndromo II",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne <code>true</code> <em>se a string </em><code>s</code><em> puder ser um palíndromo após deletar <strong>no máximo um</strong> caractere dela</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;aba&quot;\n<strong>Saída:</strong> true\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abca&quot;\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> Você poderia deletar o caractere &#39;c&#39;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;abc&quot;\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s</code> consiste em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "682",
    "paidOnly": false,
    "title": "Baseball Game",
    "titleSlug": "baseball-game",
    "url": "https://leetcode.com/problems/baseball-game",
    "description_url": "https://leetcode.com/problems/baseball-game/description/",
    "description": "<p>You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.</p>\n\n<p>You are given a list of strings <code>operations</code>, where <code>operations[i]</code> is the <code>i<sup>th</sup></code> operation you must apply to the record and is one of the following:</p>\n\n<ul>\n\t<li>An integer <code>x</code>.\n\n\t<ul>\n\t\t<li>Record a new score of <code>x</code>.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;+&#39;</code>.\n\t<ul>\n\t\t<li>Record a new score that is the sum of the previous two scores.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;D&#39;</code>.\n\t<ul>\n\t\t<li>Record a new score that is the double of the previous score.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;C&#39;</code>.\n\t<ul>\n\t\t<li>Invalidate the previous score, removing it from the record.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>Return <em>the sum of all the scores on the record after applying all the operations</em>.</p>\n\n<p>The test cases are generated such that the answer and all intermediate calculations fit in a <strong>32-bit</strong> integer and that all operations are valid.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> ops = [&quot;5&quot;,&quot;2&quot;,&quot;C&quot;,&quot;D&quot;,&quot;+&quot;]\n<strong>Output:</strong> 30\n<strong>Explanation:</strong>\n&quot;5&quot; - Add 5 to the record, record is now [5].\n&quot;2&quot; - Add 2 to the record, record is now [5, 2].\n&quot;C&quot; - Invalidate and remove the previous score, record is now [5].\n&quot;D&quot; - Add 2 * 5 = 10 to the record, record is now [5, 10].\n&quot;+&quot; - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> ops = [&quot;5&quot;,&quot;-2&quot;,&quot;4&quot;,&quot;C&quot;,&quot;D&quot;,&quot;9&quot;,&quot;+&quot;,&quot;+&quot;]\n<strong>Output:</strong> 27\n<strong>Explanation:</strong>\n&quot;5&quot; - Add 5 to the record, record is now [5].\n&quot;-2&quot; - Add -2 to the record, record is now [5, -2].\n&quot;4&quot; - Add 4 to the record, record is now [5, -2, 4].\n&quot;C&quot; - Invalidate and remove the previous score, record is now [5, -2].\n&quot;D&quot; - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n&quot;9&quot; - Add 9 to the record, record is now [5, -2, -4, 9].\n&quot;+&quot; - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n&quot;+&quot; - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> ops = [&quot;1&quot;,&quot;C&quot;]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong>\n&quot;1&quot; - Add 1 to the record, record is now [1].\n&quot;C&quot; - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= operations.length &lt;= 1000</code></li>\n\t<li><code>operations[i]</code> is <code>&quot;C&quot;</code>, <code>&quot;D&quot;</code>, <code>&quot;+&quot;</code>, or a string representing an integer in the range <code>[-3 * 10<sup>4</sup>, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li>For operation <code>&quot;+&quot;</code>, there will always be at least two previous scores on the record.</li>\n\t<li>For operations <code>&quot;C&quot;</code> and <code>&quot;D&quot;</code>, there will always be at least one previous score on the record.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/baseball-game/solutions/",
    "solution": "### Approach #1: Stack [Accepted]\n\n**Intuition and Algorithm**\n\nLet's maintain the value of each valid round on a stack as we process the data. A stack is ideal since we only deal with operations involving the last or second-last valid round.\n\n<iframe src=\"https://leetcode.com/playground/FRAbgcgJ/shared\" frameBorder=\"0\" name=\"FRAbgcgJ\" width=\"100%\" height=\"462\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `ops`. We parse through every element in the given array once, and do $$O(1)$$ work for each element.\n\n* Space Complexity: $$O(N)$$, the space used to store our `stack`.",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/682.html",
    "category": "Algorithms",
    "acceptance_rate": 78.62577572667992,
    "topics": [
      "Array",
      "Stack",
      "Simulation"
    ],
    "hints": [],
    "likes": 3057,
    "dislikes": 1941,
    "similar_questions": "[{\"title\": \"Crawler Log Folder\", \"titleSlug\": \"crawler-log-folder\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"464.1K\", \"totalSubmission\": \"590.3K\", \"totalAcceptedRaw\": 464091, \"totalSubmissionRaw\": 590252, \"acRate\": \"78.6%\"}",
    "title_pt": "Jogo de Beisebol",
    "description_pt": "<p>Você está mantendo as pontuações de um jogo de beisebol com regras estranhas. No início do jogo, você começa com um registro vazio.</p>\n\n<p>Você recebe uma lista de strings <code>operations</code>, em que <code>operations[i]</code> é a <code>i<sup>ésima</sup></code> operação que você deve aplicar ao registro e é uma das seguintes:</p>\n\n<ul>\n\t<li>Um inteiro <code>x</code>.\n\n\t<ul>\n\t\t<li>Registre uma nova pontuação de <code>x</code>.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;+&#39;</code>.\n\t<ul>\n\t\t<li>Registre uma nova pontuação que é a soma das duas pontuações anteriores.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;D&#39;</code>.\n\t<ul>\n\t\t<li>Registre uma nova pontuação que é o dobro da pontuação anterior.</li>\n\t</ul>\n\t</li>\n\t<li><code>&#39;C&#39;</code>.\n\t<ul>\n\t\t<li>Invalide a pontuação anterior, removendo-a do registro.</li>\n\t</ul>\n\t</li>\n</ul>\n\n<p>Retorne <em>a soma de todas as pontuações no registro após aplicar todas as operações</em>.</p>\n\n<p>Os casos de teste são gerados de modo que a resposta e todos os cálculos intermediários caibam em um inteiro de <strong>32 bits</strong> e que todas as operações sejam válidas.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ops = [&quot;5&quot;,&quot;2&quot;,&quot;C&quot;,&quot;D&quot;,&quot;+&quot;]\n<strong>Saída:</strong> 30\n<strong>Explicação:</strong>\n&quot;5&quot; - Adicione 5 ao registro, o registro agora é [5].\n&quot;2&quot; - Adicione 2 ao registro, o registro agora é [5, 2].\n&quot;C&quot; - Invalide e remova a pontuação anterior, o registro agora é [5].\n&quot;D&quot; - Adicione 2 * 5 = 10 ao registro, o registro agora é [5, 10].\n&quot;+&quot; - Adicione 5 + 10 = 15 ao registro, o registro agora é [5, 10, 15].\nA soma total é 5 + 10 + 15 = 30.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ops = [&quot;5&quot;,&quot;-2&quot;,&quot;4&quot;,&quot;C&quot;,&quot;D&quot;,&quot;9&quot;,&quot;+&quot;,&quot;+&quot;]\n<strong>Saída:</strong> 27\n<strong>Explicação:</strong>\n&quot;5&quot; - Adicione 5 ao registro, o registro agora é [5].\n&quot;-2&quot; - Adicione -2 ao registro, o registro agora é [5, -2].\n&quot;4&quot; - Adicione 4 ao registro, o registro agora é [5, -2, 4].\n&quot;C&quot; - Invalide e remova a pontuação anterior, o registro agora é [5, -2].\n&quot;D&quot; - Adicione 2 * -2 = -4 ao registro, o registro agora é [5, -2, -4].\n&quot;9&quot; - Adicione 9 ao registro, o registro agora é [5, -2, -4, 9].\n&quot;+&quot; - Adicione -4 + 9 = 5 ao registro, o registro agora é [5, -2, -4, 9, 5].\n&quot;+&quot; - Adicione 9 + 5 = 14 ao registro, o registro agora é [5, -2, -4, 9, 5, 14].\nA soma total é 5 + -2 + -4 + 9 + 5 + 14 = 27.\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> ops = [&quot;1&quot;,&quot;C&quot;]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong>\n&quot;1&quot; - Adicione 1 ao registro, o registro agora é [1].\n&quot;C&quot; - Invalide e remova a pontuação anterior, o registro agora é [].\nComo o registro está vazio, a soma total é 0.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= operations.length &lt;= 1000</code></li>\n\t<li><code>operations[i]</code> é <code>&quot;C&quot;</code>, <code>&quot;D&quot;</code>, <code>&quot;+&quot;</code>, ou uma string que representa um inteiro no intervalo <code>[-3 * 10<sup>4</sup>, 3 * 10<sup>4</sup>]</code>.</li>\n\t<li>Para a operação <code>&quot;+&quot;</code>, sempre haverá pelo menos duas pontuações anteriores no registro.</li>\n\t<li>Para as operações <code>&quot;C&quot;</code> e <code>&quot;D&quot;</code>, sempre haverá pelo menos uma pontuação anterior no registro.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "684",
    "paidOnly": false,
    "title": "Redundant Connection",
    "titleSlug": "redundant-connection",
    "url": "https://leetcode.com/problems/redundant-connection",
    "description_url": "https://leetcode.com/problems/redundant-connection/description/",
    "description": "<p>In this problem, a tree is an <strong>undirected graph</strong> that is connected and has no cycles.</p>\n\n<p>You are given a graph that started as a tree with <code>n</code> nodes labeled from <code>1</code> to <code>n</code>, with one additional edge added. The added edge has two <strong>different</strong> vertices chosen from <code>1</code> to <code>n</code>, and was not an edge that already existed. The graph is represented as an array <code>edges</code> of length <code>n</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>\n\n<p>Return <em>an edge that can be removed so that the resulting graph is a tree of </em><code>n</code><em> nodes</em>. If there are multiple answers, return the answer that occurs last in the input.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg\" style=\"width: 222px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> edges = [[1,2],[1,3],[2,3]]\n<strong>Output:</strong> [2,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg\" style=\"width: 382px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\n<strong>Output:</strong> [1,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == edges.length</code></li>\n\t<li><code>3 &lt;= n &lt;= 1000</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>1 &lt;= a<sub>i</sub> &lt; b<sub>i</sub> &lt;= edges.length</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>There are no repeated edges.</li>\n\t<li>The given graph is connected.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/redundant-connection/solutions/",
    "solution": "## Solution\n\n---\n\n### Overview\n\nWe are given a graph consisting of $N$ nodes and $N − 1$ edges, which means the graph initially forms a tree. A tree is a special type of graph that is connected (there is a path between any two nodes) and acyclic (it does not contain any cycles). However, a new edge is added to the tree, connecting two nodes that are already part of the graph. This new edge creates a cycle because there are now two distinct paths between some pairs of nodes. As a result, the graph is no longer a tree but a single-cycle graph.\n\nOur goal is to identify the edge that, if removed, will restore the graph to its original state as a tree. Since the tree must be connected and acyclic, removing any edge from the cycle will break the cycle and turn the graph into a tree. However, if there are multiple edges that can be removed to achieve this, we are required to return the edge that appears last in the given list of edges.\n\n---\n\n### Approach 1: Depth-First Search - Brute Force\n\n#### Intuition\n\nThe key idea is that we can safely discard an edge if it connects two nodes that are already part of the same connected component. In simple terms, this means that if there's already a path between the two nodes (even without the current edge), adding this edge would create a cycle, making it redundant.\n\nTo check if a path exists between two nodes, we can use graph traversal techniques such as Depth-First Search (DFS) or Breadth-First Search (BFS). In this approach, we will use DFS to verify whether the two nodes of each edge are already connected. If you're unfamiliar with DFS, you can explore this helpful [DFS guide](https://leetcode.com/explore/featured/card/graph/).\n\nNow, as we go through the edges, we examine each one. For every edge, we use DFS to determine if the two nodes it connects are already part of the same connected component. If a path already exists, that means the nodes are connected, and we can safely discard the edge because it would create a cycle. If there’s no existing path, we know that the edge is essential for connecting the nodes, so we add it to our graph.\n\nOne important thing to remember is that we process the edges in the order they appear in the input list. This ensures that if multiple redundant edges are present, the last one we process will be the one that forms the cycle.\n\n#### Algorithm\n\n1. Define the function `isConnected` that takes the source node `src`, target node `target`, boolean array `visited`, and the adjacency list `adjList`. This returns true if there's a path between `src` and `target` with the edges in the list `adjList` using DFS:\n    - Mark the current node `src` as visited.\n    - Initialize the variable `isFound` to `false`, this is going to denote the answer.\n    - Recursively traverse to the unvisited adjacent nodes and check if the `target` node is found.\n    - Return `isFound` in the end.\n2. Iterate over the list `edges` from left to and right and for each `edge`:\n    - Initialize an empty array `visited` with all indices as `false`.\n    - Call the method `isConnected` and if it returns `true` return `edge`\n    - Otherwise, add the edge to the adjacency list `adjList`.\n3. If the input is valid, this part of the code should be unreachable. Return an empty list `{}` in such cases.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Ydw6rbYM/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Ydw6rbYM\"></iframe>\n\n#### Complexity Analysis\n\nHere, $N$ is the number of nodes and edges in the given graph.\n\n- Time complexity: $O(N^2)$.\n\n    Iterating over each of the $N$ edges and performing a DFS to check if the nodes are already connected would result in $N \\times N$ operations. The time complexity of a DFS is $O(V+E)$, where $V$ is the number of vertices and $E$ is the number of edges. In this problem, both $V$ and $E$ are equal to $N$. Therefore, the total time complexity is $O(N^2)$.\n\n- Space complexity: $O(N)$\n\n    The adjacency list `adjList` will store $N$ edges, and the size of the `visited` array is $N$. Additionally, space is required for the active stack calls in the DFS, which can be as large as one per node. Therefore, the total space complexity is $O(N)$.\n\n---\n\n### Approach 2: Depth-First Search - Single Traversal\n\n#### Intuition\n\nWe cannot remove just any edge from the graph, as doing so might disconnect the graph. The edge we remove must be part of the cycle. If we can identify the edges or nodes involved in the cycle, we can choose to remove the edge that appears last in the input edge list.\n\nTo detect the cycle in the graph, we need to identify at least one node that belongs to it. This can be accomplished using DFS while keeping track of the parent of each node, where the parent represents the node from which we reached the current node. If we encounter a node that has already been visited and the node we are coming from is different from its parent, we can conclude that the node is part of the cycle.\n\nOnce we identify a node in the cycle, we can backtrack through the parent array to find all the other nodes that are part of the cycle, until we return to the starting node. We will mark all these cycle nodes in an unordered map. Then, we iterate over the edges in reverse order, and if both nodes of an edge are marked in the map, we can discard this edge as it forms the cycle. Finally, we can return this redundant edge.\n\n![fig](../Figures/684/684A.png)\n\n#### Algorithm\n\n1. Initialize Variables:\n\n    - Set `cycleStart` to `-1` to mark the start of the cycle.\n    - Create a `visited` array to keep track of visited nodes.\n    - Create a `parent` array to store the parent of each node in the DFS traversal.\n    - Initialize an adjacency list `adjList` to represent the graph.\n\n2. Build the Graph:\n\n    - Loop through each edge in the input `edges` list.\n    - For each edge `[u, v]`, add `v` to `adjList[u]` and `u` to `adjList[v]` to make the graph undirected.\n\n3. Start a DFS from node `0` (or any node, as the graph is connected).\n\n    - In the DFS function:\n        - Mark the current node as visited.\n        - For each adjacent node, check if it's visited:\n            - If not visited, recursively call DFS on the adjacent node, and update its parent.\n            - If the node is visited and its parent is different from the previous one, mark it as `cycleStart` to identify the cycle.\n\n4. Track Cycle Nodes:\n\n    - Using the `parent` array, backtrack from `cycleStart` to collect all nodes in the cycle.\n    - Store these nodes in the `cycleNodes` map for quick lookup.\n\n5. Identify the Redundant Edge:\n\n    - Iterate through the edges in reverse order.\n    - For each edge, check if both nodes of the edge are in the `cycleNodes` map:\n        - If both nodes are in the cycle, return this edge as the redundant connection.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/5URgLFer/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"5URgLFer\"></iframe>\n\n#### Complexity Analysis\n\nHere, $N$ is the number of nodes and edges in the given graph.\n\n- Time complexity: $O(N)$.\n\n    We perform the DFS starting from node `0` only once, which has a time complexity of $O(N)$. Then, we iterate over the cycle nodes using the `parent` array, with a maximum of $N$ iterations if all nodes are part of the cycle. Finally, we iterate over all edges and check the map in $O(1)$ time for each edge. Therefore, the total time complexity is $O(N)$.\n\n- Space complexity: $O(N)$\n\n    The adjacency list `adjList` will store $N$ edges, and the size of the visited array is $N$. Additionally, space is required for the active stack calls during DFS, which can be as large as one per node. The map `cycleNodes` can contain at most $N$ entries. Therefore, the total space complexity is $O(N)$.\n\n---\n\n### Approach 3: Disjoint Set Union (DSU)\n\n#### Intuition\n\nWe’re still working with the same core idea as in the first approach: an edge can be discarded if the nodes it connects are already part of the same component. In the previous approach, we used DFS to check if a path existed between the nodes. However, there's an alternative and more efficient way to do this using a data structure called Disjoint Set Union (DSU).\n\n> If you are not familiar with DSU, please go through our [Explore Card](https://leetcode.com/explore/learn/card/graph/618/disjoint-set/). We will not talk about implementation details here and assume you are already familiar with the interface of DSU.\n\nThe idea behind DSU is that each node is in its own a separate set. As we go through the edges, we perform a union operation that merges the sets of the two connected nodes. This helps us track which nodes are in the same component. If, during this process, we encounter an edge where the two nodes are already in the same component (i.e., they share the same representative), we know that adding this edge would create a cycle, so it’s redundant and can be safely discarded.\n\nThe great thing about DSU is that it can check whether two nodes are in the same component in nearly constant time, specifically in $O(α(N))$, where $α(N)$ is the inverse Ackermann function (which grows extremely slowly). This makes DSU much faster than DFS for this type of problems.\n\nIn this approach, we treat each node as its own component at the start. As we process each edge, we perform the union operation to merge the components of the two nodes connected by the edge. If the nodes are in different components, we unite them and update their representatives. If the nodes are already in the same component, we’ve found a redundant edge and return it as the result.\n\n#### Algorithm\n\n1. Define DSU (Disjoint Set Union):\n\n    - Initialize two arrays:\n        - `size[]` to store the size of each component (starts with 1 for each node).\n        - `representative[]` to track the representative (or root) of each component (initially, each node is its own representative).\n        - Find Operation (`find`):\n            - For each node, find its ultimate representative (root of the component).\n            - Path Compression: During the recursive search, update the representative of each visited node to directly point to the root, speeding up future lookups.\n        - Union Operation (`doUnion`):\n            - Check if the two nodes belong to the same component:\n            - If they already share the same representative, they are part of the same component, so adding this edge would form a cycle. Return `false`.\n            - If the nodes belong to different components, union them:\n            - Attach the smaller component to the larger one (union by size), ensuring the tree remains balanced to minimize depth.\n\n2. Iterate Through Edges:\n\n    - Process each edge in the list of edges:\n        - Convert the 1-based indices from the input to 0-based for array indexing.\n        - Use `doUnion` to attempt connecting the nodes of the edge.\n        - If `doUnion` returns `false`, it means adding this edge would form a cycle, so return the current edge as the redundant edge.\n\n3. If the input is valid, this part of the code should be unreachable. Return an empty list `{}` in such cases.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/JWuYpx4d/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"JWuYpx4d\"></iframe>\n\n#### Complexity Analysis\n\nHere, $N$ is the number of nodes and edges in the given graph.\n\n- Time complexity: $O(N \\cdot \\alpha(N))$\n\n    We iterate over all edges, and for each edge, we invoke the `doUnion` function, which has a time complexity of $O(\\alpha(N))$, given that both union by size and path compression are employed. Consequently, the overall time complexity of the algorithm is $O(N \\cdot \\alpha(N))$. It is important to note that $\\alpha(N)$ represents the inverse Ackermann function, which grows so slowly that it is often considered asymptotically constant, or $O(1)$.\n\n- Space complexity: $O(N)$\n\n    The list `representative`, used to store the representatives, and the list `size`, used to store the size of each component, will each contain $N$ entries. Therefore, the total space complexity is $O(N)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass UnionFind:\n  def __init__(self, n: int):\n    self.id = [i for i in range(n + 1)]\n\n  def union(self, u: int, v: int) -> bool:\n    i = self.find(u)\n    j = self.find(v)\n    if i == j:\n      return False\n    self.id[i] = j\n    return True\n\n  def find(self, u: int) -> int:\n    if self.id[u] != u:\n      self.id[u] = self.find(self.id[u])\n    return self.id[u]\n\n\nclass Solution:\n  def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n    uf = UnionFind(len(edges))\n\n    for edge in edges:\n      if not uf.union(edge[0], edge[1]):\n        return edge",
    "solution_code_java": "\t\t\t\n\nclass UnionFind {\n  public UnionFind(int n) {\n    id = new int[n];\n    for (int i = 0; i < n; ++i)\n      id[i] = i;\n  }\n\n  public boolean union(int u, int v) {\n    final int i = find(u);\n    final int j = find(v);\n    if (i == j)\n      return false;\n    id[i] = j;\n    return true;\n  }\n\n  private int[] id;\n\n  private int find(int u) {\n    return id[u] == u ? u : (id[u] = find(id[u]));\n  }\n}\n\nclass Solution {\n  public int[] findRedundantConnection(int[][] edges) {\n    UnionFind uf = new UnionFind(edges.length + 1);\n\n    for (int[] e : edges)\n      if (!uf.union(e[0], e[1]))\n        return edge;\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass UnionFind {\n public:\n  UnionFind(int n) : id(n) {\n    iota(begin(id), end(id), 0);\n  }\n\n  bool union_(int u, int v) {\n    const int i = find(u);\n    const int j = find(v);\n    if (i == j)\n      return false;\n    id[i] = j;\n    return true;\n  }\n\n private:\n  vector<int> id;\n\n  int find(int u) {\n    return id[u] == u ? u : id[u] = find(id[u]);\n  }\n};\n\nclass Solution {\n public:\n  vector<int> findRedundantConnection(vector<vector<int>>& edges) {\n    UnionFind uf(edges.size() + 1);\n\n    for (const vector<int>& e : edges)\n      if (!uf.union_(e[0], e[1]))\n        return e;\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/684.html",
    "category": "Algorithms",
    "acceptance_rate": 66.3145377650601,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Graph"
    ],
    "hints": [],
    "likes": 6867,
    "dislikes": 436,
    "similar_questions": "[{\"title\": \"Redundant Connection II\", \"titleSlug\": \"redundant-connection-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Accounts Merge\", \"titleSlug\": \"accounts-merge\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Employees to Be Invited to a Meeting\", \"titleSlug\": \"maximum-employees-to-be-invited-to-a-meeting\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Shortest Cycle in a Graph\", \"titleSlug\": \"shortest-cycle-in-a-graph\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"542.1K\", \"totalSubmission\": \"817.4K\", \"totalAcceptedRaw\": 542057, \"totalSubmissionRaw\": 817404, \"acRate\": \"66.3%\"}",
    "title_pt": "Conexão Redundante",
    "description_pt": "<p>Neste problema, uma árvore é um <strong>grafo não direcionado</strong> que é conexo e não possui ciclos.</p>\n\n<p>Você recebe um grafo que começou como uma árvore com <code>n</code> nós rotulados de <code>1</code> a <code>n</code>, com uma aresta adicional adicionada. A aresta adicionada tem dois vértices <strong>diferentes</strong> escolhidos de <code>1</code> a <code>n</code>, e não era uma aresta que já existia. O grafo é representado como um array <code>edges</code> de comprimento <code>n</code>, em que <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indica que existe uma aresta entre os nós <code>a<sub>i</sub></code> e <code>b<sub>i</sub></code> no grafo.</p>\n\n<p>Retorne <em>uma aresta que pode ser removida para que o grafo resultante seja uma árvore de </em><code>n</code><em> nós</em>. Se houver múltiplas respostas, retorne a resposta que ocorre por último na entrada.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/reduntant1-1-graph.jpg\" style=\"width: 222px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> edges = [[1,2],[1,3],[2,3]]\n<strong>Saída:</strong> [2,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/02/reduntant1-2-graph.jpg\" style=\"width: 382px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\n<strong>Saída:</strong> [1,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == edges.length</code></li>\n\t<li><code>3 &lt;= n &lt;= 1000</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>1 &lt;= a<sub>i</sub> &lt; b<sub>i</sub> &lt;= edges.length</code></li>\n\t<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>\n\t<li>Não há arestas repetidas.</li>\n\t<li>O grafo fornecido é conectado.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "685",
    "paidOnly": false,
    "title": "Redundant Connection II",
    "titleSlug": "redundant-connection-ii",
    "url": "https://leetcode.com/problems/redundant-connection-ii",
    "description_url": "https://leetcode.com/problems/redundant-connection-ii/description/",
    "description": "<p>In this problem, a rooted tree is a <b>directed</b> graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.</p>\n\n<p>The given input is a directed graph that started as a rooted tree with <code>n</code> nodes (with distinct values from <code>1</code> to <code>n</code>), with one additional directed edge added. The added edge has two different vertices chosen from <code>1</code> to <code>n</code>, and was not an edge that already existed.</p>\n\n<p>The resulting graph is given as a 2D-array of <code>edges</code>. Each element of <code>edges</code> is a pair <code>[u<sub>i</sub>, v<sub>i</sub>]</code> that represents a <b>directed</b> edge connecting nodes <code>u<sub>i</sub></code> and <code>v<sub>i</sub></code>, where <code>u<sub>i</sub></code> is a parent of child <code>v<sub>i</sub></code>.</p>\n\n<p>Return <em>an edge that can be removed so that the resulting graph is a rooted tree of</em> <code>n</code> <em>nodes</em>. If there are multiple answers, return the answer that occurs last in the given 2D-array.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg\" style=\"width: 222px; height: 222px;\" />\n<pre>\n<strong>Input:</strong> edges = [[1,2],[1,3],[2,3]]\n<strong>Output:</strong> [2,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg\" style=\"width: 222px; height: 382px;\" />\n<pre>\n<strong>Input:</strong> edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n<strong>Output:</strong> [4,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == edges.length</code></li>\n\t<li><code>3 &lt;= n &lt;= 1000</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li>\n\t<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/redundant-connection-ii/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Depth-First Search [Accepted]\n\n**Intuition**\n\nStarting from a rooted tree with `N-1` edges and `N` vertices, let's enumerate the possibilities for the added \"redundant\" edge. If there is no loop, then either one vertex must have two parents (or no edge is redundant). If there is a loop, then either one vertex has two parents, or every vertex has one parent.\n\nIn the first two cases, there are only two candidates for deleting an edge, and we can try removing the last one and seeing if that works. In the last case, the last edge of the cycle can be removed: for example, when `1->2->3->4->1->5`, we want the last edge (by order of occurrence) in the cycle `1->2->3->4->1` (but not necessarily `1->5`).\n\n**Algorithm**\n\nWe'll first construct the underlying graph, keeping track of edges coming from nodes with multiple parents. After, we either have 2 or 0 `candidates`.\n\nIf there are no candidates, then every vertex has one parent, such as in the case `1->2->3->4->1->5`. From any node, we walk towards its parent until we revisit a node - then we must be inside the cycle, and any future seen nodes are part of that cycle.  Now we take the last edge that occurs in the cycle.\n\nOtherwise, we'll see if the graph induced by `parent` is a rooted tree. We again take the `root` by walking from any node towards the parent until we can't, then we perform a depth-first search on this `root`. If we visit every node, then removing the last of the two edge candidates is acceptable, and we should.  Otherwise, we should remove the first of the two edge candidates.\n\nIn our solution, we use `orbit` to find the result upon walking from a node `x` towards its parent repeatedly until you revisit a node or can't walk anymore.  `orbit(x).node` (or `orbit(x)[0]` in Python) will be the resulting node, while `orbit(x).seen` (or `orbit(x)[1]`) will be all the nodes visited.\n\n<iframe src=\"https://leetcode.com/playground/GbE4kZpx/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"GbE4kZpx\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$ where $$N$$ is the number of vertices (and also the number of edges) in the graph. We perform a depth-first search.\n\n* Space Complexity: $$O(N)$$, the size of the graph.",
    "solution_code_python": "\t\t\t\n\nclass UnionFind:\n  def __init__(self, n: int):\n    self.id = [i for i in range(n + 1)]\n\n  def union(self, u: int, v: int) -> bool:\n    i = self.find(u)\n    j = self.find(v)\n    if i == j:\n      return False\n    self.id[i] = j\n    return True\n\n  def find(self, u: int) -> int:\n    if self.id[u] != u:\n      self.id[u] = self.find(self.id[u])\n    return self.id[u]\n\n\nclass Solution:\n  def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n    ids = [0] * (len(edges) + 1)\n    nodeWithTwoParents = 0\n\n    for u, v in edges:\n      ids[v] += 1\n      if ids[v] == 2:\n        nodeWithTwoParents = v\n\n    def findRedundantDirectedConnection(skippedEdgeIndex: int) -> List[int]:\n      uf = UnionFind(len(edges) + 1)\n\n      for i, edge in enumerate(edges):\n        if i == skippedEdgeIndex:\n          continue\n        if not uf.union(edge[0], edge[1]):\n          return edge\n\n      return []\n\n    # If there is no edge with two ids\n    # We don't have to skip any edge\n    if nodeWithTwoParents == 0:\n      return findRedundantDirectedConnection(-1)\n\n    for i in reversed(range(len(edges))):\n      _, v = edges[i]\n      if v == nodeWithTwoParents:\n        # Try to delete edges[i]\n        if not findRedundantDirectedConnection(i):\n          return edges[i]",
    "solution_code_java": "\t\t\t\n\nclass UnionFind {\n  public UnionFind(int n) {\n    id = new int[n];\n    for (int i = 0; i < n; ++i)\n      id[i] = i;\n  }\n\n  public boolean union(int u, int v) {\n    final int i = find(u);\n    final int j = find(v);\n    if (i == j)\n      return false;\n    id[i] = j;\n    return true;\n  }\n\n  private int[] id;\n\n  private int find(int u) {\n    return id[u] == u ? u : (id[u] = find(id[u]));\n  }\n}\n\nclass Solution {\n  public int[] findRedundantDirectedConnection(int[][] edges) {\n    int[] ids = new int[edges.length + 1];\n    int nodeWithTwoParents = 0;\n\n    for (int[] e : edges) {\n      final int v = e[1];\n      if (++ids[v] == 2) {\n        nodeWithTwoParents = v;\n        break;\n      }\n    }\n\n    // If there is no edge with two ids\n    // We don't have to skip any edge\n    if (nodeWithTwoParents == 0)\n      return findRedundantDirectedConnection(edges, -1);\n\n    for (int i = edges.length - 1; i >= 0; --i)\n      if (edges[i][1] == nodeWithTwoParents)\n        // Try to delete edges[i]\n        if (findRedundantDirectedConnection(edges, i).length == 0)\n          return edges[i];\n\n    throw new IllegalArgumentException();\n  }\n\n  private int[] findRedundantDirectedConnection(int[][] edges, int skippedEdgeIndex) {\n    UnionFind uf = new UnionFind(edges.length + 1);\n\n    for (int i = 0; i < edges.length; ++i) {\n      if (i == skippedEdgeIndex)\n        continue;\n      if (!uf.union(edges[i][0], edges[i][1]))\n        return edges[i];\n    }\n\n    return new int[] {};\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass UnionFind {\n public:\n  UnionFind(int n) : id(n) {\n    iota(begin(id), end(id), 0);\n  }\n\n  bool union_(int u, int v) {\n    const int i = find(u);\n    const int j = find(v);\n    if (i == j)\n      return false;\n    id[i] = j;\n    return true;\n  }\n\n private:\n  vector<int> id;\n\n  int find(int u) {\n    return id[u] == u ? u : id[u] = find(id[u]);\n  }\n};\n\nclass Solution {\n public:\n  vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {\n    vector<int> ids(edges.size() + 1);\n    int nodeWithTwoParents = 0;\n\n    for (const vector<int>& e : edges) {\n      const int v = e[1];\n      if (++ids[v] == 2) {\n        nodeWithTwoParents = v;\n        break;\n      }\n    }\n\n    // If there is no edge with two ids\n    // We don't have to skip any edge\n    if (nodeWithTwoParents == 0)\n      return findRedundantDirectedConnection(edges, -1);\n\n    for (int i = edges.size() - 1; i >= 0; --i)\n      if (edges[i][1] == nodeWithTwoParents)\n        // Try to delete edges[i]\n        if (findRedundantDirectedConnection(edges, i).empty())\n          return edges[i];\n\n    throw;\n  }\n\n  vector<int> findRedundantDirectedConnection(const vector<vector<int>>& edges,\n                                              int skippedEdgeIndex) {\n    UnionFind uf(edges.size() + 1);\n\n    for (int i = 0; i < edges.size(); ++i) {\n      if (i == skippedEdgeIndex)\n        continue;\n      if (!uf.union_(edges[i][0], edges[i][1]))\n        return edges[i];\n    }\n\n    return {};\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/685.html",
    "category": "Algorithms",
    "acceptance_rate": 34.99604843181689,
    "topics": [
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Graph"
    ],
    "hints": [],
    "likes": 2423,
    "dislikes": 325,
    "similar_questions": "[{\"title\": \"Redundant Connection\", \"titleSlug\": \"redundant-connection\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"80.1K\", \"totalSubmission\": \"229K\", \"totalAcceptedRaw\": 80149, \"totalSubmissionRaw\": 229022, \"acRate\": \"35.0%\"}",
    "title_pt": "Conexão Redundante II",
    "description_pt": "<p>Neste problema, uma árvore enraizada é um grafo <b>direcionado</b> tal que existe exatamente um nó (a raiz) para o qual todos os outros nós são descendentes desse nó, além de cada nó ter exatamente um pai, exceto o nó raiz, que não tem pais.</p>\n\n<p>A entrada fornecida é um grafo direcionado que começou como uma árvore enraizada com <code>n</code> nós (com valores distintos de <code>1</code> a <code>n</code>), com uma aresta direcionada adicional adicionada. A aresta adicionada tem dois vértices diferentes escolhidos de <code>1</code> a <code>n</code>, e não era uma aresta que já existia.</p>\n\n<p>O grafo resultante é dado como um array 2D de <code>edges</code>. Cada elemento de <code>edges</code> é um par <code>[u<sub>i</sub>, v<sub>i</sub>]</code> que representa uma aresta <b>direcionada</b> conectando os nós <code>u<sub>i</sub></code> e <code>v<sub>i</sub></code>, onde <code>u<sub>i</sub></code> é um pai do filho <code>v<sub>i</sub></code>.</p>\n\n<p>Retorne <em>uma aresta que pode ser removida de modo que o grafo resultante seja uma árvore enraizada de</em> <code>n</code> <em>nós</em>. Se houver múltiplas respostas, retorne a resposta que ocorre por último no array 2D fornecido.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/graph1.jpg\" style=\"width: 222px; height: 222px;\" />\n<pre>\n<strong>Entrada:</strong> edges = [[1,2],[1,3],[2,3]]\n<strong>Saída:</strong> [2,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/12/20/graph2.jpg\" style=\"width: 222px; height: 382px;\" />\n<pre>\n<strong>Entrada:</strong> edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n<strong>Saída:</strong> [4,1]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == edges.length</code></li>\n\t<li><code>3 &lt;= n &lt;= 1000</code></li>\n\t<li><code>edges[i].length == 2</code></li>\n\t<li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub> &lt;= n</code></li>\n\t<li><code>u<sub>i</sub> != v<sub>i</sub></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "686",
    "paidOnly": false,
    "title": "Repeated String Match",
    "titleSlug": "repeated-string-match",
    "url": "https://leetcode.com/problems/repeated-string-match",
    "description_url": "https://leetcode.com/problems/repeated-string-match/description/",
    "description": "<p>Given two strings <code>a</code> and <code>b</code>, return <em>the minimum number of times you should repeat string </em><code>a</code><em> so that string</em> <code>b</code> <em>is a substring of it</em>. If it is impossible for <code>b</code>​​​​​​ to be a substring of <code>a</code> after repeating it, return <code>-1</code>.</p>\n\n<p><strong>Notice:</strong> string <code>&quot;abc&quot;</code> repeated 0 times is <code>&quot;&quot;</code>, repeated 1 time is <code>&quot;abc&quot;</code> and repeated 2 times is <code>&quot;abcabc&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = &quot;abcd&quot;, b = &quot;cdabcdab&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> We return 3 because by repeating a three times &quot;ab<strong>cdabcdab</strong>cd&quot;, b is a substring of it.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> a = &quot;a&quot;, b = &quot;aa&quot;\n<strong>Output:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>a</code> and <code>b</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/repeated-string-match/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Ad-Hoc [Accepted]\n\n**Intuition**\n\nThe question can be summarized as \"What is the smallest `k` for which `B` is a substring of `A * k`?\"  We can just try every `k`.\n\n**Algorithm**\n\nImagine we wrote `S = A+A+A+...`. If `B` is to be a substring of `S`, we only need to check whether some `S[0:], S[1:], ..., S[len(A) - 1:]` starts with `B`, as `S` is long enough to contain `B`, and `S` has a period at most `len(A)`.\n\nNow, suppose `q` is the least number for which `len(B) <= len(A * q)`. We only need to check whether `B` is a substring of `A * q` or `A * (q+1)`. If we try `k < q`, then `B` has a larger length than `A * q` and therefore can't be a substring. When `k = q+1`, `A * k` is already big enough to try all positions for `B`; namely, `A[i:i+len(B)] == B` for `i = 0, 1, ..., len(A) - 1`.\n\n<iframe src=\"https://leetcode.com/playground/gTtmgvev/shared\" frameBorder=\"0\" name=\"gTtmgvev\" width=\"100%\" height=\"224\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N*(N+M))$$, where $$M, N$$ are the lengths of strings `A, B`. We create two strings `A * q`, `A * (q+1)` which have a length at most `O(M+N)`. When checking whether `B` is a substring of `A`, this check takes naively the product of their lengths.\n\n* Space complexity: As justified above, we created strings that used $$O(M+N)$$ space.\n\n---\n\n### Approach #2: Rabin-Karp (Rolling Hash) [Accepted]\n\n**Intuition**\n\nAs in *Approach #1*, we've reduced the problem to deciding whether B is a substring of some `A * k`. Using the following technique, we can decide whether `B` is a substring in $$O(len(A) * k)$$ time.\n\n**Algorithm**\n\nFor strings $$S$$, consider each $$S[i]$$ as some integer ASCII code. Then for some prime $$p$$, consider the following function modulo some prime modulus $$\\mathcal{M}$$:\n\n$$\\text{hash}(S) = \\sum_{0 \\leq i < len(S)} p^i * S[i]$$\n\nNotably, $$\\text{hash}(S[1:] + x) = \\frac{(\\text{hash}(S) - S[0])}{p} + p^{n-1} x$$. This shows we can get the hash of every substring of `A * q` in time complexity linear to its size (We will also use the fact that $$p^{-1} = p^{\\mathcal{M}-2} \\mod \\mathcal{M}$$).\n\nHowever, hashes may collide haphazardly. To be absolutely sure in theory, we should check the answer in the usual way. The expected number of checks we make is in the order of $$1 + \\frac{s}{\\mathcal{M}}$$ where $$s$$ is the number of substrings we computed hashes for (assuming the hashes are equally distributed), which is effectively 1.\n\n<iframe src=\"https://leetcode.com/playground/DKSFgXSr/shared\" frameBorder=\"0\" name=\"DKSFgXSr\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(M+N)$$ (at these sizes), where $$M, N$$ are the lengths of strings `A, B`. As in *Approach #1*, we justify that `A * (q+1)` will be of length $$O(M + N)$$, and computing the rolling hashes was linear work. We will also do a linear $$O(N)$$ final check of our answer $$1 + O(M) / \\mathcal{M}$$ times. In total, this is $$O(M+N + N(1 + \\frac{M}{\\mathcal{M}}))$$ work. Since $$M \\leq 10000 < \\mathcal{M} = 10^9 + 7$$, we can consider this to be linear behavior.\n\n* Space complexity: $$O(1)$$. Only integers were stored with additional memory.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def repeatedStringMatch(self, a: str, b: str) -> int:\n    n = ceil(len(b) / len(a))\n    s = a * n\n    if b in s:\n      return n\n    if b in s + a:\n      return n + 1\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int repeatedStringMatch(String A, String B) {\n    final int n = (int) Math.ceil((double) B.length() / (double) A.length());\n    final String s = String.join(\"\", Collections.nCopies(n, A));\n    if (s.contains(B))\n      return n;\n    if ((s + A).contains(B))\n      return n + 1;\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int repeatedStringMatch(string a, string b) {\n    const int n = ceil((double)b.length() / a.length());\n    string s;\n\n    for (int i = 0; i < n; ++i)\n      s += a;\n\n    if (s.find(b) != string::npos)\n      return n;\n    if ((s + a).find(b) != string::npos)\n      return n + 1;\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/686.html",
    "category": "Algorithms",
    "acceptance_rate": 36.56887220576594,
    "topics": [
      "String",
      "String Matching"
    ],
    "hints": [],
    "likes": 2695,
    "dislikes": 998,
    "similar_questions": "[{\"title\": \"Repeated Substring Pattern\", \"titleSlug\": \"repeated-substring-pattern\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"204.2K\", \"totalSubmission\": \"558.4K\", \"totalAcceptedRaw\": 204193, \"totalSubmissionRaw\": 558381, \"acRate\": \"36.6%\"}",
    "title_pt": "Repetição de String até Correspondência",
    "description_pt": "<p>Dadas duas strings <code>a</code> e <code>b</code>, retorne <em>o número mínimo de vezes que você deve repetir a string </em><code>a</code><em> para que a string</em> <code>b</code> <em>seja uma substring dela</em>. Se for impossível para <code>b</code>​​​​​​ ser uma substring de <code>a</code> após repeti-la, retorne <code>-1</code>.</p>\n\n<p><strong>Observe:</strong> a string <code>&quot;abc&quot;</code> repetida 0 vezes é <code>&quot;&quot;</code>, repetida 1 vez é <code>&quot;abc&quot;</code> e repetida 2 vezes é <code>&quot;abcabc&quot;</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = &quot;abcd&quot;, b = &quot;cdabcdab&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> Retornamos 3 porque, ao repetir a três vezes, &quot;ab<strong>cdabcdab</strong>cd&quot;, b é uma substring dela.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> a = &quot;a&quot;, b = &quot;aa&quot;\n<strong>Saída:</strong> 2\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= a.length, b.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>a</code> e <code>b</code> consistem de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "687",
    "paidOnly": false,
    "title": "Longest Univalue Path",
    "titleSlug": "longest-univalue-path",
    "url": "https://leetcode.com/problems/longest-univalue-path",
    "description_url": "https://leetcode.com/problems/longest-univalue-path/description/",
    "description": "<p>Given the <code>root</code> of a binary tree, return <em>the length of the longest path, where each node in the path has the same value</em>. This path may or may not pass through the root.</p>\n\n<p><strong>The length of the path</strong> between two nodes is represented by the number of edges between them.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg\" style=\"width: 450px; height: 238px;\" />\n<pre>\n<strong>Input:</strong> root = [5,4,5,1,1,null,5]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The shown image shows that the longest path of the same value (i.e. 5).\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg\" style=\"width: 450px; height: 238px;\" />\n<pre>\n<strong>Input:</strong> root = [1,4,5,4,4,null,5]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> The shown image shows that the longest path of the same value (i.e. 4).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li>The depth of the tree will not exceed <code>1000</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-univalue-path/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Depth-First Search\n\n**Intuition**\n\nWe can try to solve the problem in a recursive manner, as for trees the recursive solutions are intuitive and easy to follow. Let's suppose we have a node in the binary tree, and for both the left and right child, we have the count of nodes in the path that is equal to the node's value. How can we determine the longest univalue path for this node? If the node count for the left and right child is `x` and `y` respectively, then the answer for the parent node should be `x + y`. This is because the longest path would be considering the nodes on both children starting from one child to the parent node and then to the other child.\n\nIn the image below, the univalue path for the root node will be 3, as the number of nodes on the left child path that have the same value as the root node is 1 and the number of nodes on the right child path having the same value as the root node is 2. Hence, the path will include the nodes on both left and right and thus will have a length of 3.\n\n![fig](../Figures/687/687B.png)\n\nNow, we know that, for each left and right child path, we can find the number of nodes equal to their parent node. Then we can find the longest univalue path for the parent node. How to find the count of these nodes? As we just discussed above, if the number of nodes on the left and right child path have the same value as the node `x` and `y`, then the number of nodes that are equal to the parent node should be `max(x, y) + 1`. This is because we will consider only the longest child path, and there's an extra `1` representing the current node.\n\nTherefore, in the recursive function, the base condition would be that if the node is null then we can return `0`. Otherwise, we will recursively call for the left and right child and store the count of nodes in the variables `left` and `right`. Update the answer variable if it's less than the univalue path at the current node which is `x + y`. Return the `max(x, y) + 1` which is the maximum number of nodes that have the same value as `root` on either the left or right side.\n\n![fig](../Figures/687/687A.png)\n\n**Algorithm**\n\n1. Define the recursive function `solve()`, which accepts two arguments first the current node` root` and the second is the value of its parent node `parent`. This method returns the maximum number of consecutive nodes that are present on either the left or right side of the `root` with the same value, including the `root`.\n\n    1. If the root is `NULL`, then return `0`.\n    2. Recursively call `solve()` for the left and right child with the parent value as the value of `root`.\n    3. Update the answer variable `ans` if `left + right` is greater than `ans`.\n    4. If the value of `root` is equal to the parent, return `max(left, right) + 1`, otherwise, return `0`.\n\n2. Call `solve()` with `root` and parent value as `-1`.\n3. Return the maximum univalue path length `ans`.\n\n\n**Implementation**\n\n<iframe src=\"https://leetcode.com/playground/RDxJkYBK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"RDxJkYBK\"></iframe>\n\n**Complexity Analysis**\n\nHere, $N$ is the number of nodes in the binary tree.\n\n* Time complexity: $O(N)$\n\n  We are iterating over each node only once and hence the time complexity is equal to $O(N)$.\n\n* Space complexity: $O(N)$\n\n  The only space we need is during the recursion, the maximum number of active stack calls would be equal to the height of the tree. In the case of a skewed tree, the height of the tree will be equal to $N$, hence the space complexity is equal to $O(N)$.\n  <br/>\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n    ans = 0\n\n    def longestUnivaluePathDownFrom(root: Optional[TreeNode]) -> int:\n      nonlocal ans\n      if not root:\n        return 0\n\n      l = longestUnivaluePathDownFrom(root.left)\n      r = longestUnivaluePathDownFrom(root.right)\n      arrowLeft = l + 1 if root.left and root.left.val == root.val else 0\n      arrowRight = r + 1 if root.right and root.right.val == root.val else 0\n      ans = max(ans, arrowLeft + arrowRight)\n      return max(arrowLeft, arrowRight)\n\n    longestUnivaluePathDownFrom(root)\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int longestUnivaluePath(TreeNode root) {\n    longestUnivaluePathDownFrom(root);\n    return ans;\n  }\n\n  private int ans = 0;\n\n  private int longestUnivaluePathDownFrom(TreeNode root) {\n    if (root == null)\n      return 0;\n\n    final int l = longestUnivaluePathDownFrom(root.left);\n    final int r = longestUnivaluePathDownFrom(root.right);\n    final int arrowLeft = root.left != null && root.left.val == root.val ? l + 1 : 0;\n    final int arrowRight = root.right != null && root.right.val == root.val ? r + 1 : 0;\n    ans = Math.max(ans, arrowLeft + arrowRight);\n    return Math.max(arrowLeft, arrowRight);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int longestUnivaluePath(TreeNode* root) {\n    int ans = 0;\n    longestUnivaluePathDownFrom(root, ans);\n    return ans;\n  }\n\n private:\n  int longestUnivaluePathDownFrom(TreeNode* root, int& ans) {\n    if (root == nullptr)\n      return 0;\n\n    const int l = longestUnivaluePathDownFrom(root->left, ans);\n    const int r = longestUnivaluePathDownFrom(root->right, ans);\n    const int arrowLeft =\n        root->left && root->left->val == root->val ? l + 1 : 0;\n    const int arrowRight =\n        root->right && root->right->val == root->val ? r + 1 : 0;\n    ans = max(ans, arrowLeft + arrowRight);\n    return max(arrowLeft, arrowRight);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/687.html",
    "category": "Algorithms",
    "acceptance_rate": 42.50464766102778,
    "topics": [
      "Tree",
      "Depth-First Search",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 4340,
    "dislikes": 674,
    "similar_questions": "[{\"title\": \"Binary Tree Maximum Path Sum\", \"titleSlug\": \"binary-tree-maximum-path-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Univalue Subtrees\", \"titleSlug\": \"count-univalue-subtrees\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Path Sum III\", \"titleSlug\": \"path-sum-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Path With Different Adjacent Characters\", \"titleSlug\": \"longest-path-with-different-adjacent-characters\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"202.1K\", \"totalSubmission\": \"475.5K\", \"totalAcceptedRaw\": 202113, \"totalSubmissionRaw\": 475508, \"acRate\": \"42.5%\"}",
    "title_pt": "Caminho Mais Longo de Valor Único",
    "description_pt": "<p>Dada a <code>root</code> de uma árvore binária, retorne <em>o comprimento do caminho mais longo, em que cada nó no caminho tem o mesmo valor</em>. Esse caminho pode ou não passar pela raiz.</p>\n\n<p><strong>O comprimento do caminho</strong> entre dois nós é representado pelo número de arestas entre eles.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/ex1.jpg\" style=\"width: 450px; height: 238px;\" />\n<pre>\n<strong>Entrada:</strong> root = [5,4,5,1,1,null,5]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A imagem mostrada mostra que o caminho mais longo do mesmo valor (ou seja, 5).\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/13/ex2.jpg\" style=\"width: 450px; height: 238px;\" />\n<pre>\n<strong>Entrada:</strong> root = [1,4,5,4,4,null,5]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> A imagem mostrada mostra que o caminho mais longo do mesmo valor (ou seja, 4).\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[0, 10<sup>4</sup>]</code>.</li>\n\t<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>\n\t<li>A profundidade da árvore não excederá <code>1000</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "688",
    "paidOnly": false,
    "title": "Knight Probability in Chessboard",
    "titleSlug": "knight-probability-in-chessboard",
    "url": "https://leetcode.com/problems/knight-probability-in-chessboard",
    "description_url": "https://leetcode.com/problems/knight-probability-in-chessboard/description/",
    "description": "<p>On an <code>n x n</code> chessboard, a knight starts at the cell <code>(row, column)</code> and attempts to make exactly <code>k</code> moves. The rows and columns are <strong>0-indexed</strong>, so the top-left cell is <code>(0, 0)</code>, and the bottom-right cell is <code>(n - 1, n - 1)</code>.</p>\n\n<p>A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.</p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/knight.png\" style=\"width: 300px; height: 300px;\" />\n<p>Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.</p>\n\n<p>The knight continues moving until it has made exactly <code>k</code> moves or has moved off the chessboard.</p>\n\n<p>Return <em>the probability that the knight remains on the board after it has stopped moving</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 3, k = 2, row = 0, column = 0\n<strong>Output:</strong> 0.06250\n<strong>Explanation:</strong> There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 1, k = 0, row = 0, column = 0\n<strong>Output:</strong> 1.00000\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 25</code></li>\n\t<li><code>0 &lt;= k &lt;= 100</code></li>\n\t<li><code>0 &lt;= row, column &lt;= n - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/knight-probability-in-chessboard/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\n>**Note.** For this problem, we assume that you already know the fundamentals of dynamic programming and are figuring out how to apply it to a wide range of problems, such as this one. If you are not yet at this stage, we recommend checking out our relevant [Explore Card content on dynamic programming](https://leetcode.com/explore/featured/card/dynamic-programming/) before coming back to this article.\n\n---\n\n### Approach 1: Bottom-up Dynamic Programming\n\n#### Intuition\n\nWe need to find the probability that the knight will remain on the chessboard after $k$ moves, that is it will be in one of the cells $(i, j)$ such that $0 \\le i < n, 0 \\le j < n$.\n\nThe first observation: the probability of the knight being on the board after $k$ moves equals the sum of probabilities of being in the cell $(i, j)$ over all $0 \\le i < n, 0 \\le j < n$.\n\nWe reduce our problem to finding the probability of the knight being in the cell $(i, j)$ after $k$ moves for each $0 \\le i < n, 0 \\le j < n$.\n\nWhere the knight locates at the $k^\\text{th}$ move depends on where it was at the previous $(k - 1)^\\text{th}$ move which in turn depends on where it was at the $(k - 2)^\\text{th}$ move and so on.\n\nThe transition from the current $k^\\text{th}$ move to the previous $(k - 1)^\\text{th}$ one is essentially the reduction to the smaller subproblem. When we have a reduction to the smaller problem, it is worth thinking of dynamic programming.\n\nLet's think about what we need to completely describe the knight's state.\n\nThe knight makes the first move, then the second one, the third one, and so on until the last $k^\\text{th}$ move. The first parameter that describes the state is $\\text{moves}$ – how many moves has the knight already made. One can think of it as of time passed since the beginning of the knight's journey.\n\nAlso, we need the knight's location on the chessboard, which we can describe with two integers $i$ and $j$ – the cell's coordinates.\n\nThree parameters $\\text{moves}$, $i$, and $j$ are enough to fully describe the knight's state.\n\nTo solve the problem using dynamic programming, we define $\\text{dp}[\\text{moves}][i][j]$ as the probability of the knight being at cell $(i, j)$ on the chessboard after $\\text{moves}$ moves.\n\nHere is an example of the DP table for $n = 8, \\text{row} = 4, \\text{column} = 4, 0 \\le \\text{moves} \\le 2$.\n\n![Example of a DP table](../Figures/688/688_dp_example.drawio.png)\n\nThe base case is when $\\text{moves} = 0$, representing the starting position of the knight. In this case, the probability of being at cell $(\\text{row}, \\text{column})$ is 100%. We set $\\text{dp}[0][\\text{row}][\\text{column}] = 1$, and all other cells have a probability of $0$.\n\nNow, let's consider the transitions for the dynamic programming solution. We will compute the DP table in increasing order of $\\text{moves}$ – $\\text{dp}[0]$ is already calculated, after that we find $\\text{dp}[1]$, then $\\text{dp}[2]$ and so on. For each $\\text{moves}$ from $1$ to $k$, we want to calculate the probability for each cell $(i, j)$ based on the previous moves.\n\nTo determine the probability for each cell after $\\text{moves}$ moves, we iterate over all cells $(i, j)$ on the chessboard. For each cell, we consider all possible moves the knight can make to reach that cell.\n\n![Knight's moves](../Figures/688/688_knight_moves.drawio.png)\n\nFor a given cell $(i, j)$, we iterate over the possible directions, calculating the probability of reaching cell $(i, j)$ from neighboring cells $(i', j')$ in the previous move. The variables $i'$ and $j'$ represent the coordinates of the neighboring cells (in the sense of knight's moves).\n\nWe consider all eight possible directions that a knight can move. Each direction corresponds to a movement pattern of two steps in one direction and one step in the perpendicular direction, or vice versa. For example, one possible direction is moving two steps vertically up and one step horizontally to the right. We use a list of $\\text{directions}$ to represent these possible moves: $\\text{directions} = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)]$.\n\nFor each direction, we calculate the probability of reaching cell $(i, j)$ from the neighboring cell $(i', j')$ in the previous move. We sum up the probabilities for all eight neighboring cells and divide the result by $8$ since there are eight possible moves for the knight.\n\nBy considering all possible directions and summing up the probabilities from the neighboring cells, we obtain the probability of being at cell $(i, j)$ after $\\text{moves}$ moves:\n\n$\\Large{\\text{dp}[\\text{moves}][i][j] = \\frac{1}{8} \\sum_{(i', j')} \\text{dp}[\\text{moves} - 1][i'][j']}$\n\n![1/8 factor](../Figures/688/688_1_8_factor.drawio.png)\n\nThis probability takes into account all the possible paths and movements of the knight up to that point.\n\nFinally, to calculate the total probability of the knight remaining on the board after $k$ moves, we sum up the probabilities for all cells $(i, j)$ on the chessboard.\n\nLet $\\text{total\\_probability}$ represent the overall probability that the knight remains on the chessboard after $k$ moves. To calculate this probability, we need to consider each cell on the chessboard.\n\nWe iterate over all the cells $(i, j)$ on the chessboard, starting from the top-left cell and moving row by row. For each cell, we sum up $\\text{dp}[k][i][j]$. These $\\text{dp}$ values represent the probabilities of the knight being at that cell after $k$ moves.\n\nBy summing up these probabilities for all cells on the chessboard, we obtain the $\\text{total\\_probability}$. This value reflects the cumulative likelihood that the knight will remain on the chessboard after $k$ moves. The higher the $\\text{total\\_probability}$, the greater the chance that the knight will still be on the board.\n\nOne can write this in mathematical notation: $$\\text{{total\\_probability}} = \\sum_{i=0}^{n-1} \\sum_{j=0}^{n-1} \\text{dp}[k][i][j]$$.\n\nThe $\\text{total\\_probability}$ represents the probability that the knight remains on the board after $k$ moves, and you can return this value as the result.\n\n#### Algorithm\n\n1. Define possible directions for the knight's moves in $\\text{directions}$.\n2. Initialize the dynamic programming table $\\text{dp}$ with zeros.\n3. Set $\\text{dp}[0][\\text{row}][\\text{column}]$ to $1$, representing the starting position of the knight.\n4. Iterate $\\text{moves}$ from $1$ to $k$.\n    - Iterate $i$ from $0$ to $n-1$ (rows on the chessboard).\n        - Iterate $j$ from $0$ to $n-1$ (columns on the chessboard).\n            - Iterate over possible directions:\n                - Calculate $i'$ as $i$ minus the vertical component of the direction.\n                - Calculate $j'$ as $j$ minus the horizontal component of the direction.\n                - Check if $i'$ and $j'$ are within the range $[0, n-1]$.\n                    - If within range, add $\\frac{1}{8} \\text{dp}[\\text{moves} - 1][i'][j']$ to $\\text{dp}[\\text{moves}][i][j]$.\n5. Calculate the total probability by summing all values in $\\text{dp}[k]$.\n6. Return the total probability.\n\n#### Implementation\n\nIn code, the variables $i'$ and $j'$ are denoted as $\\text{prev\\_i}$ and $\\text{prev\\_j}$, respectively.\n\n<iframe src=\"https://leetcode.com/playground/4gnHU7CH/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"4gnHU7CH\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time complexity: $O(k \\cdot n^2)$.\n\nWe have four nested for-loops: `for moves`, `for i`, `for j`, and `for direction`. The outer loop `for moves` runs $k$ times, the second and third loops `for i` and `for j` iterate over all cells on the $n \\times n$ chessboard, and the innermost loop `for direction` iterates over the possible directions. As there are a constant number of directions ($8$), this loop can be considered as $O(1)$ iterations.\n\nWithin each state $(\\text{moves}, i, j)$, the time complexity is constant, as we perform simple calculations and update the dynamic programming table.\n\nThe total number of iterations is determined by the product of the number of iterations in each loop: $O(k \\cdot n^2)$.\n\n* Space complexity: $O(k \\cdot n^2)$.\n\nWe use a three-dimensional dynamic programming table $\\text{dp}$ of size $(k+1) \\times n \\times n$ to store the probabilities of being at each cell after a certain number of moves. Therefore, the space complexity is $O(k \\cdot n^2)$.\n\n---\n\n### Approach 2: Bottom-up Dynamic Programming with Optimized Space Complexity\n\nIn the original approach, we used a 3D dynamic programming table $\\text{dp}$ to store the probabilities of being at each cell after a certain number of moves. However, this approach requires $O(k \\cdot n^2)$ space complexity.\n\nTo reduce the space complexity, we can observe that we only need the probabilities from the previous move $\\text{moves} - 1$ to calculate the probabilities for the current move $\\text{moves}$. Therefore, we can maintain two 2D arrays $\\text{prev\\_dp}$ and $\\text{curr\\_dp}$, each of size $n \\times n$, to store the probabilities for the previous move and the current move, respectively.\n\nDuring the iteration, we update the values in $\\text{curr\\_dp}$ based on the values in $\\text{prev\\_dp}$. After each iteration, we swap the arrays $\\text{prev\\_dp}$ and $\\text{curr\\_dp}$ to reuse the space for the next iteration.\n\nThis way, we only need $O(n^2)$ space to store the probabilities for the current and previous moves, resulting in an optimized space complexity of $O(n^2)$.\n\nBy using this optimized memory approach, we can solve the problem efficiently while reducing the space required for storage.\n\n#### Algorithm\n\n1. Define possible directions for the knight's moves in $\\text{directions}$.\n2. Initialize the dynamic programming tables $\\text{prev\\_dp}$ and $\\text{curr\\_dp}$ with zeros.\n3. Set $\\text{prev\\_dp}[\\text{row}][\\text{column}]$ to $1$, representing the starting position of the knight.\n4. Iterate $\\text{moves}$ from $1$ to $k$.\n    - Iterate $i$ from $0$ to $n-1$ (rows on the chessboard).\n        - Iterate $j$ from $0$ to $n-1$ (columns on the chessboard).\n\t    - Reset the probability for the current square before calculating it $\\text{curr\\_dp}[i][j] = 0$.\n            - Iterate over possible directions:\n                - Calculate $i'$ as $i$ minus the vertical component of the direction.\n                - Calculate $j'$ as $j$ minus the horizontal component of the direction.\n                - Check if $i'$ and $j'$ are within the range $[0, n-1]$.\n                    - If within range, add $\\frac{1}{8} \\text{prev\\_dp}[i'][j']$ to $\\text{curr\\_dp}[i][j]$.\n    - Swap $\\text{prev\\_dp}$ and $\\text{curr\\_dp}$.\n5. Calculate the total probability by summing all values in $\\text{prev\\_dp}$.\n6. Return the total probability.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/CK5WYbtD/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"CK5WYbtD\"></iframe>\n\n#### Complexity Analysis\n\n* Time complexity: $O(k \\cdot n^2)$.\n\nIt is the same as in the previous approach.\n\n* Space complexity: $O(n^2)$.\n\nWe use two dynamic programming tables: $\\text{prev\\_dp}$ and $\\text{curr\\_dp}$, each of size $n \\times n$. Therefore, the space complexity is $O(n^2)$. The space complexity does not depend on the number of moves $k$, as we only keep track of the probabilities of being at each cell after the previous and current moves.\n\n---\n\n### Approach 3: Top-down Dynamic Programming (Memoization)\n\n#### Intuition\n\nIn this approach, we will calculate the same DP table using the same recurrence relation as in the first one, but the manner of organizing computations will differ.\n\nWe will use the recursive function $\\text{calculateDP}(\\text{moves}, i, j)$ that returns the value of $\\text{dp}[\\text{moves}][i][j]$.\n\nThe base case of the recursive function is $\\text{moves} = 0$: $\\text{calculateDP}(0, \\text{row}, \\text{column})$ returns $1$, and $\\text{calculateDP}(0, i, j)$ returns $0$ for all cells $(i, j) \\ne (\\text{row}, \\text{column})$.\n\nOne can rewrite the DP recurrence relation as follows in terms of $\\text{calculateDP}$: $\\text{calculateDP}(\\text{moves}, i, j)$ returns the sum of $\\frac{1}{8} \\text{calculateDP}(\\text{moves} - 1, i', j')$ over the neighboring cells $(i', j')$. It is the same relation as in the first approach.\n\nThe answer to the problem is the sum of $\\text{calculateDP}(k, i, j)$ over all cells $(i, j)$.\n\nIn the function $\\text{calculateDP}(\\text{moves}, i, j)$, we check if the value $\\text{dp}[\\text{moves}][i][j]$ has already been calculated and stored in the DP table. If it has, we directly return the stored value. Otherwise, we calculate the probability using the same recurrence relation as in the first approach.\n\nTo use this function, we need to initialize the DP table $\\text{dp}$ with $-1$ values to indicate that the probabilities have not been calculated yet.\n\nAfter calculating the probabilities for each cell, we can calculate the total probability by summing up the probabilities for all cells $(i, j)$ on the chessboard.\n\n#### Algorithm\n\nThe function $\\text{calculateDP}$ takes three parameters: $\\text{moves}$, $i$, and $j$.\n\n1. If $\\text{moves}$ equals $0$, return $1$ if $i$ equals $\\text{row}$ and $j$ equals $\\text{column}$, otherwise return $0$.\n2. If $\\text{dp}[\\text{moves}][i][j]$ is not equal to $-1$, return $\\text{dp}[\\text{moves}][i][j]$.\n3. Initialize $\\text{dp}[\\text{moves}][i][j]$ to $0$.\n4. Iterate over possible directions:\n    - Calculate $i'$ by subtracting the vertical component of the direction from $i$.\n    - Calculate $j'$ by subtracting the horizontal component of the direction from $j$.\n    - Check if $i'$ and $j'$ are within the chessboard boundaries:\n        - If so, add $\\frac{1}{8} \\text{calculateDP}(\\text{moves} - 1, i', j')$ to $\\text{dp}[\\text{moves}][i][j]$.\n5. Return $\\text{dp}[\\text{moves}][i][j]$.\n\nTo solve the problem:\n- Initialize the $\\text{dp}$ table with $-1$ values.\n- Calculate the total probability by summing $\\text{calculateDP}(k, i, j)$ for all $i$, $j$.\n- Return the total probability.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/fdSjWkfm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"fdSjWkfm\"></iframe>\n\n\n#### Complexity Analysis\n\n* Time complexity: $O(k \\cdot n^2)$.\n\nEven though we changed the order in which we calculate DP, the time complexity is the same as in the previous approach: for each state $(\\text{moves}, i, j)$, we calculate $\\text{dp}[\\text{moves}][i][j]$ in $O(1)$. Since we store the results in the memory, we will compute $\\text{dp}[\\text{moves}][i][j]$ only once.\n\n* Space complexity: $O(k \\cdot n^2)$.\n\nWe store the DP table of size $[k + 1][n][n]$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def knightProbability(self, N: int, K: int, r: int, c: int) -> float:\n    dirs = [(1, 2), (2, 1), (2, -1), (1, -2),\n            (-1, -2), (-2, -1), (-2, 1), (-1, 2)]\n\n    # dp[i][j] := probability to stand on (i, j)\n    dp = [[0] * N for _ in range(N)]\n    dp[r][c] = 1\n\n    for _ in range(K):\n      newDp = [[0] * N for _ in range(N)]\n      for i in range(N):\n        for j in range(N):\n          for dx, dy in dirs:\n            x = i + dx\n            y = j + dy\n            if 0 <= x < N and 0 <= y < N:\n              newDp[i][j] += dp[x][y]\n      dp = newDp\n\n    return sum(map(sum, dp)) / 8**K",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public double knightProbability(int N, int K, int r, int c) {\n    final double kProb = 0.125;\n    final int[][] dirs = {{-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};\n\n    // dp[i][j] := probability to stand on (i, j)\n    double[][] dp = new double[N][N];\n    dp[r][c] = 1.0;\n\n    for (int k = 0; k < K; ++k) {\n      double[][] newDp = new double[N][N];\n      for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n          if (dp[i][j] > 0.0) {\n            for (int[] dir : dirs) {\n              final int x = i + dir[0];\n              final int y = j + dir[1];\n              if (x < 0 || x >= N || y < 0 || y >= N)\n                continue;\n              newDp[x][y] += dp[i][j] * kProb;\n            }\n          }\n      dp = newDp;\n    }\n\n    double ans = 0.0;\n\n    for (double[] row : dp)\n      ans += Arrays.stream(row).sum();\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  double knightProbability(int N, int K, int r, int c) {\n    constexpr double kProb = 0.125;\n    const vector<pair<int, int>> dirs{{-2, 1}, {-1, 2}, {1, 2},   {2, 1},\n                                      {2, -1}, {1, -2}, {-1, -2}, {-2, -1}};\n\n    // dp[i][j] := probability to stand on (i, j)\n    vector<vector<double>> dp(N, vector<double>(N));\n    dp[r][c] = 1.0;\n\n    for (int k = 0; k < K; ++k) {\n      vector<vector<double>> newDp(N, vector<double>(N));\n      for (int i = 0; i < N; ++i)\n        for (int j = 0; j < N; ++j)\n          if (dp[i][j] > 0.0) {\n            for (const auto& [dx, dy] : dirs) {\n              const int x = i + dx;\n              const int y = j + dy;\n              if (x < 0 || x >= N || y < 0 || y >= N)\n                continue;\n              newDp[x][y] += dp[i][j] * kProb;\n            }\n          }\n      dp = move(newDp);\n    }\n\n    return accumulate(begin(dp), end(dp), 0.0,\n                      [](double s, vector<double>& row) {\n      return s + accumulate(begin(row), end(row), 0.0);\n    });\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/688.html",
    "category": "Algorithms",
    "acceptance_rate": 56.55697876208578,
    "topics": [
      "Dynamic Programming"
    ],
    "hints": [],
    "likes": 3935,
    "dislikes": 486,
    "similar_questions": "[{\"title\": \"Out of Boundary Paths\", \"titleSlug\": \"out-of-boundary-paths\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Moves to Kill All Pawns\", \"titleSlug\": \"maximum-number-of-moves-to-kill-all-pawns\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"171.1K\", \"totalSubmission\": \"302.5K\", \"totalAcceptedRaw\": 171099, \"totalSubmissionRaw\": 302525, \"acRate\": \"56.6%\"}",
    "title_pt": "Probabilidade do Cavalo no Tabuleiro de Xadrez",
    "description_pt": "<p>Em um tabuleiro de xadrez <code>n x n</code>, um cavalo começa na célula <code>(row, column)</code> e tenta fazer exatamente <code>k</code> movimentos. As linhas e colunas são <strong>indexadas em 0</strong>, então a célula no canto superior esquerdo é <code>(0, 0)</code>, e a célula no canto inferior direito é <code>(n - 1, n - 1)</code>.</p>\n\n<p>Um cavalo de xadrez tem oito movimentos possíveis que pode fazer, como ilustrado abaixo. Cada movimento é duas células em uma direção cardinal, depois uma célula em uma direção ortogonal.</p>\n<img src=\"https://assets.leetcode.com/uploads/2018/10/12/knight.png\" style=\"width: 300px; height: 300px;\" />\n<p>Cada vez que o cavalo deve se mover, ele escolhe um dos oito movimentos possíveis uniformemente ao acaso (mesmo que a peça saia do tabuleiro) e se move para lá.</p>\n\n<p>O cavalo continua se movendo até ter feito exatamente <code>k</code> movimentos ou ter saído do tabuleiro.</p>\n\n<p>Retorne <em>a probabilidade de que o cavalo permaneça no tabuleiro após ter parado de se mover</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 3, k = 2, row = 0, column = 0\n<strong>Saída:</strong> 0.06250\n<strong>Explicação:</strong> Há dois movimentos (para (1,2), (2,1)) que manterão o cavalo no tabuleiro.\nA partir de cada uma dessas posições, também há dois movimentos que manterão o cavalo no tabuleiro.\nA probabilidade total de o cavalo permanecer no tabuleiro é 0.0625.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 1, k = 0, row = 0, column = 0\n<strong>Saída:</strong> 1.00000\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 25</code></li>\n\t<li><code>0 &lt;= k &lt;= 100</code></li>\n\t<li><code>0 &lt;= row, column &lt;= n - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "689",
    "paidOnly": false,
    "title": "Maximum Sum of 3 Non-Overlapping Subarrays",
    "titleSlug": "maximum-sum-of-3-non-overlapping-subarrays",
    "url": "https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays",
    "description_url": "https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, find three non-overlapping subarrays of length <code>k</code> with maximum sum and return them.</p>\n\n<p>Return the result as a list of indices representing the starting position of each interval (<strong>0-indexed</strong>). If there are multiple answers, return the lexicographically smallest one.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,1,2,6,7,5,1], k = 2\n<strong>Output:</strong> [0,3,5]\n<strong>Explanation:</strong> Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically smaller.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,1,2,1,2,1,2,1], k = 2\n<strong>Output:</strong> [0,2,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;&nbsp;2<sup>16</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= floor(nums.length / 3)</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\n### Approach 1: Memoization\n\n#### Intuition\n\nAt first, we might think of a greedy approach: since all array values are positive, we could just find the three largest `k`- length subarrays. Unfortunately, this doesn't always work because the subarrays might overlap and, even if we avoid overlaps, we might miss better combinations. For example, taking a smaller subarray sum early on could allow us to pick two much larger subarrays later. This is why a greedy approach fails - we need to balance between local (current subarray) and global (overall) optimization.\n\nTo find the optimal subarrays, we need to make a decision at each position in the array:  \n- Should we take the `k`-length subarray starting here?  \n- Or should we skip it and move to the next position?  \n\nThis \"take it or leave it\" choice is typical in dynamic programming problems, similar to the 0/1 Knapsack Problem. If you are unfamiliar with the 0/1 Knapsack Problem, take a look at this excellent [LeetCode Discuss post 🔗](https://leetcode.com/discuss/study-guide/1152328/01-Knapsack-Problem-and-Dynamic-Programming#:~:text=Statement%3A%20Given%20a%20set%20of,equal%20to%20the%20knapsack's%20capacity.).\n\nLet us try to implement a memoized recursive function which should pick three subarrays such that their total sum is as large as possible. However, it is too slow to calculate the `k`-length subarray whenever we want to pick a particular index. To optimize this, let's precalculate the sum of the `k`-length subarray starting at each index. We create an array `sums` and populate it by maintaining a window of size `k` that slides through the array, adding the new element and removing the oldest one at each step.\n\nFor our recursive function design, which returns the largest total sum after selecting the subarrays, we need to consider two base cases:\n- If we’ve already selected 3 subarrays, return the current sum immediately.\n- If we've reached the array's end, terminate naturally.\n\nAt each step, we have two choices:  \n1. Take the current subarray: Add its sum to the total and jump `k` positions forward (to avoid overlap).  \n2. Skip the current position: Move to the next position and continue looking for subarrays.  \n\nWe take the larger of these two choices, and this forms our recurrence relation.\n\nTo keep track of these decisions and avoid recalculating results, we use a 2D array (`dp`) of size `n × 3`, where `n` is the length of the array and `3` represents the number of subarrays we need to find. Each cell in `dp` stores the best sum for a specific position and the number of remaining subarrays.\n\nOnce we’ve calculated the largest total sum using this DP table, we need to find the starting indices of the subarrays that produce this sum. This is the second phase of the solution: **path reconstruction**.  \n\nTo do this, we use a Depth-First Search (DFS) to retrace the steps of the DP function. At each step, we decide whether to include the current position or skip it, and we check the `dp` table to guide our choice.  \n- If taking the current position gives the same or a better sum, we add its index to our result.  \n\nSince all DP states are precomputed, each DFS step is fast. After the DFS completes, the `indices` list contains the starting indices of the three non-overlapping subarrays. We return this list as our final answer.\n\n> If you are unfamiliar with dynamic programming, check out the [Dynamic Programming Explore Card 🔗](https://leetcode.com/explore/featured/card/dynamic-programming/). This resource provides an in-depth look at the dynamic programming paradigm, explaining its key concepts and applications with a variety of problems to solidify understanding of the pattern. \n\n#### Algorithm\n\n- Create a variable `n` to store the number of possible starting positions for subarrays, calculated as the array length minus `k` plus 1.\n- Initialize:\n  - an array `sums` of size `n` to store sums of all possible `k`-length subarrays.\n  - a variable `windowSum` to store the sum of the first `k` elements.\n- Store the first window sum in `sums[0]`.\n- Use a sliding window technique to calculate the remaining sums:\n  - Subtract the leftmost element of the previous window.\n  - Add the rightmost element of the current window.\n  - Store the result in the corresponding position of the `sums` array.\n- Initialize a 2D array `memo` of size `n x 4` to store dynamic programming states, where `memo[i][j]` represents the largest sum possible starting from index `i` with `j` subarrays remaining.\n- Initialize an empty list `indices` to store final result indices.\n- Call `dp` to find the optimal sum using dynamic programming.\n- Call `dfs` to reconstruct the path and find the starting indices.\n- Return `indices` as the required answer.\n\nIn the `dp` function:\n- Base case 1: If the remaining subarrays (`rem`) is 0, return 0 as we've found all required subarrays.\n- Base case 2: If the current index (`idx`) exceeds array bounds, return -infinity if we still need subarrays, else return 0.\n- Check if the current state is already computed by examining `memo[idx][rem]`. If the value is not -1, return the memoized result.\n- Calculate the first choice by adding the current subarray sum (`sums[idx]`) to the result of a recursive call with:\n  - Index advanced by `k` positions (`idx + k`).\n  - One less subarray remaining (`rem - 1`).\n- Calculate the second choice by making a recursive call with:\n  - Index advanced by 1 (`idx + 1`).\n  - Same number of subarrays remaining (`rem`).\n- Store the larger of two choices in `memo[idx][rem]`.\n- Return the stored largest value.\n\nIn the `dfs` function:\n- Base case 1: If the remaining subarrays (`rem`) is `0`, return as the solution is complete.\n- Base case 2: If the current index (`idx`) exceeds array bounds, return as the path is invalid.\n- Calculate the largest sum possible by including the current subarray using the same parameters as in the `dp` function.  \n- Calculate the largest sum possible by skipping the current subarray using the same parameters as in the `dp` function.\n- Compare the two possibilities:\n  - If including the current subarray gives a greater or equal sum:\n    - Add the current index to the solution list.\n    - Make a recursive call with an index advanced by `k` and one less subarray remaining.\n  - Otherwise:\n    - Make a recursive call with the next index and the same number of subarrays.\n  \n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/3svjmRjT/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3svjmRjT\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`, $k$ be the length of each subarray and $m$ be the required number of non-overlapping subarrays.\n\n- Time Complexity: $O(n \\cdot m) \\approx O(n)$\n\n    The algorithm first computes prefix sums in $O(n)$ time using a sliding window. The `dp` function fills an $n \\times (m + 1)$ memo table, where each state `(i, j)` is computed once due to memoization. The `dfs` function reconstructs the solution in $O(m)$ time by tracing the path through the `dp` table. \n    \n    Combining these, the overall time complexity is $O(n)$ for prefix sums, $O(n \\cdot m)$ for DP, and $O(m)$ for DFS, resulting in $O(n \\cdot m)$. With $m$ fixed at 3, this simplifies to $O(n)$.\n\n- Space Complexity: $O(n \\cdot m) \\approx O(n)$\n\n    The algorithm uses an array `sums` of size $n$ to store subarray sums and a `memo` table of size $n \\times (m + 1)$, which requires $O(n \\cdot m)$ space. The recursion stack depth is limited by $m$, contributing $O(m)$ to space complexity. The `indices` list stores $m$ elements. \n    \n    Thus, the space complexity is dominated by the `memo` table, resulting in $O(n \\cdot m)$. With $m$ fixed at 3, this simplifies to $O(n)$.\n\n> Note: While `m = 3` is fixed in this problem, we've kept it as a variable in the analysis to show how the complexity would scale if `m` were different. \n\n---\n\n### Approach 2: Tabulation\n\n#### Intuition\n\nOur previous top-down dynamic programming approach had two main drawbacks: recursive overhead and complex path reconstruction. Let's develop a more efficient bottom-up approach that eliminates the need for recursive path reconstruction.\n\nLet's shift our insight a bit: instead of thinking about \"What choices do we have at each position?\", we can think about \"What’s the best result we can achieve with a specific number of subarrays up to each position?\". \n\nNotice that at a particular position, if we know the best possible answer for the two subarrays occurring before it, we can easily find the biggest third subarray occurring after it and complete the problem. So, we can build our answer progressively by finding the best arrangements for one subarray first, then using that information to find the best arrangements for two subarrays, and finally for three subarrays. \n\nTo make this process faster, we optimize how we calculate subarray sums by using prefix sums. A prefix sum array holds the sum of elements from the start of the array up to each position. This lets us calculate any subarray sum quickly by subtracting two values from the prefix sum array: `prefixSum[end] - prefixSum[start]`.\n\nNow, let's build the main solution. For each index in the array, we’ll keep track of two things:  \n1. The best sum possible up to that index, called `bestSum`.\n2. The starting index that gives us this best sum, called `bestIndex`.\n\nWe’ll calculate these values for 1, 2, and 3 subarrays. To do this, we use a `bestIndex` matrix of size $4 \\times (n + 1)$, where `bestIndex[i][j]` gives the best sum achieved up to index `j` with `i` subarrays.\n\nWe'll loop over each number of subarrays starting from 1. Inside this loop, we loop over each array position and calculate the best possible sum for that position. For each index, the best sum will be one of two options:  \n- Option 1: The sum we get by including a subarray that ends at this position.\n- Option 2: The best sum we had up to the previous index (for the same number of subarrays).\n\nTo calculate **Option 2**, we simply retrieve the best sum from the previous index for the same subarray count from the `bestSum` array.\n\nTo calculate **Option 1**, we check the sum of the `k`-length subarray ending at the current position and add it to the best sum we could get with one less subarray, ending at the position `index - k`. This comes from the `bestSum[subarrayCount - 1][index - k]`.\n\nIf including the current subarray gives us a better sum, we update both `bestSum` and `bestIndex` to reflect this. If not, we keep the best values from the previous position. This approach also ensures that we find the lexicographically smallest result, because we only update when we find a strictly better sum.\n\nOnce the main loop is done, we'll have the best sum and the corresponding index for the three subarrays. Now, we need to figure out where each of these subarrays starts.\n\nStarting from the end of the array, we use the `bestIndex` table to trace back the starting index for each subarray. For the third subarray, we check the starting index stored for the best sum with three subarrays. After that, we work backward to find the starting index for the second and first subarrays. Each time we find the start of a subarray, we update `currentEnd` to be the start of the subarray we just picked. This ensures there is no overlap between subarrays.\n\nAt the end of this process, we’ll have the starting indices of the three subarrays that give the largest sum.\n\n#### Algorithm\n\n- Initialize a variable `n` to store the length of the input array `nums`.\n- Create a prefix sum array of size `n + 1`:\n  - Populate the prefix sum array by iteratively adding each element to the previous sum.\n- Create a 2D array:\n  - `bestSum` of size `4 x (n + 1)` to store the largest sums achievable with up to 3 subarrays ending at each position.\n  - `bestIndex` of size `4 x (n + 1)` to store starting indices of subarrays that give the best sums.\n- For each possible number of subarrays `subarrayCount`:\n  - For each possible ending position (`k * subarrayCount` to `n`):\n    - Calculate the current sum by adding the:\n      - Sum of the current window (using prefix sum).\n      - Best sum achievable with one less subarray ending before the current window.\n    - If the current sum is greater than the best sum ending at the previous position:\n      - Update `bestSum` at current position with current sum.\n      - Store the starting index of the current window in `bestIndex`.\n    - Otherwise:\n      - Copy `bestSum` and `bestIndex` from the previous position to the current position.\n- Create a `result` array of size 3 to store the final starting indices.\n- Initialize `currentEnd` to point to the end of the array.\n- For each subarray (counting down from `3` to `1`):\n  - Store the best starting index for the current subarray count in the `result` array.\n  - Update `currentEnd` to point to the start of the just-placed subarray.\n- Return the `result` array containing optimal starting indices.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Tf43XcQ3/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Tf43XcQ3\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`, $k$ be the length of each subarray and $m$ be the required number of non-overlapping subarrays.\n\n- Time complexity: $O(n \\cdot m) \\approx O(n)$\n\n    The algorithm first computes prefix sums in $O(n)$ time by traversing the array once. For each $t$ from $1$ to $m$, it iterates from position $k \\cdot t$ to $n$, performing constant-time operations at each step. This results in $O(n \\cdot m)$ operations due to the nested loops - $m$ outer iterations and approximately $n$ inner iterations. The final backtracking step takes $O(m)$ time. Thus, the overall time complexity is $O(n \\cdot m)$. With $m = 3$, this simplifies to $O(n)$.\n\n- Space complexity: $O(n \\cdot m) \\approx O(n)$\n\n    The algorithm uses a prefix sum array of size $n + 1$ to store cumulative sums. It also maintains two 2D arrays `bestSum` and `bestIndex`, each of size $(m + 1) \\times (n + 1)$, resulting in $O(n \\times m)$ space. The `result` array uses $O(m)$ space. Therefore, the total space complexity is $O(n \\times m)$. Since $m = 3$ in this problem, this reduces to $O(n)$.\n\n> Note: While `m = 3` is fixed in this problem, we've kept it as a variable in the analysis to show how the complexity would scale if `m` were different. \n\n---\n\n### Approach 3: Three Pointers\n\n#### Intuition\n\nIn the previous two approaches, we focused on finding the best solution for any number of non-overlapping subarrays. However, since our problem only requires finding 3 subarrays, we can use this fact to simplify our approach.\n\nWe can break the problem into three parts by **fixing the position of the middle subarray** first. This divides the array into three regions:\n1. The left region (before the middle subarray), where we need to find the best left subarray.\n2. The middle subarray itself.\n3. The right region (after the middle subarray), where we need to find the best right subarray.\n\nFor each possible position of the middle subarray, we can then find the best subarrays in the left and right regions. The highest sum across all possible middle subarray positions will give us the final answer.\n\nHowever, we need to optimize the way we calculate each subarray on either side while also maintaining information about their starting positions. In previous approaches, we used a prefix sum to precompute subarray sums. We'll now extend that idea further to also precompute the starting positions of the best subarray sums for each index in the array.\n\nTo implement this concept, we will create two arrays, `leftMaxIndex` and `rightMaxIndex`, to help us track the best subarrays for each segment. \n\nThe `leftMaxIndex[i]` array will store the starting index of the best subarray sum that ends at index `i`. To calculate this value, we compare the sum of the `k`-length subarray ending at `i` with the best sum we've found to the left of `i`. If the sum before is equal to the sum at index `i`, we prefer the earlier subarray, as we want the lexicographically smallest index. Similarly, we will build the `rightMaxIndex` array, where `rightMaxIndex[i]` will store the starting index of the best subarray sum starting at or after index `i`.\n\nIn the main loop, we will consider `k`-length subarrays starting from each index in the `nums` array. For each subarray, we will look up the corresponding `leftMaxIndex` and `rightMaxIndex` values, calculate the sum for these subarrays, and store the starting indices of the subarrays that give us the largest sum.\n\n#### Algorithm\n\n- Initialize variables:\n  - `n` to store the length of input array nums.\n  - `maxSum` to store the largest sum possible with three non-overlapping subarrays.\n- Create a prefix sum array of size `n + 1` to enable quick calculation of subarray sums.\n- Populate the prefix sum array by iteratively adding each element to the previous sum.\n- Create arrays `leftMaxIndex` and `rightMaxIndex` to store the best starting index for the left and right subarrays. respectively at each position.\n- Create a `result` array of size 3 to store the final starting indices.\n- Iterate from position `k` to `n - 1` to find the best left subarray for each position:\n  - Calculate the current subarray sum using prefix sum array.\n  - If current subarray sum is greater than the largest sum we have seen so far:\n    - Update `leftMaxIndex` at current position with the starting index of current subarray.\n    - Update the largest sum seen so far.\n  - Otherwise:\n    - Copy the previous best index to current position.\n- Set the rightmost possible position as initial best right subarray position.\n- Iterate from position `n - k - 1` to `0` to find the best right subarray for each position:\n  - Calculate the current subarray sum using prefix sum array.\n  - If current subarray sum is greater than or equal to the largest sum seen so far:\n    - Update `rightMaxIndex` at current position with the starting index of current subarray.\n    - Update the largest sum seen so far.\n  - Otherwise:\n    - Copy the next position's best index to current position.\n- Iterate over all possible middle subarray positions from `k` to `n - 2*k`:\n  - Get the best left subarray index before current position.\n  - Get the best right subarray index after current position plus `k`.\n  - Calculate total sum of all three subarrays using prefix sum array.\n  - If total sum is greater than `maxSum`:\n    - Update `maxSum` with the new largest sum.\n    - Store the three starting indices in the `result` array.\n- Return the `result` array containing the three optimal starting indices.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/oAxWfXoQ/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"oAxWfXoQ\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`.\n\n- Time complexity: $O(n)$\n\n    The algorithm performs four linear scans. The first scan builds the prefix sum array in $O(n)$ time. The second builds the `leftMaxIndex` array from left to right in $O(n)$. The third scan builds the `rightMaxIndex` array from right to left, also in $O(n)$. The final scan finds the optimal middle position in $O(n)$. Since each operation is a sequential linear scan, the overall time complexity is $O(n)$.\n\n- Space complexity: $O(n)$\n\n    The algorithm uses three arrays of size proportional to the input length: the prefix sum array of size $n+1$, a `leftMaxIndex` array of size $n$, and a `rightMaxIndex` array of size $n$. Since all auxiliary space usage grow linearly with the input size, the total space complexity is $O(n)$.\n\n---\n\n### Approach 4: Sliding Window\n\n#### Intuition\n\nIn Approach 2, we built up the solution incrementally: the best two subarrays were derived from the best single subarray, and the best three subarrays were built from the best two. We can extend this concept to create a more optimized solution that doesn’t require storing all possible sums — just the best ones at each step.\n\nImagine a train with three cars, each of length `k`, moving along a track (our array). The cars must maintain their order and can't overlap:\n\n```\nInitial position:\n[Car1][Car2][Car3]------------------\n 0    k     2k    \n\nAfter one move:\n-[Car1][Car2][Car3]-----------------\n 1    k+1   2k+1  \n\nAnd so on...\n```\nEach car calculates the sum of the numbers it covers. At each position, Car1 finds the best single-window sum seen so far, Car2 combines its current sum with the best sum from Car1, and Car3 combines its current sum with the best combined sum from Cars 1 and 2.\n\nThe main idea in this approach is that we don’t need to try every possible combination of subarrays. Instead, by keeping track of the best results so far at each level - for one subarray, two subarrays, and three subarrays - we can build the solution incrementally. When we reach the end of the `nums` array, the best result for three subarrays will be our final answer.\n\nWe'll first need to set up three sliding windows. We only need to keep track of their starting points, which will be `0`, `k`, and `2*k` respectively. This ensures that the windows never overlap. We'll calculate the sums of the subarrays within these windows and store them in three variables:\n1. `bestSingleSum` — The best sum for a single subarray.\n2. `bestDoubleSum` — The best sum for two non-overlapping subarrays.\n3. `bestTripleSum` — The best sum for three non-overlapping subarrays.\n\nAs the windows slide forward over the array, we update the current sums by subtracting the element that moves out of the window and adding the new element that enters. At each step, we update the “best seen so far” sums in sequence: first `bestSingleSum`, then `bestDoubleSum`, and finally `bestTripleSum`. \n\nAlong with updating the sums, we also track the starting indices for these best subarrays, so by the end of the loop, the indices corresponding to `bestTripleSum` will represent the solution. We return these indices as the final result.\n\nThe slideshow below demonstrates the algorithm in action (Consider `k = 3`):\n\n!?!../Documents/689_re/slideshow.json:1404,702!?!\n\n#### Algorithm\n\n- Initialize:\n  - a variable `bestSingleStart` to store the starting index of the best single subarray.\n  - an array `bestDoubleStart` to store the starting indices of the best two subarrays.\n  - an array `bestTripleStart` to store the starting indices of the best three subarrays.\n- Create a variable `currentWindowSumSingle` to store the sum of the first `k` elements.\n  - Calculate `currentWindowSumSingle` by adding the first `k` elements from the input array.\n- Create a variable `currentWindowSumDouble` to store the sum of the second window of `k` elements.\n  - Calculate `currentWindowSumDouble` by adding elements from index `k` to `2*k - 1`.\n- Create a variable `currentWindowSumTriple` to store the sum of the third window of `k` elements.\n  - Calculate `currentWindowSumTriple` by adding elements from index `2*k` to `3*k - 1`.\n- Initialize variables `bestSingleSum`, `bestDoubleSum` and `bestTripleSum` to store the largest sum achieved with one, two, and three subarrays, respectively.\n- Initialize three sliding window pointers: `singleStartIndex` at `1`, `doubleStartIndex` at `k + 1`, and `tripleStartIndex` at `2*k + 1`.\n- While `tripleStartIndex` is less than or equal to array length minus `k`:\n  - Update `currentWindowSumSingle`, `currentWindowSumDouble`, and `currentWindowSumTriple` by removing the leftmost element and adding the new rightmost element.\n  - If current `currentWindowSumSingle` is greater than `bestSingleSum`:\n    - Update `bestSingleStart` to current `singleStartIndex`.\n    - Update `bestSingleSum` to current `currentWindowSumSingle`.\n  - If the sum of current `currentWindowSumDouble` and `bestSingleSum` is greater than `bestDoubleSum`:\n    - Update `bestDoubleStart` with `bestSingleStart` and current `doubleStartIndex`.\n    - Update `bestDoubleSum` with the new largest sum.\n  - If the sum of current `currentWindowSumTriple` and `bestDoubleSum` is greater than `bestTripleSum`:\n    - Update `bestTripleStart` with `bestDoubleStart` and current `tripleStartIndex`.\n    - Update `bestTripleSum` with the new largest sum.\n  - Increment all three sliding window pointers.\n- Return `bestTripleStart` containing the optimal starting indices.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/MB2U2xdH/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"MB2U2xdH\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`.\n\n- Time complexity: $O(n + k)$\n\n    The algorithm computes three initial window sums, each taking $O(k)$. It then processes the array with three sliding windows, requiring $O(n)$. Since all operations are constant-time during the single pass, the total time complexity is $O(n + k)$.\n\n- Space complexity: $O(1)$\n\n    The algorithm uses a constant amount of extra space regardless of input size. It maintains three arrays of fixed sizes (`bestDoubleStart` of size $2$ and `bestTripleStart` of size $3$) and several single variables. Since none of these space requirements grow with the input size, the space complexity is $O(1)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n    ans = [-1] * 3\n    subarrayCount = len(nums) - k + 1\n    dp = [0] * subarrayCount\n    summ = 0\n\n    for i, num in enumerate(nums):\n      summ += num\n      if i >= k:\n        summ -= nums[i - k]\n      if i >= k - 1:\n        dp[i - k + 1] = summ\n\n    left = [0] * subarrayCount\n    maxIndex = 0\n\n    for i in range(subarrayCount):\n      if dp[i] > dp[maxIndex]:\n        maxIndex = i\n      left[i] = maxIndex\n\n    right = [0] * subarrayCount\n    maxIndex = subarrayCount - 1\n\n    for i in reversed(range(subarrayCount)):\n      if dp[i] >= dp[maxIndex]:\n        maxIndex = i\n      right[i] = maxIndex\n\n    for i in range(k, subarrayCount - k):\n      if ans[0] == -1 or dp[left[i - k]] + dp[i] + dp[right[i + k]] > dp[ans[0]] + dp[ans[1]] + dp[ans[2]]:\n        ans = [left[i - k], i, right[i + k]]\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int[] maxSumOfThreeSubarrays(int[] nums, int k) {\n    final int n = nums.length - k + 1;\n    int[] sums = new int[n]; // sums[i] := sum of nums[i..i + k)\n    int[] l = new int[n];    // l[i] := index in [0..i] having max sums[i]\n    int[] r = new int[n];    // r[i] := index in [i..n) having max sums[i]\n\n    int sum = 0;\n    for (int i = 0; i < nums.length; ++i) {\n      sum += nums[i];\n      if (i >= k)\n        sum -= nums[i - k];\n      if (i >= k - 1)\n        sums[i - k + 1] = sum;\n    }\n\n    int maxIndex = 0;\n    for (int i = 0; i < n; ++i) {\n      if (sums[i] > sums[maxIndex])\n        maxIndex = i;\n      l[i] = maxIndex;\n    }\n\n    maxIndex = n - 1;\n    for (int i = n - 1; i >= 0; --i) {\n      if (sums[i] >= sums[maxIndex])\n        maxIndex = i;\n      r[i] = maxIndex;\n    }\n\n    int[] ans = {-1, -1, -1};\n\n    for (int i = k; i + k < n; ++i)\n      if (ans[0] == -1 ||\n          sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]) {\n        ans[0] = l[i - k];\n        ans[1] = i;\n        ans[2] = r[i + k];\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {\n    const int n = nums.size() - k + 1;\n    vector<int> sums(n);  // sums[i] := sum of nums[i..i + k)\n    vector<int> l(n);     // l[i] := index in [0..i] having max sums[i]\n    vector<int> r(n);     // r[i] := index in [i..n) having max sums[i]\n\n    int sum = 0;\n    for (int i = 0; i < nums.size(); ++i) {\n      sum += nums[i];\n      if (i >= k)\n        sum -= nums[i - k];\n      if (i >= k - 1)\n        sums[i - k + 1] = sum;\n    }\n\n    int maxIndex = 0;\n    for (int i = 0; i < n; ++i) {\n      if (sums[i] > sums[maxIndex])\n        maxIndex = i;\n      l[i] = maxIndex;\n    }\n\n    maxIndex = n - 1;\n    for (int i = n - 1; i >= 0; --i) {\n      if (sums[i] >= sums[maxIndex])\n        maxIndex = i;\n      r[i] = maxIndex;\n    }\n\n    vector<int> ans{-1, -1, -1};\n\n    for (int i = k; i < n - k; ++i)\n      if (ans[0] == -1 || sums[ans[0]] + sums[ans[1]] + sums[ans[2]] <\n                              sums[l[i - k]] + sums[i] + sums[r[i + k]]) {\n        ans[0] = l[i - k];\n        ans[1] = i;\n        ans[2] = r[i + k];\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/689.html",
    "category": "Algorithms",
    "acceptance_rate": 59.43009545199326,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Sliding Window",
      "Prefix Sum"
    ],
    "hints": [],
    "likes": 2541,
    "dislikes": 156,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock III\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sum of Variable Length Subarrays\", \"titleSlug\": \"sum-of-variable-length-subarrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"148.2K\", \"totalSubmission\": \"249.3K\", \"totalAcceptedRaw\": 148182, \"totalSubmissionRaw\": 249339, \"acRate\": \"59.4%\"}",
    "title_pt": "Soma Máxima de 3 Subarrays Não Sobrepostos",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, encontre três subarrays não sobrepostos de comprimento <code>k</code> com soma máxima e retorne-os.</p>\n\n<p>Retorne o resultado como uma lista de índices representando a posição inicial de cada intervalo (<strong>indexado em 0</strong>). Se houver múltiplas respostas, retorne a menor em ordem lexicográfica.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,1,2,6,7,5,1], k = 2\n<strong>Saída:</strong> [0,3,5]\n<strong>Explicação:</strong> Os subarrays [1, 2], [2, 6], [7, 5] correspondem aos índices iniciais [0, 3, 5].\nPoderíamos também ter escolhido [2, 1], mas uma resposta de [1, 3, 5] seria menor em ordem lexicográfica.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,1,2,1,2,1,2,1], k = 2\n<strong>Saída:</strong> [0,2,4]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;&nbsp;2<sup>16</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= floor(nums.length / 3)</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "690",
    "paidOnly": false,
    "title": "Employee Importance",
    "titleSlug": "employee-importance",
    "url": "https://leetcode.com/problems/employee-importance",
    "description_url": "https://leetcode.com/problems/employee-importance/description/",
    "description": "<p>You have a data structure of employee information, including the employee&#39;s unique ID, importance value, and direct subordinates&#39; IDs.</p>\n\n<p>You are given an array of employees <code>employees</code> where:</p>\n\n<ul>\n\t<li><code>employees[i].id</code> is the ID of the <code>i<sup>th</sup></code> employee.</li>\n\t<li><code>employees[i].importance</code> is the importance value of the <code>i<sup>th</sup></code> employee.</li>\n\t<li><code>employees[i].subordinates</code> is a list of the IDs of the direct subordinates of the <code>i<sup>th</sup></code> employee.</li>\n</ul>\n\n<p>Given an integer <code>id</code> that represents an employee&#39;s ID, return <em>the <strong>total</strong> importance value of this employee and all their direct and indirect subordinates</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg\" style=\"width: 400px; height: 258px;\" />\n<pre>\n<strong>Input:</strong> employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\n<strong>Output:</strong> 11\n<strong>Explanation:</strong> Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg\" style=\"width: 362px; height: 361px;\" />\n<pre>\n<strong>Input:</strong> employees = [[1,2,[5]],[5,-3,[]]], id = 5\n<strong>Output:</strong> -3\n<strong>Explanation:</strong> Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= employees.length &lt;= 2000</code></li>\n\t<li><code>1 &lt;= employees[i].id &lt;= 2000</code></li>\n\t<li>All <code>employees[i].id</code> are <strong>unique</strong>.</li>\n\t<li><code>-100 &lt;= employees[i].importance &lt;= 100</code></li>\n\t<li>One employee has at most one direct leader and may have several subordinates.</li>\n\t<li>The IDs in <code>employees[i].subordinates</code> are valid IDs.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/employee-importance/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Depth-First Search [Accepted]\n\n**Intuition and Algorithm**\n\nLet's use a hashmap `emap = {employee.id -> employee}` to query employees quickly.\n\nNow to find the total importance of an employee, it will be the importance of that employee, plus the total importance of each of that employee's subordinates.  This is a straightforward depth-first search.\n\n<iframe src=\"https://leetcode.com/playground/jnJd8b9P/shared\" frameBorder=\"0\" width=\"100%\" height=\"361\" name=\"jnJd8b9P\"></iframe>\n\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the number of employees. We might query each employee in `dfs`.\n\n* Space Complexity: $$O(N)$$, the size of the implicit call stack when evaluating `dfs`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def getImportance(self, employees: List['Employee'], id: int) -> int:\n    idToEmployee = {employee.id: employee for employee in employees}\n\n    def dfs(id: int) -> int:\n      values = idToEmployee[id].importance\n      for subId in idToEmployee[id].subordinates:\n        values += dfs(subId)\n      return values\n\n    return dfs(id)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int getImportance(List<Employee> employees, int id) {\n    Map<Integer, Employee> idToEmployee = new HashMap<>();\n\n    for (Employee employee : employees)\n      idToEmployee.put(employee.id, employee);\n\n    return dfs(id, idToEmployee);\n  }\n\n  private int dfs(int id, Map<Integer, Employee> idToEmployee) {\n    int values = 0;\n\n    for (final int subId : idToEmployee.get(id).subordinates)\n      values += dfs(subId, idToEmployee);\n\n    return idToEmployee.get(id).importance + values;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int getImportance(vector<Employee*> employees, int id) {\n    unordered_map<int, Employee*> idToEmployee;\n\n    for (Employee* employee : employees)\n      idToEmployee[employee->id] = employee;\n\n    return dfs(id, idToEmployee);\n  }\n\n private:\n  int dfs(int id, const unordered_map<int, Employee*>& idToEmployee) {\n    int values = 0;\n\n    for (const int subId : idToEmployee.at(id)->subordinates)\n      values += dfs(subId, idToEmployee);\n\n    return idToEmployee.at(id)->importance + values;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/690.html",
    "category": "Algorithms",
    "acceptance_rate": 68.29203967707433,
    "topics": [
      "Array",
      "Hash Table",
      "Tree",
      "Depth-First Search",
      "Breadth-First Search"
    ],
    "hints": [],
    "likes": 2159,
    "dislikes": 1347,
    "similar_questions": "[{\"title\": \"Nested List Weight Sum\", \"titleSlug\": \"nested-list-weight-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"233K\", \"totalSubmission\": \"341.3K\", \"totalAcceptedRaw\": 233049, \"totalSubmissionRaw\": 341254, \"acRate\": \"68.3%\"}",
    "title_pt": "Importância do Funcionário",
    "description_pt": "<p>Você tem uma estrutura de dados com informações de funcionários, incluindo o ID único do funcionário, o valor de importância e os IDs de seus subordinados diretos.</p>\n\n<p>Você recebe um array de funcionários <code>employees</code> onde:</p>\n\n<ul>\n\t<li><code>employees[i].id</code> é o ID do <code>i<sup>th</sup></code> funcionário.</li>\n\t<li><code>employees[i].importance</code> é o valor de importância do <code>i<sup>th</sup></code> funcionário.</li>\n\t<li><code>employees[i].subordinates</code> é uma lista dos IDs dos subordinados diretos do <code>i<sup>th</sup></code> funcionário.</li>\n</ul>\n\n<p>Dado um inteiro <code>id</code> que representa o ID de um funcionário, retorne <em>o valor de importância <strong>total</strong> desse funcionário e de todos os seus subordinados diretos e indiretos</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/31/emp1-tree.jpg\" style=\"width: 400px; height: 258px;\" />\n<pre>\n<strong>Entrada:</strong> employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\n<strong>Saída:</strong> 11\n<strong>Explicação:</strong> O funcionário 1 tem um valor de importância de 5 e tem dois subordinados diretos: o funcionário 2 e o funcionário 3.\nAmbos têm um valor de importância de 3.\nAssim, o valor total de importância do funcionário 1 é 5 + 3 + 3 = 11.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/31/emp2-tree.jpg\" style=\"width: 362px; height: 361px;\" />\n<pre>\n<strong>Entrada:</strong> employees = [[1,2,[5]],[5,-3,[]]], id = 5\n<strong>Saída:</strong> -3\n<strong>Explicação:</strong> O funcionário 5 tem um valor de importância de -3 e não tem subordinados diretos.\nAssim, o valor total de importância do funcionário 5 é -3.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= employees.length &lt;= 2000</code></li>\n\t<li><code>1 &lt;= employees[i].id &lt;= 2000</code></li>\n\t<li>Todos os <code>employees[i].id</code> são <strong>únicos</strong>.</li>\n\t<li><code>-100 &lt;= employees[i].importance &lt;= 100</code></li>\n\t<li>Um funcionário tem, no máximo, um chefe direto e pode ter vários subordinados.</li>\n\t<li>Os IDs em <code>employees[i].subordinates</code> são IDs válidos.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "691",
    "paidOnly": false,
    "title": "Stickers to Spell Word",
    "titleSlug": "stickers-to-spell-word",
    "url": "https://leetcode.com/problems/stickers-to-spell-word",
    "description_url": "https://leetcode.com/problems/stickers-to-spell-word/description/",
    "description": "<p>We are given <code>n</code> different types of <code>stickers</code>. Each sticker has a lowercase English word on it.</p>\n\n<p>You would like to spell out the given string <code>target</code> by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.</p>\n\n<p>Return <em>the minimum number of stickers that you need to spell out </em><code>target</code>. If the task is impossible, return <code>-1</code>.</p>\n\n<p><strong>Note:</strong> In all test cases, all words were chosen randomly from the <code>1000</code> most common US English words, and <code>target</code> was chosen as a concatenation of two random words.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> stickers = [&quot;with&quot;,&quot;example&quot;,&quot;science&quot;], target = &quot;thehat&quot;\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nWe can use 2 &quot;with&quot; stickers, and 1 &quot;example&quot; sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target &quot;thehat&quot;.\nAlso, this is the minimum number of stickers necessary to form the target string.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> stickers = [&quot;notice&quot;,&quot;possible&quot;], target = &quot;basicbasic&quot;\n<strong>Output:</strong> -1\nExplanation:\nWe cannot form the target &quot;basicbasic&quot; from cutting letters from the given stickers.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == stickers.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 50</code></li>\n\t<li><code>1 &lt;= stickers[i].length &lt;= 10</code></li>\n\t<li><code>1 &lt;= target.length &lt;= 15</code></li>\n\t<li><code>stickers[i]</code> and <code>target</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/stickers-to-spell-word/solutions/",
    "solution": "[TOC]\n\n### Approach 1: Optimized Exhaustive Search\n\n<br>\n\n**Intuition**\n\nA natural answer is to exhaustively search for combinations of stickers. Because the data is randomized, there are many heuristics available to us that will make this faster.\n\n* For all stickers, we can ignore any letters that are not in the target word.\n\n* When our candidate's answer won't be smaller than an answer we have already found, we can stop searching this path.\n\n* We should try to have our exhaustive search bound to the answer as soon as possible, so the effect described in the above point happens more often.\n\n* When a sticker dominates another, we shouldn't include the dominant sticker in our sticker collection.  [Here, we say a sticker `A` dominates `B` if `A.count(letter) >= B.count(letter)` for all letters.]\n\n<br>\n\n**Algorithm**\n\nFirstly, for each sticker, let's create a count of that sticker (a mapping `letter -> sticker.count(letter)`) that does not consider letters not in the target word.  Let `A` be an array of these counts.  Also, let's create `t_count`, a count of our `target` word.\n\nSecondly, let's remove dominated stickers. Because dominance is a transitive relation, we only need to check if a sticker is not dominated by any other sticker once - the ones that aren't dominated are included in our collection.\n\nWe are now ready to begin our exhaustive search. A call to `search(ans)` denotes that we want to decide the minimum number of stickers we can use in `A` to satisfy the target count `t_count`. `ans` will store the currently formed answer, and `best` will store the current best answer.\n\nIf our current answer can't beat our current best answer, we should stop searching.  Also, if there are no stickers left and our target is satisfied, we should update our answer.\n\nOtherwise, we want to know the maximum number of these stickers we can use. For example, if this sticker is `'abb'` and our target is `'aaabbbbccccc'`, then we could use a maximum of 3 stickers.  This is the maximum of `math.ceil(target.count(letter) / sticker.count(letter))`, taken over all `letter`s in `sticker`.  Let's call this quantity `used`.\n\nAfter, for the sticker we are currently considering, we try to use `used` of them, then `used - 1`, `used - 2`, and so on. The reason we do it in this order is so that we can arrive at a value for `best` more quickly, which will stop other branches of our exhaustive search from continuing.\n\nThe Python version of this solution showcases using `collections.Counter` as a way to simplify some code sections, whereas the Java solution sticks to arrays.\n\n<iframe src=\"https://leetcode.com/playground/KP3fS7G3/shared\" frameBorder=\"0\" name=\"KP3fS7G3\" width=\"100%\" height=\"515\"></iframe>\n\n<br>\n\n**Complexity Analysis**\n\n* Time Complexity: Let $$N$$ be the number of stickers, and $$T$$ be the number of letters in the target word. A bound for time complexity is $$O(N^{T+1} T^2)$$: for each sticker, we'll have to try using it up to $$T+1$$ times, and updating our target count costs $$O(T)$$, which we do up to $$T$$ times. Alternatively, since the answer is bounded at $$T$$, we can prove that we can only search up to $$\\binom{N+T-1}{T-1}$$ times. This would be $$O(\\binom{N+T-1}{T-1} T^2)$$.\n\n* Space Complexity: $$O(N+T)$$, to store `stickersCount`, `targetCount`, and handle the recursive call stack when calling `search`.\n\n<br>\n\n---\n### Approach 2: Dynamic Programming\n\n<br>\n\n**Intuition**\n\nSuppose we need `dp[state]` stickers to satisfy all `target[i]`'s for which the `i`-th bit of `state` is set. We would like to know `dp[(1 << len(target)) - 1]`.\n\n<br>\n\n**Algorithm**\n\nFor each `state`, let's work with it as `now` and look at what happens to it after applying a sticker. For each letter in the sticker that can satisfy an unset bit of `state`, we set the bit (`now |= 1 << i`). In the end, we know `now` is the result of applying that sticker to `state`, and we update our `dp` appropriately.\n\nWhen using Python, we will need some extra techniques from *Approach #1* to pass in time.\n\n<iframe src=\"https://leetcode.com/playground/JTZ2SYco/shared\" frameBorder=\"0\" name=\"JTZ2SYco\" width=\"100%\" height=\"515\"></iframe>\n\n<br>\n\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(2^T * S * T)$$ where $$S$$ is the total number of letters in all stickers, and $$T$$ is the number of letters in the target word. We can examine each loop carefully to arrive at this conclusion.\n\n* Space Complexity: $$O(2^T)$$, the space used by `dp`.\n\n<br>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def minStickers(self, stickers: List[str], target: str) -> int:\n    n = len(target)\n    maxMask = 1 << n\n    # dp[i] := min # Of stickers to spell out i,\n    # Where i is the bit representation of target\n    dp = [math.inf] * maxMask\n    dp[0] = 0\n\n    for mask in range(maxMask):\n      if dp[mask] == math.inf:\n        continue\n      # Try to expand from `mask` by using each sticker\n      for sticker in stickers:\n        superMask = mask\n        for c in sticker:\n          for i, t in enumerate(target):\n            # Try to apply it on a missing char\n            if c == t and not (superMask >> i & 1):\n              superMask |= 1 << i\n              break\n        dp[superMask] = min(dp[superMask], dp[mask] + 1)\n\n    return -1 if dp[-1] == math.inf else dp[-1]",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minStickers(String[] stickers, String target) {\n    final int n = target.length();\n    final int maxMask = 1 << n;\n    // dp[i] := min # of stickers to spell out i,\n    // Where i is the bit representation of target\n    int[] dp = new int[maxMask];\n    Arrays.fill(dp, Integer.MAX_VALUE);\n    dp[0] = 0;\n\n    for (int mask = 0; mask < maxMask; ++mask) {\n      if (dp[mask] == Integer.MAX_VALUE)\n        continue;\n      // Try to expand from `mask` by using each sticker\n      for (final String sticker : stickers) {\n        int superMask = mask;\n        for (final char c : sticker.toCharArray())\n          for (int i = 0; i < n; ++i)\n            // Try to apply it on a missing char\n            if (c == target.charAt(i) && (superMask >> i & 1) == 0) {\n              superMask |= 1 << i;\n              break;\n            }\n        dp[superMask] = Math.min(dp[superMask], dp[mask] + 1);\n      }\n    }\n\n    return dp[maxMask - 1] == Integer.MAX_VALUE ? -1 : dp[maxMask - 1];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minStickers(vector<string>& stickers, string target) {\n    const int n = target.size();\n    const int maxMask = 1 << n;\n    // dp[i] := min # of stickers to spell out i,\n    // Where i is the bit representation of target\n    vector<int> dp(maxMask, INT_MAX);\n    dp[0] = 0;\n\n    for (int mask = 0; mask < maxMask; ++mask) {\n      if (dp[mask] == INT_MAX)\n        continue;\n      // Try to expand from `mask` by using each sticker\n      for (const string& sticker : stickers) {\n        int superMask = mask;\n        for (const char c : sticker)\n          for (int i = 0; i < n; ++i)\n            // Try to apply it on a missing char\n            if (c == target[i] && !(superMask >> i & 1)) {\n              superMask |= 1 << i;\n              break;\n            }\n        dp[superMask] = min(dp[superMask], dp[mask] + 1);\n      }\n    }\n\n    return dp.back() == INT_MAX ? -1 : dp.back();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/691.html",
    "category": "Algorithms",
    "acceptance_rate": 49.97971556717528,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Dynamic Programming",
      "Backtracking",
      "Bit Manipulation",
      "Memoization",
      "Bitmask"
    ],
    "hints": [
      "We want to perform an exhaustive search, but we need to speed it up based on the input data being random.  \r\n\r\nFor all stickers, we can ignore any letters that are not in the target word.  \r\n\r\nWhen our candidate answer won't be smaller than an answer we have already found, we can stop searching this path.  \r\n\r\nWhen a sticker dominates another, we shouldn't include the dominated sticker in our sticker collection.  [Here, we say a sticker `A` dominates `B` if `A.count(letter) >= B.count(letter)` for all letters.]"
    ],
    "likes": 1286,
    "dislikes": 127,
    "similar_questions": "[{\"title\": \"Ransom Note\", \"titleSlug\": \"ransom-note\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"88.7K\", \"totalSubmission\": \"177.5K\", \"totalAcceptedRaw\": 88702, \"totalSubmissionRaw\": 177476, \"acRate\": \"50.0%\"}",
    "title_pt": "Figurinhas para Soletrar Palavra",
    "description_pt": "<p>Temos <code>n</code> tipos diferentes de <code>stickers</code>. Cada sticker tem uma palavra em inglês minúscula escrita nele.</p>\n\n<p>Você gostaria de soletrar a string fornecida <code>target</code> cortando letras individuais da sua coleção de stickers e reorganizando-as. Você pode usar cada sticker mais de uma vez, se quiser, e você tem quantidades infinitas de cada sticker.</p>\n\n<p>Retorne <em>o número mínimo de stickers que você precisa para soletrar </em><code>target</code>. Se a tarefa for impossível, retorne <code>-1</code>.</p>\n\n<p><strong>Nota:</strong> Em todos os casos de teste, todas as palavras foram escolhidas aleatoriamente entre as <code>1000</code> palavras mais comuns do inglês americano, e <code>target</code> foi escolhida como a concatenação de duas palavras aleatórias.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> stickers = [&quot;with&quot;,&quot;example&quot;,&quot;science&quot;], target = &quot;thehat&quot;\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>\nPodemos usar 2 stickers &quot;with&quot; e 1 sticker &quot;example&quot;.\nDepois de cortar e reorganizar as letras desses stickers, podemos formar a string alvo &quot;thehat&quot;.\nAlém disso, este é o número mínimo de stickers necessário para formar a string alvo.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> stickers = [&quot;notice&quot;,&quot;possible&quot;], target = &quot;basicbasic&quot;\n<strong>Saída:</strong> -1\nExplicação:\nNão podemos formar a string alvo &quot;basicbasic&quot; a partir do corte de letras dos stickers fornecidos.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == stickers.length</code></li>\n\t<li><code>1 &lt;= n &lt;= 50</code></li>\n\t<li><code>1 &lt;= stickers[i].length &lt;= 10</code></li>\n\t<li><code>1 &lt;= target.length &lt;= 15</code></li>\n\t<li><code>stickers[i]</code> e <code>target</code> consistem de letras minúsculas do inglês.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Queremos realizar uma busca exaustiva, mas precisamos acelerá-la com base no fato de os dados de entrada serem aleatórios.  \n\nPara todos os stickers, podemos ignorar quaisquer letras que não estejam na palavra alvo.  \n\nQuando nossa resposta candidata não for menor do que uma resposta que já encontramos, podemos parar de procurar esse caminho.  \n\nQuando um sticker domina outro, não devemos incluir o sticker dominado em nossa coleção de stickers.  [Aqui, dizemos que um sticker `A` domina `B` se `A.count(letter) >= B.count(letter)` para todas as letras.]"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "692",
    "paidOnly": false,
    "title": "Top K Frequent Words",
    "titleSlug": "top-k-frequent-words",
    "url": "https://leetcode.com/problems/top-k-frequent-words",
    "description_url": "https://leetcode.com/problems/top-k-frequent-words/description/",
    "description": "<p>Given an array of strings <code>words</code> and an integer <code>k</code>, return <em>the </em><code>k</code><em> most frequent strings</em>.</p>\n\n<p>Return the answer <strong>sorted</strong> by <strong>the frequency</strong> from highest to lowest. Sort the words with the same frequency by their <strong>lexicographical order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;i&quot;,&quot;love&quot;,&quot;leetcode&quot;,&quot;i&quot;,&quot;love&quot;,&quot;coding&quot;], k = 2\n<strong>Output:</strong> [&quot;i&quot;,&quot;love&quot;]\n<strong>Explanation:</strong> &quot;i&quot; and &quot;love&quot; are the two most frequent words.\nNote that &quot;i&quot; comes before &quot;love&quot; due to a lower alphabetical order.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;the&quot;,&quot;day&quot;,&quot;is&quot;,&quot;sunny&quot;,&quot;the&quot;,&quot;the&quot;,&quot;the&quot;,&quot;sunny&quot;,&quot;is&quot;,&quot;is&quot;], k = 4\n<strong>Output:</strong> [&quot;the&quot;,&quot;is&quot;,&quot;sunny&quot;,&quot;day&quot;]\n<strong>Explanation:</strong> &quot;the&quot;, &quot;is&quot;, &quot;sunny&quot; and &quot;day&quot; are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 500</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n\t<li><code>k</code> is in the range <code>[1, The number of <strong>unique</strong> words[i]]</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Follow-up:</strong> Could you solve it in <code>O(n log(k))</code> time and <code>O(n)</code> extra space?</p>\n",
    "solution_url": "https://leetcode.com/problems/top-k-frequent-words/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def topKFrequent(self, words: List[str], k: int) -> List[str]:\n    ans = []\n    bucket = [[] for _ in range(len(words) + 1)]\n\n    for word, freq in Counter(words).items():\n      bucket[freq].append(word)\n\n    for b in reversed(bucket):\n      for word in sorted(b):\n        ans.append(word)\n        if len(ans) == k:\n          return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> topKFrequent(String[] words, int k) {\n    final int n = words.length;\n    List<String> ans = new ArrayList<>();\n    List<String>[] bucket = new List[n + 1];\n    Map<String, Integer> count = new HashMap<>();\n\n    for (final String word : words)\n      count.put(word, count.getOrDefault(word, 0) + 1);\n\n    for (final String word : count.keySet()) {\n      final int freq = count.get(word);\n      if (bucket[freq] == null)\n        bucket[freq] = new ArrayList<>();\n      bucket[freq].add(word);\n    }\n\n    for (int freq = n; freq > 0; --freq)\n      if (bucket[freq] != null) {\n        Collections.sort(bucket[freq]);\n        for (final String word : bucket[freq]) {\n          ans.add(word);\n          if (ans.size() == k)\n            return ans;\n        }\n      }\n\n    throw new IllegalArgumentException();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> topKFrequent(vector<string>& words, int k) {\n    const int n = words.size();\n    vector<string> ans;\n    vector<vector<string>> bucket(n + 1);\n    unordered_map<string, int> count;\n\n    for (const string& word : words)\n      ++count[word];\n\n    for (const auto& [word, freq] : count)\n      bucket[freq].push_back(word);\n\n    for (int freq = n; freq > 0; --freq) {\n      sort(begin(bucket[freq]), end(bucket[freq]));\n      for (const string& word : bucket[freq]) {\n        ans.push_back(word);\n        if (ans.size() == k)\n          return ans;\n      }\n    }\n\n    throw;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/692.html",
    "category": "Algorithms",
    "acceptance_rate": 59.16718959347388,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Trie",
      "Sorting",
      "Heap (Priority Queue)",
      "Bucket Sort",
      "Counting"
    ],
    "hints": [],
    "likes": 7827,
    "dislikes": 363,
    "similar_questions": "[{\"title\": \"Top K Frequent Elements\", \"titleSlug\": \"top-k-frequent-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Closest Points to Origin\", \"titleSlug\": \"k-closest-points-to-origin\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Features by Popularity\", \"titleSlug\": \"sort-features-by-popularity\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sender With Largest Word Count\", \"titleSlug\": \"sender-with-largest-word-count\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Pairs in Array\", \"titleSlug\": \"maximum-number-of-pairs-in-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"697.7K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 697729, \"totalSubmissionRaw\": 1179252, \"acRate\": \"59.2%\"}",
    "title_pt": "Palavras Mais Frequentes entre as K Principais",
    "description_pt": "<p>Dado um array de strings <code>words</code> e um inteiro <code>k</code>, retorne <em>as </em><code>k</code><em> strings mais frequentes</em>.</p>\n\n<p>Retorne a resposta <strong>ordenada</strong> pela <strong>frequência</strong> da maior para a menor. Ordene as palavras com a mesma frequência por sua <strong>ordem lexicográfica</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;i&quot;,&quot;love&quot;,&quot;leetcode&quot;,&quot;i&quot;,&quot;love&quot;,&quot;coding&quot;], k = 2\n<strong>Saída:</strong> [&quot;i&quot;,&quot;love&quot;]\n<strong>Explicação:</strong> &quot;i&quot; e &quot;love&quot; são as duas palavras mais frequentes.\nNote que &quot;i&quot; vem antes de &quot;love&quot; devido a uma ordem alfabética menor.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;the&quot;,&quot;day&quot;,&quot;is&quot;,&quot;sunny&quot;,&quot;the&quot;,&quot;the&quot;,&quot;the&quot;,&quot;sunny&quot;,&quot;is&quot;,&quot;is&quot;], k = 4\n<strong>Saída:</strong> [&quot;the&quot;,&quot;is&quot;,&quot;sunny&quot;,&quot;day&quot;]\n<strong>Explicação:</strong> &quot;the&quot;, &quot;is&quot;, &quot;sunny&quot; e &quot;day&quot; são as quatro palavras mais frequentes, com o número de ocorrências sendo 4, 3, 2 e 1 respectivamente.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 500</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 10</code></li>\n\t<li><code>words[i]</code> consiste de letras minúsculas do alfabeto inglês.</li>\n\t<li><code>k</code> está no intervalo <code>[1, The number of <strong>unique</strong> words[i]]</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Desafio extra:</strong> Você conseguiria resolvê-lo em tempo <code>O(n log(k))</code> e espaço extra <code>O(n)</code>?</p>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "693",
    "paidOnly": false,
    "title": "Binary Number with Alternating Bits",
    "titleSlug": "binary-number-with-alternating-bits",
    "url": "https://leetcode.com/problems/binary-number-with-alternating-bits",
    "description_url": "https://leetcode.com/problems/binary-number-with-alternating-bits/description/",
    "description": "<p>Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 5\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The binary representation of 5 is: 101\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 7\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The binary representation of 7 is: 111.</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> n = 11\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The binary representation of 11 is: 1011.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-number-with-alternating-bits/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Convert to String [Accepted]\n\n**Intuition and Algorithm**\n\nLet's convert the given number into a string of binary digits. Then, we should simply check that no two adjacent digits are the same.\n\n<iframe src=\"https://leetcode.com/playground/79o5Wvyy/shared\" frameBorder=\"0\" name=\"79o5Wvyy\" width=\"100%\" height=\"241\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(1)$$. For arbitrary inputs, we do $$O(w)$$ work, where $$w$$ is the number of bits in `n`. However, $$w \\leq 32$$.\n\n* Space complexity: $$O(1)$$, or alternatively $$O(w)$$.\n\n---\n\n### Approach #2: Divide By Two [Accepted]\n\n**Intuition and Algorithm**\n\nWe can get the last bit and the rest of the bits via `n % 2` and `n // 2` operations. Let's remember `cur`, the last bit of `n`. If the last bit ever equals the last bit of the remaining, then two adjacent bits have the same value, and the answer is `False`.  Otherwise, the answer is `True`.\n\nAlso note that instead of `n % 2` and `n // 2`, we could have used operators `n & 1` and `n >>= 1` instead.\n\n<iframe src=\"https://leetcode.com/playground/oFAELrSA/shared\" frameBorder=\"0\" name=\"oFAELrSA\" width=\"100%\" height=\"258\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(1)$$. For arbitrary inputs, we do $$O(w)$$ work, where $$w$$ is the number of bits in `n`. However, $$w \\leq 32$$.\n\n* Space complexity: $$O(1)$$.",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/693.html",
    "category": "Algorithms",
    "acceptance_rate": 63.40649069172276,
    "topics": [
      "Bit Manipulation"
    ],
    "hints": [],
    "likes": 1398,
    "dislikes": 113,
    "similar_questions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"155.3K\", \"totalSubmission\": \"245K\", \"totalAcceptedRaw\": 155340, \"totalSubmissionRaw\": 244993, \"acRate\": \"63.4%\"}",
    "title_pt": "Número Binário com Bits Alternados",
    "description_pt": "<p>Dado um inteiro positivo, verifique se ele tem bits alternados: ou seja, se dois bits adjacentes sempre terão valores diferentes.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 5\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> A representação binária de 5 é: 101\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 7\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> A representação binária de 7 é: 111.</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> n = 11\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> A representação binária de 11 é: 1011.</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "695",
    "paidOnly": false,
    "title": "Max Area of Island",
    "titleSlug": "max-area-of-island",
    "url": "https://leetcode.com/problems/max-area-of-island",
    "description_url": "https://leetcode.com/problems/max-area-of-island/description/",
    "description": "<p>You are given an <code>m x n</code> binary matrix <code>grid</code>. An island is a group of <code>1</code>&#39;s (representing land) connected <strong>4-directionally</strong> (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.</p>\n\n<p>The <strong>area</strong> of an island is the number of cells with a value <code>1</code> in the island.</p>\n\n<p>Return <em>the maximum <strong>area</strong> of an island in </em><code>grid</code>. If there is no island, return <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg\" style=\"width: 500px; height: 310px;\" />\n<pre>\n<strong>Input:</strong> grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> The answer is not 11, because the island must be connected 4-directionally.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> grid = [[0,0,0,0,0,0,0,0]]\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/max-area-of-island/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Depth-First Search (Recursive) [Accepted]\n\n**Intuition and Algorithm**\n\nWe want to know the area of each connected shape in the grid, then take the maximum of these.\n\nIf we are on a land square and explore every square connected to it 4-directionally (and recursively squares connected to those squares, and so on), then the total number of squares explored will be the area of that connected shape.\n\nTo ensure we don't count squares in a shape more than once, let's use `seen` to keep track of squares we haven't visited before. It will also prevent us from counting the same shape more than once.\n\n<iframe src=\"https://leetcode.com/playground/CQGNqDhr/shared\" frameBorder=\"0\" name=\"CQGNqDhr\" width=\"100%\" height=\"479\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(R*C)$$, where $$R$$ is the number of rows in the given `grid`, and $$C$$ is the number of columns.  We visit every square once.\n\n* Space complexity: $$O(R*C)$$, the space used by `seen` to keep track of visited squares and the space used by the call stack during our recursion.\n\n---\n### Approach #2: Depth-First Search (Iterative) [Accepted]\n\n**Intuition and Algorithm**\n\nWe can try the same approach using a stack-based, (or \"iterative\") depth-first search.\n\nHere, `seen` will represent squares that have either been visited or are added to our list of squares to visit (`stack`). For every starting land square that hasn't been visited, we will explore 4-directionally around it, adding land squares that haven't been added to `seen` to our `stack`.\n\nOn the side, we'll keep a count `shape` of the total number of squares seen during the exploration of this shape. We'll want the running max of these counts.\n\n<iframe src=\"https://leetcode.com/playground/khZHhSir/shared\" frameBorder=\"0\" name=\"khZHhSir\" width=\"100%\" height=\"515\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(R*C)$$, where $$R$$ is the number of rows in the given `grid`, and $$C$$ is the number of columns. We visit every square once.\n\n* Space complexity: $$O(R*C)$$, the space used by `seen` to keep track of visited squares and the space used by `stack`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n    def dfs(i: int, j: int) -> int:\n      if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]):\n        return 0\n      if grid[i][j] != 1:\n        return 0\n\n      grid[i][j] = 2\n\n      return 1 + dfs(i + 1, j) + dfs(i - 1, j) + dfs(i, j + 1) + dfs(i, j - 1)\n\n    return max(dfs(i, j) for i in range(len(grid)) for j in range(len(grid[0])))",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxAreaOfIsland(int[][] grid) {\n    int ans = 0;\n\n    for (int i = 0; i < grid.length; ++i)\n      for (int j = 0; j < grid[0].length; ++j)\n        ans = Math.max(ans, dfs(grid, i, j));\n\n    return ans;\n  }\n\n  private int dfs(int[][] grid, int i, int j) {\n    if (i < 0 || i == grid.length || j < 0 || j == grid[0].length)\n      return 0;\n    if (grid[i][j] != 1)\n      return 0;\n\n    grid[i][j] = 2;\n\n    return 1 + dfs(grid, i + 1, j) + dfs(grid, i - 1, j)\n             + dfs(grid, i, j + 1) + dfs(grid, i, j - 1);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxAreaOfIsland(vector<vector<int>>& grid) {\n    int ans = 0;\n\n    for (int i = 0; i < grid.size(); ++i)\n      for (int j = 0; j < grid[0].size(); ++j)\n        ans = max(ans, dfs(grid, i, j));\n\n    return ans;\n  }\n\n private:\n  int dfs(vector<vector<int>>& grid, int i, int j) {\n    if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())\n      return 0;\n    if (grid[i][j] != 1)\n      return 0;\n\n    grid[i][j] = 2;\n\n    return 1 + dfs(grid, i + 1, j) + dfs(grid, i - 1, j)\n             + dfs(grid, i, j + 1) + dfs(grid, i, j - 1);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/695.html",
    "category": "Algorithms",
    "acceptance_rate": 73.07192621185467,
    "topics": [
      "Array",
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Matrix"
    ],
    "hints": [],
    "likes": 10280,
    "dislikes": 214,
    "similar_questions": "[{\"title\": \"Number of Islands\", \"titleSlug\": \"number-of-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Battleships in a Board\", \"titleSlug\": \"battleships-in-a-board\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Island Perimeter\", \"titleSlug\": \"island-perimeter\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Largest Submatrix With Rearrangements\", \"titleSlug\": \"largest-submatrix-with-rearrangements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Detonate the Maximum Bombs\", \"titleSlug\": \"detonate-the-maximum-bombs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Fish in a Grid\", \"titleSlug\": \"maximum-number-of-fish-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 1051769, \"totalSubmissionRaw\": 1439362, \"acRate\": \"73.1%\"}",
    "title_pt": "Máxima Área de uma Ilha",
    "description_pt": "<p>Você recebe uma matriz binária <code>m x n</code> <code>grid</code>. Uma ilha é um grupo de <code>1</code>&#39;s (representando terra) conectados <strong>em 4 direções</strong> (horizontal ou vertical). Você pode assumir que todas as quatro bordas da matriz são cercadas por água.</p>\n\n<p>A <strong>área</strong> de uma ilha é o número de células com valor <code>1</code> na ilha.</p>\n\n<p>Retorne <em>a área <strong>máxima</strong> de uma ilha em </em><code>grid</code>. Se não houver ilha, retorne <code>0</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg\" style=\"width: 500px; height: 310px;\" />\n<pre>\n<strong>Entrada:</strong> grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> A resposta não é 11, porque a ilha deve estar conectada em 4 direções.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> grid = [[0,0,0,0,0,0,0,0]]\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>m == grid.length</code></li>\n\t<li><code>n == grid[i].length</code></li>\n\t<li><code>1 &lt;= m, n &lt;= 50</code></li>\n\t<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "696",
    "paidOnly": false,
    "title": "Count Binary Substrings",
    "titleSlug": "count-binary-substrings",
    "url": "https://leetcode.com/problems/count-binary-substrings",
    "description_url": "https://leetcode.com/problems/count-binary-substrings/description/",
    "description": "<p>Given a binary string <code>s</code>, return the number of non-empty substrings that have the same number of <code>0</code>&#39;s and <code>1</code>&#39;s, and all the <code>0</code>&#39;s and all the <code>1</code>&#39;s in these substrings are grouped consecutively.</p>\n\n<p>Substrings that occur multiple times are counted the number of times they occur.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;00110011&quot;\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> There are 6 substrings that have equal number of consecutive 1&#39;s and 0&#39;s: &quot;0011&quot;, &quot;01&quot;, &quot;1100&quot;, &quot;10&quot;, &quot;0011&quot;, and &quot;01&quot;.\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, &quot;00110011&quot; is not a valid substring because all the 0&#39;s (and 1&#39;s) are not grouped together.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;10101&quot;\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> There are 4 substrings: &quot;10&quot;, &quot;01&quot;, &quot;10&quot;, &quot;01&quot; that have equal number of consecutive 1&#39;s and 0&#39;s.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/count-binary-substrings/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Group By Character [Accepted]\n\n**Intuition**\n\nWe can convert the string `s` into an array `groups` that represents the length of same-character contiguous blocks within the string. For example, if `s = \"110001111000000\"`, then `groups = [2, 3, 4, 6]`.\n\nFor every binary string of the form `'0' * k + '1' * k` or `'1' * k + '0' * k`, the middle of this string must occur between two groups.  \n\nLet's try to count the number of valid binary strings between `groups[i]` and `groups[i+1]`. If we have `groups[i] = 2, groups[i+1] = 3`, then it represents either `\"00111\"` or `\"11000\"`. We clearly can make `min(groups[i], groups[i+1])` valid binary strings within this string.  Because the binary digits to the left or right of this string must change at the boundary, our answer can never be larger.\n\n**Algorithm**\n\nLet's create `groups` as defined above. The first element of `s` belongs in its own group. From then on, each element either doesn't match the previous element, so that it starts a new group of size 1, or it does match, so that the size of the most recent group increases by 1.\n\nAfterward, we will take the sum of `min(groups[i-1], groups[i])`.\n\n**Python**\n```python\nclass Solution(object):\n    def countBinarySubstrings(self, s):\n        groups = [1]\n        for i in xrange(1, len(s)):\n            if s[i-1] != s[i]:\n                groups.append(1)\n            else:\n                groups[-1] += 1\n\n        ans = 0\n        for i in xrange(1, len(groups)):\n            ans += min(groups[i-1], groups[i])\n        return ans\n```\n\n*Alternate Implentation*\n```python\nclass Solution(object):\n    def countBinarySubstrings(self, s):\n        groups = [len(list(v)) for _, v in itertools.groupby(s)]\n        return sum(min(a, b) for a, b in zip(groups, groups[1:]))\n```\n\n**Java**\n```java\nclass Solution {\n    public int countBinarySubstrings(String s) {\n        int[] groups = new int[s.length()];\n        int t = 0;\n        groups[0] = 1;\n        for (int i = 1; i < s.length(); i++) {\n            if (s.charAt(i-1) != s.charAt(i)) {\n                groups[++t] = 1;\n            } else {\n                groups[t]++;\n            }\n        }\n\n        int ans = 0;\n        for (int i = 1; i <= t; i++) {\n            ans += Math.min(groups[i-1], groups[i]);\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `s`. Every loop is through $$O(N)$$ items with $$O(1)$$ work inside the for-block.\n\n* Space Complexity: $$O(N)$$, the space used by `groups`.\n\n---\n### Approach #2: Linear Scan [Accepted]\n\n**Intuition and Algorithm**\n\nWe can amend our *Approach #1* to calculate the answer on the fly. Instead of storing `groups`, we will remember only `prev = groups[-2]` and `cur = groups[-1]`.  Then, the answer is the sum of `min(prev, cur)` over each different final `(prev, cur)` we see.\n\n**Python**\n```python\nclass Solution(object):\n    def countBinarySubstrings(self, s):\n        ans, prev, cur = 0, 0, 1\n        for i in xrange(1, len(s)):\n            if s[i-1] != s[i]:\n                ans += min(prev, cur)\n                prev, cur = cur, 1\n            else:\n                cur += 1\n\n        return ans + min(prev, cur)\n```\n\n**Java**\n```java\nclass Solution {\n    public int countBinarySubstrings(String s) {\n        int ans = 0, prev = 0, cur = 1;\n        for (int i = 1; i < s.length(); i++) {\n            if (s.charAt(i-1) != s.charAt(i)) {\n                ans += Math.min(prev, cur);\n                prev = cur;\n                cur = 1;\n            } else {\n                cur++;\n            }\n        }\n        return ans + Math.min(prev, cur);\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `s`. Every loop is through $$O(N)$$ items with $$O(1)$$ work inside the for-block.\n\n* Space Complexity: $$O(1)$$, the space used by `prev`, `cur`, and `ans`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def countBinarySubstrings(self, s: str) -> int:\n    ans = 0\n    prevCount = 0\n    equals = 1\n\n    for i in range(len(s) - 1):\n      if s[i] == s[i + 1]:\n        equals += 1\n      else:\n        ans += min(prevCount, equals)\n        prevCount = equals\n        equals = 1\n\n    return ans + min(prevCount, equals)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int countBinarySubstrings(String s) {\n    int ans = 0;\n    int prevEquals = 0;\n    int currEquals = 1;\n\n    for (int i = 0; i + 1 < s.length(); ++i)\n      if (s.charAt(i) == s.charAt(i + 1))\n        ++currEquals;\n      else {\n        ans += Math.min(prevEquals, currEquals);\n        prevEquals = currEquals;\n        currEquals = 1;\n      }\n\n    return ans + Math.min(prevEquals, currEquals);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int countBinarySubstrings(string s) {\n    int ans = 0;\n    int prevEquals = 0;\n    int currEquals = 1;\n\n    for (int i = 0; i + 1 < s.length(); ++i)\n      if (s[i] == s[i + 1])\n        ++currEquals;\n      else {\n        ans += min(prevEquals, currEquals);\n        prevEquals = currEquals;\n        currEquals = 1;\n      }\n\n    return ans + min(prevEquals, currEquals);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/696.html",
    "category": "Algorithms",
    "acceptance_rate": 65.8632424857723,
    "topics": [
      "Two Pointers",
      "String"
    ],
    "hints": [
      "How many valid binary substrings exist in \"000111\", and how many in \"11100\"?  What about \"00011100\"?"
    ],
    "likes": 4083,
    "dislikes": 895,
    "similar_questions": "[{\"title\": \"Encode and Decode Strings\", \"titleSlug\": \"encode-and-decode-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Substrings With Fixed Ratio\", \"titleSlug\": \"number-of-substrings-with-fixed-ratio\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Substrings With Dominant Ones\", \"titleSlug\": \"count-the-number-of-substrings-with-dominant-ones\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"230.3K\", \"totalSubmission\": \"349.7K\", \"totalAcceptedRaw\": 230304, \"totalSubmissionRaw\": 349670, \"acRate\": \"65.9%\"}",
    "title_pt": "Contar Substrings Binárias",
    "description_pt": "<p>Dada uma string binária <code>s</code>, retorne o número de substrings não vazias que tenham a mesma quantidade de <code>0</code>&#39;s e <code>1</code>&#39;s, e em que todos os <code>0</code>&#39;s e todos os <code>1</code>&#39;s nessas substrings estejam agrupados consecutivamente.</p>\n\n<p>Substrings que ocorrem várias vezes são contadas o número de vezes em que ocorrem.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;00110011&quot;\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> Existem 6 substrings que têm igual número de 1&#39;s e 0&#39;s consecutivos: &quot;0011&quot;, &quot;01&quot;, &quot;1100&quot;, &quot;10&quot;, &quot;0011&quot;, e &quot;01&quot;.\nObserve que algumas dessas substrings se repetem e são contadas o número de vezes em que ocorrem.\nAlém disso, &quot;00110011&quot; não é uma substring válida porque todos os 0&#39;s (e 1&#39;s) não estão agrupados juntos.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;10101&quot;\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> Existem 4 substrings: &quot;10&quot;, &quot;01&quot;, &quot;10&quot;, &quot;01&quot; que têm igual número de 1&#39;s e 0&#39;s consecutivos.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>\n\t<li><code>s[i]</code> é ou <code>&#39;0&#39;</code> ou <code>&#39;1&#39;</code>.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Quantas substrings binárias válidas existem em \"000111\", e quantas em \"11100\"? E em \"00011100\"?"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "697",
    "paidOnly": false,
    "title": "Degree of an Array",
    "titleSlug": "degree-of-an-array",
    "url": "https://leetcode.com/problems/degree-of-an-array",
    "description_url": "https://leetcode.com/problems/degree-of-an-array/description/",
    "description": "<p>Given a non-empty array of non-negative integers <code>nums</code>, the <b>degree</b> of this array is defined as the maximum frequency of any one of its elements.</p>\n\n<p>Your task is to find the smallest possible length of a (contiguous) subarray of <code>nums</code>, that has the same degree as <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,2,3,1]\n<strong>Output:</strong> 2\n<strong>Explanation:</strong> \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,2,3,1,4,2]\n<strong>Output:</strong> 6\n<strong>Explanation:</strong> \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>nums.length</code> will be between 1 and 50,000.</li>\n\t<li><code>nums[i]</code> will be an integer between 0 and 49,999.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/degree-of-an-array/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Left and Right Index [Accepted]\n\n**Intuition and Algorithm**\n\nAn array that has degree `d`, must have some element `x` occur `d` times.  If some subarray has the same degree, then some element `x` (that occurred `d` times), still occurs `d` times. The shortest such subarray would be from the first occurrence of `x` until the last occurrence.\n\nFor each element in the given array, let's know `left`, the index of its first occurrence; and `right`, the index of its last occurrence. For example, with `nums = [1,2,3,2,5]` we have `left[2] = 1` and `right[2] = 3`.\n\nThen, for each element `x` that occurs the maximum number of times, `right[x] - left[x] + 1` will be our candidate answer, and we'll take the minimum of those candidates.\n\n**Python**\n```python\nclass Solution(object):\n    def findShortestSubArray(self, nums):\n        left, right, count = {}, {}, {}\n        for i, x in enumerate(nums):\n            if x not in left:\n                left[x] = i\n            right[x] = i\n            count[x] = count.get(x, 0) + 1\n\n        ans = len(nums)\n        degree = max(count.values())\n        for x in count:\n            if count[x] == degree:\n                ans = min(ans, right[x] - left[x] + 1)\n\n        return ans\n```\n\n**Java**\n```java\nclass Solution {\n    public int findShortestSubArray(int[] nums) {\n        Map<Integer, Integer> left = new HashMap(),\n            right = new HashMap(), count = new HashMap();\n\n        for (int i = 0; i < nums.length; i++) {\n            int x = nums[i];\n            if (left.get(x) == null) {\n                left.put(x, I);\n            }\n            right.put(x, i);\n            count.put(x, count.getOrDefault(x, 0) + 1);\n        }\n\n        int ans = nums.length;\n        int degree = Collections.max(count.values());\n        for (int x: count.keySet()) {\n            if (count.get(x) == degree) {\n                ans = Math.min(ans, right.get(x) - left.get(x) + 1);\n            }\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `nums`. Every loop is through $$O(N)$$ items with $$O(1)$$ work inside the for-block.\n\n* Space Complexity: $$O(N)$$, the space used by `left`, `right`, and `count`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findShortestSubArray(self, nums: List[int]) -> int:\n    ans = 0\n    degree = 0\n    debut = {}\n    count = Counter()\n\n    for i, num in enumerate(nums):\n      debut.setdefault(num, i)\n      count[num] += 1\n      if count[num] > degree:\n        degree = count[num]\n        ans = i - debut[num] + 1\n      elif count[num] == degree:\n        ans = min(ans, i - debut[num] + 1)\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findShortestSubArray(int[] nums) {\n    int ans = 0;\n    int degree = 0;\n    Map<Integer, Integer> debut = new HashMap<>();\n    Map<Integer, Integer> count = new HashMap<>();\n\n    for (int i = 0; i < nums.length; ++i) {\n      final int num = nums[i];\n      debut.putIfAbsent(num, i);\n      count.put(num, count.getOrDefault(num, 0) + 1);\n      if (count.get(num) > degree) {\n        degree = count.get(num);\n        ans = i - debut.get(num) + 1;\n      } else if (count.get(num) == degree) {\n        ans = Math.min(ans, i - debut.get(num) + 1);\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findShortestSubArray(vector<int>& nums) {\n    int ans = 0;\n    int degree = 0;\n    unordered_map<int, int> debut;\n    unordered_map<int, int> count;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      const int num = nums[i];\n      if (!debut.count(num))\n        debut[num] = i;\n      if (++count[num] > degree) {\n        degree = count[num];\n        ans = i - debut[num] + 1;\n      } else if (count[num] == degree) {\n        ans = min(ans, i - debut[num] + 1);\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/697.html",
    "category": "Algorithms",
    "acceptance_rate": 57.307413046024124,
    "topics": [
      "Array",
      "Hash Table"
    ],
    "hints": [
      "Say 5 is the only element that occurs the most number of times - for example, nums = [1, 5, 2, 3, 5, 4, 5, 6].  What is the answer?"
    ],
    "likes": 3136,
    "dislikes": 1783,
    "similar_questions": "[{\"title\": \"Maximum Subarray\", \"titleSlug\": \"maximum-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"244.7K\", \"totalSubmission\": \"426.9K\", \"totalAcceptedRaw\": 244671, \"totalSubmissionRaw\": 426943, \"acRate\": \"57.3%\"}",
    "title_pt": "Grau de um Array",
    "description_pt": "<p>Dado um array não vazio de inteiros não negativos <code>nums</code>, o <b>grau</b> desse array é definido como a frequência máxima de qualquer um de seus elementos.</p>\n\n<p>Sua tarefa é encontrar o menor comprimento possível de um subarray (contíguo) de <code>nums</code> que tenha o mesmo grau que <code>nums</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,2,3,1]\n<strong>Saída:</strong> 2\n<strong>Explicação:</strong> \nO array de entrada tem grau 2 porque tanto o elemento 1 quanto o elemento 2 aparecem duas vezes.\nDos subarrays que têm o mesmo grau:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nO menor comprimento é 2. Portanto, retorne 2.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,2,3,1,4,2]\n<strong>Saída:</strong> 6\n<strong>Explicação:</strong> \nO grau é 3 porque o elemento 2 é repetido 3 vezes.\nEntão [2,2,3,1,4,2] é o menor subarray, portanto retornando 6.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>nums.length</code> estará entre 1 e 50,000.</li>\n\t<li><code>nums[i]</code> será um inteiro entre 0 e 49,999.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Suponha que 5 seja o único elemento que ocorre o maior número de vezes - por exemplo, nums = [1, 5, 2, 3, 5, 4, 5, 6]. Qual é a resposta?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "698",
    "paidOnly": false,
    "title": "Partition to K Equal Sum Subsets",
    "titleSlug": "partition-to-k-equal-sum-subsets",
    "url": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets",
    "description_url": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/",
    "description": "<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if it is possible to divide this array into <code>k</code> non-empty subsets whose sums are all equal.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [4,3,2,3,5,2,1], k = 4\n<strong>Output:</strong> true\n<strong>Explanation:</strong> It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3,4], k = 3\n<strong>Output:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>The frequency of each element is in the range <code>[1, 4]</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean canPartitionKSubsets(int[] nums, int k) {\n    final int sum = Arrays.stream(nums).sum();\n    if (sum % k != 0)\n      return false;\n\n    final int t = sum / k; // Each subset's target sum\n    boolean[] seen = new boolean[nums.length];\n    return dfs(nums, 0, k, t, t, seen);\n  }\n\n  private boolean dfs(int[] nums, int s, int k, int target, int subsetTargetSum, boolean[] seen) {\n    if (k == 0)\n      return true;\n    if (target < 0)\n      return false;\n    if (target == 0)\n      return dfs(nums, 0, k - 1, subsetTargetSum, subsetTargetSum, seen);\n\n    for (int i = s; i < nums.length; ++i) {\n      if (seen[i])\n        continue;\n      seen[i] = true;\n      if (dfs(nums, i + 1, k, target - nums[i], subsetTargetSum, seen))\n        return true;\n      seen[i] = false;\n    }\n\n    return false;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool canPartitionKSubsets(vector<int>& nums, int k) {\n    const int sum = accumulate(begin(nums), end(nums), 0);\n    if (sum % k != 0)\n      return false;\n\n    const int t = sum / k;  // Each subset's target sum\n    return dfs(nums, 0, k, t, t, vector<bool>(nums.size()));\n  }\n\n private:\n  bool dfs(const vector<int>& nums, int s, int k, int target,\n           const int subsetTargetSum, vector<bool>&& seen) {\n    if (k == 0)\n      return true;\n    if (target < 0)\n      return false;\n    if (target == 0)\n      return dfs(nums, 0, k - 1, subsetTargetSum, subsetTargetSum, move(seen));\n\n    for (int i = s; i < nums.size(); ++i) {\n      if (seen[i])\n        continue;\n      seen[i] = true;\n      if (dfs(nums, i + 1, k, target - nums[i], subsetTargetSum, move(seen)))\n        return true;\n      seen[i] = false;\n    }\n\n    return false;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/698.html",
    "category": "Algorithms",
    "acceptance_rate": 38.094780207772686,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Backtracking",
      "Bit Manipulation",
      "Memoization",
      "Bitmask"
    ],
    "hints": [
      "We can figure out what target each subset must sum to.  Then, let's recursively search, where at each call to our function, we choose which of k subsets the next value will join."
    ],
    "likes": 7342,
    "dislikes": 530,
    "similar_questions": "[{\"title\": \"Partition Equal Subset Sum\", \"titleSlug\": \"partition-equal-subset-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Fair Distribution of Cookies\", \"titleSlug\": \"fair-distribution-of-cookies\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Ways to Partition an Array\", \"titleSlug\": \"maximum-number-of-ways-to-partition-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Rows Covered by Columns\", \"titleSlug\": \"maximum-rows-covered-by-columns\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"305.1K\", \"totalSubmission\": \"800.8K\", \"totalAcceptedRaw\": 305050, \"totalSubmissionRaw\": 800770, \"acRate\": \"38.1%\"}",
    "title_pt": "Particionamento em k Subconjuntos com Soma Igual",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <code>true</code> se for possível dividir este array em <code>k</code> subconjuntos não vazios cujas somas sejam todas iguais.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [4,3,2,3,5,2,1], k = 4\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> É possível dividí-lo em 4 subconjuntos (5), (1, 4), (2,3), (2,3) com somas iguais.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3,4], k = 3\n<strong>Saída:</strong> false\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= k &lt;= nums.length &lt;= 16</code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li>A frequência de cada elemento está no intervalo <code>[1, 4]</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Podemos descobrir qual deve ser a soma-alvo de cada subconjunto. Então, vamos fazer uma busca recursiva, em que, em cada chamada da nossa função, escolhemos a qual dos k subconjuntos o próximo valor irá se juntar."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "699",
    "paidOnly": false,
    "title": "Falling Squares",
    "titleSlug": "falling-squares",
    "url": "https://leetcode.com/problems/falling-squares",
    "description_url": "https://leetcode.com/problems/falling-squares/description/",
    "description": "<p>There are several squares being dropped onto the X-axis of a 2D plane.</p>\n\n<p>You are given a 2D integer array <code>positions</code> where <code>positions[i] = [left<sub>i</sub>, sideLength<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> square with a side length of <code>sideLength<sub>i</sub></code> that is dropped with its left edge aligned with X-coordinate <code>left<sub>i</sub></code>.</p>\n\n<p>Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands <strong>on the top side of another square</strong> or <strong>on the X-axis</strong>. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.</p>\n\n<p>After each square is dropped, you must record the <strong>height of the current tallest stack of squares</strong>.</p>\n\n<p>Return <em>an integer array </em><code>ans</code><em> where </em><code>ans[i]</code><em> represents the height described above after dropping the </em><code>i<sup>th</sup></code><em> square</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg\" style=\"width: 500px; height: 505px;\" />\n<pre>\n<strong>Input:</strong> positions = [[1,2],[2,3],[6,1]]\n<strong>Output:</strong> [2,5,5]\n<strong>Explanation:</strong>\nAfter the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> positions = [[100,100],[200,100]]\n<strong>Output:</strong> [100,100]\n<strong>Explanation:</strong>\nAfter the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= positions.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= left<sub>i</sub> &lt;= 10<sup>8</sup></code></li>\n\t<li><code>1 &lt;= sideLength<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/falling-squares/solutions/",
    "solution": "[TOC]\n\n### Approach Framework\n\n**Intuition**\n\nIntuitively, there are two operations: `update`, which updates our notion of the board (number line) after dropping a square; and `query`, which finds the largest height in the current board on some interval. We will work on implementing these operations.\n\n**Coordinate Compression**\n\nIn the below approaches, since there are only up to `2 * len(positions)` critical points, namely the left and right edges of each square, we can use a technique called *coordinate compression* to map these critical points to adjacent integers, as shown in the code snippets below.  \n\nFor brevity, these snippets are omitted from the remaining solutions.\n\n<iframe src=\"https://leetcode.com/playground/6Bho7TMC/shared\" frameBorder=\"0\" width=\"100%\" height=\"276\" name=\"6Bho7TMC\"></iframe>\n\n---\n### Approach 1: Offline Propagation\n\n**Intuition**\n\nInstead of asking the question \"What squares affect this query?\", let's ask the question \"What queries are affected by this square?\"\n\n**Algorithm**\n\nLet `qans[i]` be the maximum height of the interval specified by `positions[i]`. In the end, we'll return a running max of `qans`.\n\nFor each square `positions[i]`, the maximum height will get higher by the size of the square we drop. Then, for any future squares that intersect the interval `[left, right)` (where `left = positions[i][0], right = positions[i][0] + positions[i][1]`), we'll update the maximum height of that interval.\n\n<iframe src=\"https://leetcode.com/playground/VgRrtWC6/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VgRrtWC6\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N^2)$$, where $$N$$ is the length of `positions`. We use two for-loops, each of complexity $$O(N)$$.\n\n* Space Complexity: $$O(N)$$, the space used by `qans` and `ans`.\n<br>\n<br>\n\n---\n### Approach 2: Brute Force with Coordinate Compression\n\n**Intuition and Algorithm**\n\nLet `N = len(positions)`. After mapping the board to a board of length at most $$2* N \\leq 2000$$, we can brute force the answer by simulating each square's drop directly.\n\nOur answer is either the current answer or the height of the square that was just dropped, and we'll update it appropriately.\n\n<iframe src=\"https://leetcode.com/playground/cwsSAUWX/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"cwsSAUWX\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N^2)$$, where $$N$$ is the length of `positions`. We use two for-loops, each of complexity $$O(N)$$ (because of coordinate compression.)\n\n* Space Complexity: $$O(N)$$, the space used by `heights`.\n<br>\n<br>\n\n---\n### Approach 3: Block (Square Root) Decomposition\n\n**Intuition**\n\nWhenever we perform operations (like `update` and `query`) on some interval in a domain, we could segment that domain with size $$W$$ into blocks of size $$\\sqrt{W}$$.  \n\nThen, instead of a typical brute force where we update our array `heights` representing the board, we will also hold another array `blocks`, where `blocks[i]` represents the $$B = \\lfloor \\sqrt{W} \\rfloor$$ elements `heights[B*i], heights[B*i + 1], ..., heights[B*i + B-1]`.  This allows us to write to the array in $$O(B)$$ operations.\n\n**Algorithm**\n\nLet's get into the details.  We actually need another array, `blocks_read`. When we update some element `i` in block `b = i / B`, we'll also update `blocks_read[b]`. If later we want to read the entire block, we can read from here (and stuff written to the whole block in `blocks[b]`.)\n\nWhen we write to a block, we'll write in `blocks[b]`. Later, when we want to read from an element `i` in block `b = i / B`, we'll read from `heights[i]` and `blocks[b]`.\n\nOur process for managing `query` and `update` will be similar.  While `left` isn't a multiple of `B`, we'll proceed with a brute-force-like approach, and similarly for `right`. In the end, `[left, right+1)` will represent a series of contiguous blocks: the interval will have a length that is a multiple of `B`, and `left` will also be a multiple of `B`.\n\n<iframe src=\"https://leetcode.com/playground/cRHYBAtW/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"cRHYBAtW\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N\\sqrt{N})$$, where $$N$$ is the length of `positions`. Each `query` and `update` has complexity $$O(\\sqrt{N})$$.\n\n* Space Complexity: $$O(N)$$, the space used by `heights`.\n<br>\n<br>\n\n---\n### Approach 4: Segment Tree with Lazy Propagation\n\n**Intuition**\n\nIf we were familiar with the idea of a segment tree (which supports queries and updates on intervals), we could immediately crack the problem.  \n\n**Algorithm**\n\nSegment trees work by breaking intervals into a disjoint sum of component intervals, whose number is at most `log(width)`. The motivation is that when we change an element, we only need to change `log(width)` of many intervals that aggregate on an interval containing that element.\n\nWhen we want to update an interval all at once, we need to use *lazy propagation* to ensure good run-time complexity. This topic is covered in more depth [here](https://leetcode.com/articles/a-recursive-approach-to-segment-trees-range-sum-queries-lazy-propagation/).\n\nWith such an implementation in hand, the problem falls out immediately.\n\n<iframe src=\"https://leetcode.com/playground/QL2PYqb9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"QL2PYqb9\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N \\log N)$$, where $$N$$ is the length of `positions`. This is the run-time complexity of using a segment tree.\n\n* Space Complexity: $$O(N)$$, the space used by our tree.\n<br>\n<br>",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<int> fallingSquares(vector<vector<int>>& positions) {\n    vector<int> ans;\n    map<pair<int, int>, int> xsToHeight;  // {{xStart, xEnd}, height}\n    int maxHeight = INT_MIN;\n\n    for (const vector<int>& p : positions) {\n      const int left = p[0];\n      const int sideLength = p[1];\n      const int right = left + sideLength;\n      // First range intersect with [left, right)\n      auto it = xsToHeight.upper_bound({left, right});\n      if (it != begin(xsToHeight) && (--it)->first.second <= left)\n        ++it;\n      int maxHeightInRange = 0;\n      vector<tuple<int, int, int>> ranges;\n      while (it != end(xsToHeight) && it->first.first < right) {\n        const int l = it->first.first;\n        const int r = it->first.second;\n        const int h = it->second;\n        if (l < left)\n          ranges.emplace_back(l, left, h);\n        if (right < r)\n          ranges.emplace_back(right, r, h);\n        maxHeightInRange = max(maxHeightInRange, h);\n        it = xsToHeight.erase(it);\n      }\n      const int newHeight = maxHeightInRange + sideLength;\n      xsToHeight[{left, right}] = newHeight;\n      for (const auto& [l, r, h] : ranges)\n        xsToHeight[{l, r}] = h;\n      maxHeight = max(maxHeight, newHeight);\n      ans.push_back(maxHeight);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/699.html",
    "category": "Algorithms",
    "acceptance_rate": 46.15985842796048,
    "topics": [
      "Array",
      "Segment Tree",
      "Ordered Set"
    ],
    "hints": [
      "If positions = [[10, 20], [20, 30]], this is the same as [[1, 2], [2, 3]].  Currently, the values of positions are very large.  Can you generalize this approach so as to make the values in positions manageable?"
    ],
    "likes": 652,
    "dislikes": 75,
    "similar_questions": "[{\"title\": \"The Skyline Problem\", \"titleSlug\": \"the-skyline-problem\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"31.3K\", \"totalSubmission\": \"67.8K\", \"totalAcceptedRaw\": 31301, \"totalSubmissionRaw\": 67810, \"acRate\": \"46.2%\"}",
    "title_pt": "Quadrados Caindo",
    "description_pt": "<p>Há vários quadrados sendo soltos sobre o eixo X de um plano 2D.</p>\n\n<p>Você recebe um array inteiro 2D <code>positions</code> em que <code>positions[i] = [left<sub>i</sub>, sideLength<sub>i</sub>]</code> representa o <code>i<sup>th</sup></code> quadrado com comprimento de lado <code>sideLength<sub>i</sub></code> que é solto com sua borda esquerda alinhada à coordenada X <code>left<sub>i</sub></code>.</p>\n\n<p>Cada quadrado é solto um de cada vez a partir de uma altura acima de quaisquer quadrados já aterrissados. Ele então cai para baixo (direção Y negativa) até que ou aterrisse <strong>no lado superior de outro quadrado</strong> ou <strong>no eixo X</strong>. Um quadrado que apenas encoste nas bordas esquerda/direita de outro quadrado não conta como aterrissar sobre ele. Uma vez que aterrissa, ele fica fixo no lugar e não pode ser movido.</p>\n\n<p>Após a queda de cada quadrado, você deve registrar a <strong>altura da pilha mais alta de quadrados no momento</strong>.</p>\n\n<p>Retorne <em>um array inteiro </em><code>ans</code><em> em que </em><code>ans[i]</code><em> representa a altura descrita acima após a queda do </em><code>i<sup>th</sup></code><em> quadrado</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/04/28/fallingsq1-plane.jpg\" style=\"width: 500px; height: 505px;\" />\n<pre>\n<strong>Entrada:</strong> positions = [[1,2],[2,3],[6,1]]\n<strong>Saída:</strong> [2,5,5]\n<strong>Explicação:</strong>\nApós a primeira queda, a pilha mais alta é o quadrado 1 com altura 2.\nApós a segunda queda, a pilha mais alta é os quadrados 1 e 2 com altura 5.\nApós a terceira queda, a pilha mais alta ainda é os quadrados 1 e 2 com altura 5.\nAssim, retornamos uma resposta de [2, 5, 5].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> positions = [[100,100],[200,100]]\n<strong>Saída:</strong> [100,100]\n<strong>Explicação:</strong>\nApós a primeira queda, a pilha mais alta é o quadrado 1 com altura 100.\nApós a segunda queda, a pilha mais alta é ou o quadrado 1 ou o quadrado 2, ambos com alturas de 100.\nAssim, retornamos uma resposta de [100, 100].\nObserve que o quadrado 2 apenas encosta na borda direita do quadrado 1, o que não conta como aterrissar sobre ele.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= positions.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= left<sub>i</sub> &lt;= 10<sup>8</sup></code></li>\n\t<li><code>1 &lt;= sideLength<sub>i</sub> &lt;= 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Se <code>positions = [[10, 20], [20, 30]]</code>, isso é o mesmo que <code>[[1, 2], [2, 3]]</code>. Atualmente, os valores de <code>positions</code> são muito grandes. Você consegue generalizar essa abordagem para tornar os valores em <code>positions</code> manejáveis?"
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "700",
    "paidOnly": false,
    "title": "Search in a Binary Search Tree",
    "titleSlug": "search-in-a-binary-search-tree",
    "url": "https://leetcode.com/problems/search-in-a-binary-search-tree",
    "description_url": "https://leetcode.com/problems/search-in-a-binary-search-tree/description/",
    "description": "<p>You are given the <code>root</code> of a binary search tree (BST) and an integer <code>val</code>.</p>\n\n<p>Find the node in the BST that the node&#39;s value equals <code>val</code> and return the subtree rooted with that node. If such a node does not exist, return <code>null</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,7,1,3], val = 2\n<strong>Output:</strong> [2,1,3]\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,7,1,3], val = 5\n<strong>Output:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the tree is in the range <code>[1, 5000]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>7</sup></code></li>\n\t<li><code>root</code> is a binary search tree.</li>\n\t<li><code>1 &lt;= val &lt;= 10<sup>7</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/search-in-a-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n    if not root:\n      return None\n    if root.val == val:\n      return root\n    if root.val > val:\n      return self.searchBST(root.left, val)\n    return self.searchBST(root.right, val)",
    "solution_code_java": "\t\t\t\n\npublic class Solution {\n  public TreeNode searchBST(TreeNode root, int val) {\n    if (root == null)\n      return null;\n    if (root.val == val)\n      return root;\n    if (root.val > val)\n      return searchBST(root.left, val);\n    return searchBST(root.right, val);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* searchBST(TreeNode* root, int val) {\n    if (root == nullptr)\n      return nullptr;\n    if (root->val == val)\n      return root;\n    if (root->val > val)\n      return searchBST(root->left, val);\n    return searchBST(root->right, val);\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/700.html",
    "category": "Algorithms",
    "acceptance_rate": 81.56741688488658,
    "topics": [
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 6234,
    "dislikes": 203,
    "similar_questions": "[{\"title\": \"Closest Binary Search Tree Value\", \"titleSlug\": \"closest-binary-search-tree-value\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Insert into a Binary Search Tree\", \"titleSlug\": \"insert-into-a-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Closest Nodes Queries in a Binary Search Tree\", \"titleSlug\": \"closest-nodes-queries-in-a-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 1139098, \"totalSubmissionRaw\": 1396513, \"acRate\": \"81.6%\"}",
    "title_pt": "Buscar em uma Árvore Binária de Busca",
    "description_pt": "<p>Você recebe a <code>root</code> de uma árvore binária de busca (BST) e um inteiro <code>val</code>.</p>\n\n<p>Encontre o nó na BST cujo valor do nó seja igual a <code>val</code> e retorne a subárvore enraizada nesse nó. Se tal nó não existir, retorne <code>null</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,7,1,3], val = 2\n<strong>Saída:</strong> [2,1,3]\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg\" style=\"width: 422px; height: 302px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,7,1,3], val = 5\n<strong>Saída:</strong> []\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na árvore está no intervalo <code>[1, 5000]</code>.</li>\n\t<li><code>1 &lt;= Node.val &lt;= 10<sup>7</sup></code></li>\n\t<li><code>root</code> é uma árvore binária de busca.</li>\n\t<li><code>1 &lt;= val &lt;= 10<sup>7</sup></code></li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "701",
    "paidOnly": false,
    "title": "Insert into a Binary Search Tree",
    "titleSlug": "insert-into-a-binary-search-tree",
    "url": "https://leetcode.com/problems/insert-into-a-binary-search-tree",
    "description_url": "https://leetcode.com/problems/insert-into-a-binary-search-tree/description/",
    "description": "<p>You are given the <code>root</code> node of a binary search tree (BST) and a <code>value</code> to insert into the tree. Return <em>the root node of the BST after the insertion</em>. It is <strong>guaranteed</strong> that the new value does not exist in the original BST.</p>\n\n<p><strong>Notice</strong>&nbsp;that there may exist&nbsp;multiple valid ways for the&nbsp;insertion, as long as the tree remains a BST after insertion. You can return <strong>any of them</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg\" style=\"width: 752px; height: 221px;\" />\n<pre>\n<strong>Input:</strong> root = [4,2,7,1,3], val = 5\n<strong>Output:</strong> [4,2,7,1,3,5]\n<strong>Explanation:</strong> Another accepted tree is:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/bst.jpg\" style=\"width: 352px; height: 301px;\" />\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [40,20,60,10,30,50,70], val = 25\n<strong>Output:</strong> [40,20,60,10,30,50,70,null,null,25]\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\n<strong>Output:</strong> [4,2,7,1,3,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in&nbsp;the tree will be in the range <code>[0,&nbsp;10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>8</sup> &lt;= Node.val &lt;= 10<sup>8</sup></code></li>\n\t<li>All the values <code>Node.val</code> are <strong>unique</strong>.</li>\n\t<li><code>-10<sup>8</sup> &lt;= val &lt;= 10<sup>8</sup></code></li>\n\t<li>It&#39;s <strong>guaranteed</strong> that <code>val</code> does not exist in the original BST.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/insert-into-a-binary-search-tree/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n    if not root:\n      return TreeNode(val)\n    if root.val > val:\n      root.left = self.insertIntoBST(root.left, val)\n    else:\n      root.right = self.insertIntoBST(root.right, val)\n    return root",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public TreeNode insertIntoBST(TreeNode root, int val) {\n    if (root == null)\n      return new TreeNode(val);\n    if (root.val > val)\n      root.left = insertIntoBST(root.left, val);\n    else\n      root.right = insertIntoBST(root.right, val);\n    return root;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  TreeNode* insertIntoBST(TreeNode* root, int val) {\n    if (root == nullptr)\n      return new TreeNode(val);\n    if (root->val > val)\n      root->left = insertIntoBST(root->left, val);\n    else\n      root->right = insertIntoBST(root->right, val);\n    return root;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/701.html",
    "category": "Algorithms",
    "acceptance_rate": 73.4675202917908,
    "topics": [
      "Tree",
      "Binary Search Tree",
      "Binary Tree"
    ],
    "hints": [],
    "likes": 6131,
    "dislikes": 184,
    "similar_questions": "[{\"title\": \"Search in a Binary Search Tree\", \"titleSlug\": \"search-in-a-binary-search-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"686.5K\", \"totalSubmission\": \"934.4K\", \"totalAcceptedRaw\": 686452, \"totalSubmissionRaw\": 934360, \"acRate\": \"73.5%\"}",
    "title_pt": "Inserir em uma Árvore Binária de Busca",
    "description_pt": "<p>Você recebe o nó <code>root</code> de uma árvore binária de busca (BST) e um <code>value</code> a ser inserido na árvore. Retorne <em>o nó raiz da BST após a inserção</em>. É <strong>garantido</strong> que o novo valor não existe na BST original.</p>\n\n<p><strong>Observe</strong>&nbsp;que pode existir&nbsp;mais de uma forma válida de realizar a&nbsp;inserção, contanto que a árvore permaneça uma BST após a inserção. Você pode retornar <strong>qualquer uma delas</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/insertbst.jpg\" style=\"width: 752px; height: 221px;\" />\n<pre>\n<strong>Entrada:</strong> root = [4,2,7,1,3], val = 5\n<strong>Saída:</strong> [4,2,7,1,3,5]\n<strong>Explicação:</strong> Outra árvore aceita é:\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2020/10/05/bst.jpg\" style=\"width: 352px; height: 301px;\" />\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [40,20,60,10,30,50,70], val = 25\n<strong>Saída:</strong> [40,20,60,10,30,50,70,null,null,25]\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\n<strong>Saída:</strong> [4,2,7,1,3,5]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na&nbsp;árvore estará no intervalo <code>[0,&nbsp;10<sup>4</sup>]</code>.</li>\n\t<li><code>-10<sup>8</sup> &lt;= Node.val &lt;= 10<sup>8</sup></code></li>\n\t<li>Todos os valores <code>Node.val</code> são <strong>únicos</strong>.</li>\n\t<li><code>-10<sup>8</sup> &lt;= val &lt;= 10<sup>8</sup></code></li>\n\t<li>É <strong>garantido</strong> que <code>val</code> não existe na BST original.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "703",
    "paidOnly": false,
    "title": "Kth Largest Element in a Stream",
    "titleSlug": "kth-largest-element-in-a-stream",
    "url": "https://leetcode.com/problems/kth-largest-element-in-a-stream",
    "description_url": "https://leetcode.com/problems/kth-largest-element-in-a-stream/description/",
    "description": "<p>You are part of a university admissions office and need to keep track of the <code>kth</code> highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.</p>\n\n<p>You are tasked to implement a class which, for a given integer&nbsp;<code>k</code>, maintains a stream of test scores and continuously returns the&nbsp;<code>k</code>th highest test score&nbsp;<strong>after</strong>&nbsp;a new score has been submitted. More specifically, we are looking for the <code>k</code>th highest score in the sorted list of all scores.</p>\n\n<p>Implement the&nbsp;<code>KthLargest</code> class:</p>\n\n<ul>\n\t<li><code>KthLargest(int k, int[] nums)</code> Initializes the object with the integer <code>k</code> and the stream of test scores&nbsp;<code>nums</code>.</li>\n\t<li><code>int add(int val)</code> Adds a new test score&nbsp;<code>val</code> to the stream and returns the element representing the <code>k<sup>th</sup></code> largest element in the pool of test scores so far.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong><br />\n<span class=\"example-io\">[&quot;KthLargest&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;]<br />\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[null, 4, 5, 5, 8, 8]</span></p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);<br />\nkthLargest.add(3); // return 4<br />\nkthLargest.add(5); // return 5<br />\nkthLargest.add(10); // return 5<br />\nkthLargest.add(9); // return 8<br />\nkthLargest.add(4); // return 8</p>\n</div>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Input:</strong><br />\n<span class=\"example-io\">[&quot;KthLargest&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;]<br />\n[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]]</span></p>\n\n<p><strong>Output:</strong> <span class=\"example-io\">[null, 7, 7, 7, 8]</span></p>\n\n<p><strong>Explanation:</strong></p>\nKthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]);<br />\nkthLargest.add(2); // return 7<br />\nkthLargest.add(10); // return 7<br />\nkthLargest.add(9); // return 7<br />\nkthLargest.add(9); // return 8</div>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= nums.length + 1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= val &lt;= 10<sup>4</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/kth-largest-element-in-a-stream/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nImagine a university admissions office wants to keep track of the `k-th` highest test scores from applicants in real time. This allows them to dynamically determine the cut-off score as new applications come in. To achieve this, we'll create a class `KthLargest` that can return the `k-th` largest element for an incoming stream of numbers. Specifically, we need to implement:  \n\n1. The constructor `KthLargest(int k, int[] nums)`, which initializes the class with `k` and the initial stream of numbers `num`, \n2. The function `add(int val)`, which adds a new number `val` into the existing stream of numbers, and returns the `k-th` largest element of the updated stream. \n\n### Approach 1: Maintain Sorted List\n\n### Intuition\n\nIn this problem, we need to be able to repeatedly fetch the `k-th` largest element from a growing stream of numbers. Suppose we assume that the stream of numbers is always sorted in ascending order. In that case, returning the `k-th` largest element becomes a straightforward operation of fetching the `k-th` element from the end of the stream. \n\nThus, one approach is to maintain a list that stores the entire stream of numbers seen so far, and ensure the list remains sorted each time we add a new element. This allows us to fetch the `k-th` largest element with no extra work.\n\nFor our constructor, we can initialize our list `stream` with the initial set of numbers `nums` provided, and then sort `stream` in ascending order.  \n\nFor every new `val` added to the `stream` by the `add(int val)` call, we ensure `val` is inserted at the correct position so that `stream` remains sorted. Because `stream` is sorted beforehand, we can efficiently find the correct position for `val` by using [binary search](https://leetcode.com/explore/learn/card/binary-search/).\n\nFor this binary search insertion:\n\n1. We start with the entirety of `stream` as our search space\n2. We check the middle element `stream[mid]`\n    * If `stream[mid] == val` then we know that we can add `val` at index `mid`\n    * If `stream[mid] < val`, then `val` needs to be added to the right of `stream[mid]`, so we limit the search space to the right half of `stream`. \n    * If `stream[mid]` is greater than `val`,`val` needs to be added to the left of `stream[mid]`, so we limit the search space to the left half of `stream`. \n3.  We can repeat this procedure until we narrow down our search space to the correct index to add `val`.\n\nAfter inserting `val` in the correct position, we can return `stream[stream.length - k]`, which is the `k-th` largest element in the stream.\n\n### Algorithm\n\n1. In the constructor: \n    * Initialize class variable `k` \n    * Initialize class variable list `stream` \n    * Add all of `nums` to `stream`, used to keep track of the total stream.\n    * Sort `stream` in ascending order\n2. In the `add(int val)` function: \n    * Call helper function `getIndex(int val)` to find the index `i` to add `val`\n    * Insert `val` in `stream` at index `i`\n    * Return the `k-th` largest element in `stream`, at index `stream.size() - k`\n3. In the `getIndex(int val)`:\n    * **Define starting search space**: Initialize `left` to `0` and `right` to `stream.size() - 1`  \n    * While `left <= right`:\n        * **Calculate index for middle element**: Initialize `mid` to `(left + right) / 2`\n        * **Get middle element**: Initialize `midElement` to `stream.get(mid)`\n        * If `midElement == val` return `mid`\n        * If `midElement > val`:\n            * **Go to left half of search space**: Reassign `right` to `mid - 1`\n        * If `midElement < val`:\n            * **Go to right half of search space**: Reassign `left` to `mid + 1`\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/eBbNQ3hn/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"eBbNQ3hn\"></iframe>\n\n### Complexity Analysis\n\nLet $M$ be the size of the initial stream `nums` given in the constructor. Let $N$ be the number of calls of `add`. \n\n* Time Complexity: $O(N^2 + N \\cdot M)$\n\n    The constructor involves creating a list `stream` from `nums`, which takes $O(M)$ time. Then, sorting this list takes $O(M \\cdot \\log M)$ time. Thus, the time complexity of the constructor is $O(M \\cdot \\log M)$ time.  \n\n    The `add` function involves running a binary search on `stream`. Because the total size of `stream` at the end would be $O(M + N)$, each binary search is bounded by a time complexity of $O(\\log(M + N))$. Moreover, adding a number in `stream` can take worst-case $O(M + N)$ time, as adding an element in the middle of a list can offset all the elements to its right. Then, the time complexity of a single `add` call would be $O(M + N + \\log(M + N))$. Because `add` is called $N$ times, the time complexity of all the `add` calls would be $O(N \\cdot (M + N + \\log(M + N)))$.  \n\n    We see that after expanding the time complexity for the `add` function, the $N \\cdot M$ and $N^2$ terms dominate all the other $\\log$ terms in our calculations, so the total time complexity is $O(N^2 + N \\cdot M)$\n\n* Space Complexity: $O(M + N)$\n\n    The maximum size for `stream` is $M + N$, so the total space complexity is $O(M + N)$.\n\n### Approach 2: Heap\n\n### Intuition\n\nIn Approach 1, sorting the entire stream of numbers seems unnecessary because we only need the `k-th` largest element. Maintaining a sorted list becomes costly as its size increases. To optimize, we can focus on only the necessary elements for retrieving and updating the `k-th` largest element.\n\n\n!?!../Documents/703/slideshow1.json:960,540!?!\n\n\nConsider a stream of numbers `[0, 4, 6, 9]` where `k = 3` and incoming `val = 2`. Before adding `2`, the `k-th` largest element is `4`. Adding `2` does not affect `4`'s position since `2` is smaller. Now, if the incoming value is `7`, which is greater than both `4` and `6`, `7` would become the 2nd largest number, pushing `6` to be the new `k-th` largest element, and `4` is no longer in the top `k`.\n\n\n!?!../Documents/703/slideshow2.json:960,540!?!\n\n\nFrom this example, we see that keeping track of just the `k` largest elements allows us to efficiently maintain the `k-th` largest element:\n1. **If an incoming element `val` is smaller than or equal to the existing `k-th` largest element**: The `k` largest elements remain unchanged, and we can return the current `k-th` largest element.\n2. **If `val` is larger than the current `k-th` largest element**: It replaces the current `k-th` largest element. After adding `val`, the new `k-th` largest element is the next largest element.\n\nTo efficiently maintain the `k` largest elements, we use a min-heap. In a min-heap, elements are organized such that the smallest element is always at the top (root node), providing $O(1)$ access time. Adding elements and removing the top element from the min-heap can be done in $O(\\log n)$ time.\n\nFor our problem, the min-heap will contain the `k` largest elements, with the `k-th` largest element at the top. If a new `val` is greater than the `k-th` largest element, we add `val` to the heap and remove the top element, keeping the heap size at `k` and updating the `k-th` largest element.\n\nIn our optimized approach, we initialize the min-heap with the initial stream `nums` in the constructor and ensure it contains only the `k` largest elements. In the `add(int val)` function, if `val` is smaller than the current `k-th` largest element and the heap already contains `k` elements, we return the top element. Otherwise, we add `val`, remove the top element if the heap size exceeds `k`, and return the updated top element.\n\nThis approach is more efficient in both time and space complexity compared to maintaining a fully sorted list, as the relaxed ordering of a heap allows quick access and updates to the `k` largest elements without the overhead of sorting the entire stream.\n\n### Algorithm\n\n1. In the constructor: \n    * Initialize class variable `k` to the input value `k`\n    * Initialize a class `PriorityQueue` `minHeap` to hold the `k` largest elements\n    * Iterate through each element `num` in the initial stream `nums`:\n        * Call `add(num)`\n2. In the `add(int val)` function:\n    * If `val` is greater than the smallest element in `minHeap` or the size of `minHeap` is less than `k` elements:\n        * Add `val` to `minHeap`\n        * If the size of `minHeap` is greater than `k`, then remove the top element\n    * Return the top element as the `k-th` largest element in the stream\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/7W8gK6JG/shared\" frameBorder=\"0\" width=\"100%\" height=\"497\" name=\"7W8gK6JG\"></iframe>\n\n### Complexity Analysis\n\nLet $M$ be the size of the initial stream `nums` given in the constructor, and let $N$ be the number of calls to `add`.\n\n* Time Complexity: $O((M + N) \\cdot \\log k)$\n\n    The `add` function involves adding and removing an element from a heap of size $k$, which is an $O( \\log k)$ operation. Since the `add` function is called $N$ times, the total time complexity for all `add` calls is $O(N \\cdot \\log k)$.\n    \n    The constructor also calls `add` $M$ times to initialize the heap, leading to a time complexity of $O(M \\cdot \\log k)$.\n    \n    Therefore, the overall time complexity is $O((M + N) \\cdot \\log k)$.\n\n* Space Complexity: $O(k)$\n\n    The `minHeap` maintains at most $k$ elements, so the space complexity is $O(k)$.",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass KthLargest {\n  public KthLargest(int k, int[] nums) {\n    this.k = k;\n    for (final int num : nums)\n      heapify(num);\n  }\n\n  public int add(int val) {\n    heapify(val);\n    return minHeap.peek();\n  }\n\n  private final int k;\n  private Queue<Integer> minHeap = new PriorityQueue<>();\n\n  private void heapify(int val) {\n    minHeap.offer(val);\n    if (minHeap.size() > k)\n      minHeap.poll();\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass KthLargest {\n public:\n  KthLargest(int k, vector<int>& nums) : k(k) {\n    for (const int num : nums)\n      heapify(num);\n  }\n\n  int add(int val) {\n    heapify(val);\n    return minHeap.top();\n  }\n\n private:\n  const int k;\n  priority_queue<int, vector<int>, greater<>> minHeap;\n\n  void heapify(int val) {\n    minHeap.push(val);\n    if (minHeap.size() > k)\n      minHeap.pop();\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/703.html",
    "category": "Algorithms",
    "acceptance_rate": 59.725262406409854,
    "topics": [
      "Tree",
      "Design",
      "Binary Search Tree",
      "Heap (Priority Queue)",
      "Binary Tree",
      "Data Stream"
    ],
    "hints": [],
    "likes": 6082,
    "dislikes": 3895,
    "similar_questions": "[{\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Finding MK Average\", \"titleSlug\": \"finding-mk-average\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sequentially Ordinal Rank Tracker\", \"titleSlug\": \"sequentially-ordinal-rank-tracker\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"809.8K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 809816, \"totalSubmissionRaw\": 1355902, \"acRate\": \"59.7%\"}",
    "title_pt": "K-ésimo Maior Elemento em um Fluxo",
    "description_pt": "<p>Você faz parte de um escritório de admissões de uma universidade e precisa acompanhar a <code>kth</code> maior pontuação de teste dos candidatos em tempo real. Isso ajuda a determinar as notas de corte para entrevistas e admissões dinamicamente, à medida que novos candidatos enviam suas pontuações.</p>\n\n<p>Você deve implementar uma classe que, para um inteiro&nbsp;<code>k</code> dado, mantém um fluxo de pontuações de teste e retorna continuamente a <code>k</code>ª maior pontuação de teste <strong>após</strong> uma nova pontuação ter sido enviada. Mais especificamente, estamos procurando a <code>k</code>ª maior pontuação na lista ordenada de todas as pontuações.</p>\n\n<p>Implemente a classe&nbsp;<code>KthLargest</code>:</p>\n\n<ul>\n\t<li><code>KthLargest(int k, int[] nums)</code> Inicializa o objeto com o inteiro <code>k</code> e o fluxo de pontuações de teste <code>nums</code>.</li>\n\t<li><code>int add(int val)</code> Adiciona uma nova pontuação de teste <code>val</code> ao fluxo e retorna o elemento que representa o <code>k<sup>th</sup></code> maior elemento no conjunto de pontuações de teste até o momento.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong><br />\n<span class=\"example-io\">[&quot;KthLargest&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;]<br />\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[null, 4, 5, 5, 8, 8]</span></p>\n\n<p><strong>Explicação:</strong></p>\n\n<p>KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);<br />\nkthLargest.add(3); // return 4<br />\nkthLargest.add(5); // return 5<br />\nkthLargest.add(10); // return 5<br />\nkthLargest.add(9); // return 8<br />\nkthLargest.add(4); // return 8</p>\n</div>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<div class=\"example-block\">\n<p><strong>Entrada:</strong><br />\n<span class=\"example-io\">[&quot;KthLargest&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;, &quot;add&quot;]<br />\n[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]]</span></p>\n\n<p><strong>Saída:</strong> <span class=\"example-io\">[null, 7, 7, 7, 8]</span></p>\n\n<p><strong>Explicação:</strong></p>\nKthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]);<br />\nkthLargest.add(2); // return 7<br />\nkthLargest.add(10); // return 7<br />\nkthLargest.add(9); // return 7<br />\nkthLargest.add(9); // return 8</div>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= nums.length + 1</code></li>\n\t<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt;= val &lt;= 10<sup>4</sup></code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas a <code>add</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "704",
    "paidOnly": false,
    "title": "Binary Search",
    "titleSlug": "binary-search",
    "url": "https://leetcode.com/problems/binary-search",
    "description_url": "https://leetcode.com/problems/binary-search/description/",
    "description": "<p>Given an array of integers <code>nums</code> which is sorted in ascending order, and an integer <code>target</code>, write a function to search <code>target</code> in <code>nums</code>. If <code>target</code> exists, then return its index. Otherwise, return <code>-1</code>.</p>\n\n<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 9\n<strong>Output:</strong> 4\n<strong>Explanation:</strong> 9 exists in nums and its index is 4\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 2\n<strong>Output:</strong> -1\n<strong>Explanation:</strong> 2 does not exist in nums so return -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt; nums[i], target &lt; 10<sup>4</sup></code></li>\n\t<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>\n\t<li><code>nums</code> is sorted in ascending order.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/binary-search/solutions/",
    "solution": "[TOC]\n\n## Solution\n \n--- \n\n### Overview\n\n\nIf you don't have much experience with binary-search-related problems, we strongly suggest you read this [LeetCode Explore Card](https://leetcode.com/explore/learn/card/binary-search/), our explore card for binary search! We'll cover four methods, the first three of which are closely related to those presented in this card, so it's helpful to look ahead! \n\n---\n\n### Approach 1: Find the Exact Value\n\n#### Intuition   \n\nWe start from the most basic and elementary template.\n\nFirst, we define the search space using two boundary indexes, `left` and `right`, all possible indexes are within the inclusive range `[left, right]`. We shall continue searching over the search space as long as it is not empty. A general way is to use a while loop with the condition `left <= right`, so we can break out of this loop if we empty the range or trigger other conditions which we will discuss later.\n\n![alt text](../Figures/704_fix/b1_fix.png)\n\nThe next step is to find the 'pivot point', the middle index that divides the search space into two halves. We need to compare the value at the middle index `nums[mid]` with `target`, the purpose of this step is to cut one half that is guaranteed not to contain `target`. \n\n- If `nums[mid] = target`, it means we find `target`, and the job is done! We can break the loop by returning `mid`.\n- If `nums[mid] < target`, combined with the array is sorted, we know that all values in the left half are smaller than `target`, so we can safely cut this half by letting `left = mid + 1`.  \n- If `nums[mid] > target`, it means all values in the right half are larger than `target` and can be cut safely!\n\n![alt text](../Figures/704_fix/b2_fix.png)\n\nDoes this loop ever stop? Yes, take the following picture as an example, suppose we are searching over an array of size 1, in this case, `left`, `right`, and `mid` all stand for the only index in the array. In any of the three conditions, we trigger one of the break statements and stop the loop. \n\n![alt text](../Figures/704_fix/b3_fix.png)\n\n\n<br>\n\n#### Algorithm\n\n1) Initialize the boundaries of the search space as `left = 0` and `right = nums.size - 1`.\n2) If there are elements in the range `[left, right]`, we find the middle index `mid = (left + right) / 2` and compare the middle value `nums[mid]` with `target`:\n    - If `nums[mid] = target`, return `mid`.\n    - If `nums[mid] < target`, let `left = mid + 1` and repeat step 2.\n    - If `nums[mid] > target`, let `right = mid - 1` and repeat step 2.\n3) We finish the loop without finding `target`, return `-1`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Bpknge2T/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Bpknge2T\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$n$$ be the size of the input array `nums`.\n\n* Time complexity: $$O(\\log n)$$\n\n    - `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, and it takes logarithmic time to reach this break condition.\n    \n\n* Space complexity: $$O(1)$$\n\n    - During the loop, we only need to record three indexes, `left`, `right`, and `mid`, they take constant space.\n\n<br/>\n\n\n\n---\n\n### Approach 2: Find Upper bound\n\n#### Intuition   \n\nHere we introduce an alternative way to implement binary search: instead of looking for `target` in the array `nums`, we look for the insert position where we can put `target` in without disrupting the order.\n\n![alt text](../Figures/704_fix/u1_fix.png)\n\nGenerally, we have two inserting ways, insert into the rightmost possible position which we called finding the **upper bound**, and insert into the leftmost possible position which we called finding the **lower bound**. We will implement them in the following approaches.\n\nTake the picture below as an example. Assume that we want to insert `9` into array `A`. If we look for the **upper bound**, we have to insert `9` to the right of all existing `9`s in the array. Similarly, if we look for the **lower bound**, we have to insert `9` to the left of all existing `9`s. (Although we don't have duplicate elements in this problem, having duplicate elements is more common in problems so we would better know this concept in advance!)\n\n![alt text](../Figures/704_fix/u3_fix.png)\n\n\nNow we start the binary search. Similar to the previous approach, we still use `left` and `right` as two boundary indexes. The question is, what is the next step after we find the middle index `mid`?\n\n![alt text](../Figures/704_fix/upper2_fix.png)\n\n- If `nums[mid] < target`, the insert position is on `mid`'s right, so we let `left = mid + 1` to discard the left half and `mid`.\n\n- If `nums[mid] = target`, the insert position is on `mid`'s right, so we let `left = mid + 1` to discard the left half and `mid`.\n\n![alt text](../Figures/704_fix/u4_fix.png)\n\n- If `nums[mid] > target`, `mid` can also be the insert position. So we let `right = mid` to discard the right half while keeping `mid`.\n\n\nTherefore, we merged the two conditions `nums[mid] = target` and `nums[mid] < target` and there are only two conditions in the `if-else` statement!\n\n![alt text](../Figures/704_fix/upper5_fix.png)\n\nOnce the loop stops, `left` stands for the insert position and `left - 1` is the largest element that is no larger than `target`. We just need to check if `nums[left - 1]` equals `target`. Note this boundary condition where `left = 0`, which means all elements in `nums` are larger than `target`, so there is no `target` in `nums`.\n\n\n<br>\n\n#### Algorithm\n\n1) Initialize the boundaries of the search space as `left = 0` and `right = nums.size` (Note that the maximum insert position can be `nums.size`)\n2) If there are elements in the range `[left, right]`, we find the middle index `mid = (left + right) / 2` and compare the middle value `nums[mid]` with `target`:\n    - If `nums[mid] <= target`, let `left = mid + 1` and repeat step 2.\n    - If `nums[mid] > target`, let `right = mid` and repeat step 2.\n3) We finish the loop and `left` stands for the insert position:\n    - If `left > 0` and `nums[left - 1] = target`, return `left - 1`.\n    - Otherwise, return `-1`.\n\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/EbGiVeiU/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"EbGiVeiU\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$n$$ be the size of the input array `nums`.\n\n* Time complexity: $$O(\\log n)$$\n\n    - `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, it takes logarithmic time to reach this break condition.\n    \n\n* Space complexity: $$O(1)$$\n\n    - During the loop, we only need to record three indexes, `left`, `right`, and `mid`, they take constant space.\n\n<br/>\n\n---\n\n### Approach 3: Find Lower bound\n\n#### Intuition   \n\nDifferent from the previous method, here we are looking for the **leftmost** insert position. Therefore, we will make the following changes to the judgment condition:\n\n\n- If `nums[mid] < target`, `mid` can also be the insertion position. So we let `left = mid + 1`, that is, discard the left half while keeping `mid`.\n\n- If `nums[mid] = target`, the insert position is on `mid`'s left, so we let `right = mid` to discard both the right half and `mid`.\n\n![alt text](../Figures/704_fix/lower1_fix.png)\n\n- If `nums[mid] > target`, the insert position is on `mid`'s left, so we let `right = mid` to discard both the right half and `mid`.\n\n\nTherefore, we merged the two conditions `nums[mid] = target` and `nums[mid] > target` and there are only two conditions in the `if-else` statement!\n\n![alt text](../Figures/704_fix/lower2_fix.png)\n\nOnce the loop stops, `left` stands for the insert position and `nums[left]` is the smallest element that is no less than `target`. We just need to check if `nums[left]` equals `target`. Note this boundary condition `left = nums.size`, which means all elements in `nums` are smaller than `target`, so there is no `target` in `nums`.\n\n<br>\n\n#### Algorithm\n\n1) Initialize the boundaries of the search space as `left = 0` and `right = nums.size` (Note that the maximum insert position can be `nums.size`)\n2) If there are elements in the range `[left, right]`, we find the middle index `mid = (left + right) / 2` and compare the middle value `nums[mid]` with `target`:\n    - If `nums[mid] >= target`, let `right = mid` and repeat step 2.\n    - If `nums[mid] < target`, let `left = mid + 1` and repeat step 2.\n3) We finish the loop and `left` stands for the insert position:\n    - If `left < nums.size` and `nums[left] = target`, return `left`.\n    - Otherwise, return `-1`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/PtMd9Lfm/shared\" frameBorder=\"0\" width=\"100%\" height=\"429\" name=\"PtMd9Lfm\"></iframe>\n\n\n#### Complexity Analysis\n\nLet $$n$$ be the size of the input array `nums`.\n\n* Time complexity: $$O(\\log n)$$\n\n    - `nums` is divided into half each time. In the worst-case scenario, we need to cut `nums` until the range has no element, it takes logarithmic time to reach this break condition.\n    \n\n* Space complexity: $$O(1)$$\n\n    - During the loop, we only need to record three indexes, `left`, `right`, and `mid`, they take constant space. \n\n\n<br/>\n\n\n---\n\n### Approach 4: Use built-in tools.\n\n#### Intuition   \n\nWe have implemented various templates of binary search, now let's quickly go through the last approach that uses built-in functions. C++ provides the `<algorithm>` library that defines functions for binary searching, Python provides `bisect` module which also supports binary search functions. If we are solving some standard problems that do not require a lot of customization, it's feasible to rely on these built-in tools to save time.\n\nNote that `upper_bound` and `bisect.bisect_right` look for the rightmost insertion position and bring the same result as approach 2, while `lower_bound` and `bisect.bisect_left` look for the leftmost insertion position and end up with the same result as approach 3. Once we find the insertion position, check if the value at the corresponding position equals `target`.\n\nHere we implement the method that uses **upper_bound** or **bisect.bisect_right** and leave another half as a practice!\n\n<br>\n\n#### Algorithm\n\n1) Use built-in tools to locate the rightmost insertion position `idx`.\n2) If `idx > 0` and `nums[idx - 1] = target`, return `idx -1`. Otherwise, return `-1`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/oXjRqYX9/shared\" frameBorder=\"0\" width=\"100%\" height=\"276\" name=\"oXjRqYX9\"></iframe>\n\n#### Complexity Analysis\n\nLet $$n$$ be the size of the input array `nums`.\n\n* Time complexity: $$O(\\log n)$$\n\n    - The time complexity of the built-in binary search is $$O(\\log n)$$.\n    \n\n* Space complexity: $$O(1)$$\n\n    - The built-in binary search only takes $$O(1)$$ space.\n\n<br/>",
    "solution_code_python": "",
    "solution_code_java": "",
    "solution_code_cpp": "",
    "solution_code_url": "https://leetcodehelp.github.io/704.html",
    "category": "Algorithms",
    "acceptance_rate": 59.414849083693596,
    "topics": [
      "Array",
      "Binary Search"
    ],
    "hints": [],
    "likes": 12536,
    "dislikes": 272,
    "similar_questions": "[{\"title\": \"Search in a Sorted Array of Unknown Size\", \"titleSlug\": \"search-in-a-sorted-array-of-unknown-size\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Count of Positive Integer and Negative Integer\", \"titleSlug\": \"maximum-count-of-positive-integer-and-negative-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"3.1M\", \"totalSubmission\": \"5.3M\", \"totalAcceptedRaw\": 3128889, \"totalSubmissionRaw\": 5266173, \"acRate\": \"59.4%\"}",
    "title_pt": "Busca Binária",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, que está ordenado em ordem crescente, e um inteiro <code>target</code>, escreva uma função para buscar <code>target</code> em <code>nums</code>. Se <code>target</code> existir, então retorne seu índice. Caso contrário, retorne <code>-1</code>.</p>\n\n<p>Você deve escrever um algoritmo com complexidade de tempo <code>O(log n)</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,0,3,5,9,12], target = 9\n<strong>Saída:</strong> 4\n<strong>Explicação:</strong> 9 existe em nums e seu índice é 4\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [-1,0,3,5,9,12], target = 2\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong> 2 não existe em nums, então retorne -1\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-10<sup>4</sup> &lt; nums[i], target &lt; 10<sup>4</sup></code></li>\n\t<li>Todos os inteiros em <code>nums</code> são <strong>únicos</strong>.</li>\n\t<li><code>nums</code> está ordenado em ordem crescente.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "705",
    "paidOnly": false,
    "title": "Design HashSet",
    "titleSlug": "design-hashset",
    "url": "https://leetcode.com/problems/design-hashset",
    "description_url": "https://leetcode.com/problems/design-hashset/description/",
    "description": "<p>Design a HashSet without using any built-in hash table libraries.</p>\n\n<p>Implement <code>MyHashSet</code> class:</p>\n\n<ul>\n\t<li><code>void add(key)</code> Inserts the value <code>key</code> into the HashSet.</li>\n\t<li><code>bool contains(key)</code> Returns whether the value <code>key</code> exists in the HashSet or not.</li>\n\t<li><code>void remove(key)</code> Removes the value <code>key</code> in the HashSet. If <code>key</code> does not exist in the HashSet, do nothing.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyHashSet&quot;, &quot;add&quot;, &quot;add&quot;, &quot;contains&quot;, &quot;contains&quot;, &quot;add&quot;, &quot;contains&quot;, &quot;remove&quot;, &quot;contains&quot;]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\n<strong>Output</strong>\n[null, null, null, true, false, null, true, null, false]\n\n<strong>Explanation</strong>\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1);      // set = [1]\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2);   // set = [1]\nmyHashSet.contains(2); // return False, (already removed)</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key &lt;= 10<sup>6</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code>, <code>remove</code>, and <code>contains</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-hashset/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass MyHashSet:\n  def __init__(self):\n    self.set = [False] * 1000001\n\n  def add(self, key: int) -> None:\n    self.set[key] = True\n\n  def remove(self, key: int) -> None:\n    self.set[key] = False\n\n  def contains(self, key: int) -> bool:\n    return self.set[key]",
    "solution_code_java": "\t\t\t\n\nclass MyHashSet {\n  /** Initialize your data structure here. */\n  public MyHashSet() {\n    set = new boolean[1000001];\n  }\n\n  public void add(int key) {\n    set[key] = true;\n  }\n\n  public void remove(int key) {\n    set[key] = false;\n  }\n\n  /** Returns true if this set contains the specified element */\n  public boolean contains(int key) {\n    return set[key];\n  }\n\n  private boolean[] set = new boolean[1000001];\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyHashSet {\n public:\n  /** Initialize your data structure here. */\n  MyHashSet() : set(1000001) {}\n\n  void add(int key) {\n    set[key] = true;\n  }\n\n  void remove(int key) {\n    set[key] = false;\n  }\n\n  /** Returns true if this set contains the specified element */\n  bool contains(int key) {\n    return set[key];\n  }\n\n private:\n  vector<bool> set;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/705.html",
    "category": "Algorithms",
    "acceptance_rate": 66.96049669100088,
    "topics": [
      "Array",
      "Hash Table",
      "Linked List",
      "Design",
      "Hash Function"
    ],
    "hints": [],
    "likes": 3894,
    "dislikes": 321,
    "similar_questions": "[{\"title\": \"Design HashMap\", \"titleSlug\": \"design-hashmap\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Design Skiplist\", \"titleSlug\": \"design-skiplist\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"490.7K\", \"totalSubmission\": \"732.8K\", \"totalAcceptedRaw\": 490718, \"totalSubmissionRaw\": 732847, \"acRate\": \"67.0%\"}",
    "title_pt": "Projetar um HashSet",
    "description_pt": "<p>Projete um HashSet sem usar quaisquer bibliotecas internas de tabela hash.</p>\n\n<p>Implemente a classe <code>MyHashSet</code>:</p>\n\n<ul>\n\t<li><code>void add(key)</code> Insere o valor <code>key</code> no HashSet.</li>\n\t<li><code>bool contains(key)</code> Retorna se o valor <code>key</code> existe no HashSet ou não.</li>\n\t<li><code>void remove(key)</code> Remove o valor <code>key</code> no HashSet. Se <code>key</code> não existir no HashSet, não faça nada.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyHashSet&quot;, &quot;add&quot;, &quot;add&quot;, &quot;contains&quot;, &quot;contains&quot;, &quot;add&quot;, &quot;contains&quot;, &quot;remove&quot;, &quot;contains&quot;]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\n<strong>Saída</strong>\n[null, null, null, true, false, null, true, null, false]\n\n<strong>Explicação</strong>\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1);      // set = [1]\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2);      // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2);   // set = [1]\nmyHashSet.contains(2); // return False, (already removed)</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key &lt;= 10<sup>6</sup></code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>add</code>, <code>remove</code> e <code>contains</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "706",
    "paidOnly": false,
    "title": "Design HashMap",
    "titleSlug": "design-hashmap",
    "url": "https://leetcode.com/problems/design-hashmap",
    "description_url": "https://leetcode.com/problems/design-hashmap/description/",
    "description": "<p>Design a HashMap without using any built-in hash table libraries.</p>\n\n<p>Implement the <code>MyHashMap</code> class:</p>\n\n<ul>\n\t<li><code>MyHashMap()</code> initializes the object with an empty map.</li>\n\t<li><code>void put(int key, int value)</code> inserts a <code>(key, value)</code> pair into the HashMap. If the <code>key</code> already exists in the map, update the corresponding <code>value</code>.</li>\n\t<li><code>int get(int key)</code> returns the <code>value</code> to which the specified <code>key</code> is mapped, or <code>-1</code> if this map contains no mapping for the <code>key</code>.</li>\n\t<li><code>void remove(key)</code> removes the <code>key</code> and its corresponding <code>value</code> if the map contains the mapping for the <code>key</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyHashMap&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;remove&quot;, &quot;get&quot;]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\n<strong>Output</strong>\n[null, null, null, 1, -1, null, 1, null, -1]\n\n<strong>Explanation</strong>\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1);    // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3);    // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2);    // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2);    // return -1 (i.e., not found), The map is now [[1,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key, value &lt;= 10<sup>6</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>put</code>, <code>get</code>, and <code>remove</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-hashmap/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass MyHashMap {\n  /** Initialize your data structure here. */\n  public MyHashMap() {\n    lists = new List[kSize];\n\n    for (int i = 0; i < kSize; ++i)\n      lists[i] = new ArrayList<>();\n  }\n\n  /** value will always be non-negative. */\n  public void put(int key, int value) {\n    for (int[] pair : lists[key % kSize])\n      if (pair[0] == key) {\n        pair[1] = value;\n        return;\n      }\n    lists[key % kSize].add(new int[] {key, value});\n  }\n\n  /**\n   * Returns the value to which the specified key is mapped, or -1 if this map\n   * contains no mapping for the key\n   */\n  public int get(int key) {\n    for (int[] pair : lists[key % kSize])\n      if (pair[0] == key)\n        return pair[1];\n    return -1;\n  }\n\n  /**\n   * Removes the mapping of the specified value key if this map contains a mapping\n   * for the key\n   */\n  public void remove(int key) {\n    for (int i = 0; i < lists[key % kSize].size(); ++i)\n      if (lists[key % kSize].get(i)[0] == key) {\n        lists[key % kSize].remove(i);\n        return;\n      }\n  }\n\n  private static final int kSize = 10000;\n  List<int[]>[] lists; // Each slot store (key, value) list\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyHashMap {\n public:\n  /** Initialize your data structure here. */\n  MyHashMap() : lists(kSize) {}\n\n  /** value will always be non-negative. */\n  void put(int key, int value) {\n    auto& pairs = lists[key % kSize];\n    for (auto& [k, v] : pairs)\n      if (k == key) {\n        v = value;\n        return;\n      }\n    pairs.emplace_back(key, value);\n  }\n\n  /** Returns the value to which the specified key is mapped, or -1 if this map\n   * contains no mapping for the key */\n  int get(int key) {\n    const list<pair<int, int>>& pairs = lists[key % kSize];\n    for (const auto& [k, v] : pairs)\n      if (k == key)\n        return v;\n    return -1;\n  }\n\n  /** Removes the mapping of the specified value key if this map contains a\n   * mapping for the key */\n  void remove(int key) {\n    auto& pairs = lists[key % kSize];\n    for (auto it = begin(pairs); it != end(pairs); ++it)\n      if (it->first == key) {\n        pairs.erase(it);\n        return;\n      }\n  }\n\n private:\n  static const int kSize = 10000;\n  vector<list<pair<int, int>>> lists;  // Each slot store (key, value) list\n};",
    "solution_code_url": "https://leetcodehelp.github.io/706.html",
    "category": "Algorithms",
    "acceptance_rate": 65.84058209412439,
    "topics": [
      "Array",
      "Hash Table",
      "Linked List",
      "Design",
      "Hash Function"
    ],
    "hints": [],
    "likes": 5264,
    "dislikes": 484,
    "similar_questions": "[{\"title\": \"Design HashSet\", \"titleSlug\": \"design-hashset\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Design Skiplist\", \"titleSlug\": \"design-skiplist\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"668.4K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 668429, \"totalSubmissionRaw\": 1015224, \"acRate\": \"65.8%\"}",
    "title_pt": "Projetar HashMap",
    "description_pt": "<p>Projete um HashMap sem usar nenhuma biblioteca de tabela hash integrada.</p>\n\n<p>Implemente a classe <code>MyHashMap</code>:</p>\n\n<ul>\n\t<li><code>MyHashMap()</code> inicializa o objeto com um mapa vazio.</li>\n\t<li><code>void put(int key, int value)</code> insere um par <code>(key, value)</code> no HashMap. Se a <code>key</code> já existir no mapa, atualize o <code>value</code> correspondente.</li>\n\t<li><code>int get(int key)</code> retorna o <code>value</code> ao qual a <code>key</code> especificada está mapeada, ou <code>-1</code> se este mapa não contiver nenhum mapeamento para a <code>key</code>.</li>\n\t<li><code>void remove(key)</code> remove a <code>key</code> e seu <code>value</code> correspondente se o mapa contiver o mapeamento para a <code>key</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyHashMap&quot;, &quot;put&quot;, &quot;put&quot;, &quot;get&quot;, &quot;get&quot;, &quot;put&quot;, &quot;get&quot;, &quot;remove&quot;, &quot;get&quot;]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\n<strong>Saída</strong>\n[null, null, null, 1, -1, null, 1, null, -1]\n\n<strong>Explicação</strong>\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // O mapa agora é [[1,1]]\nmyHashMap.put(2, 2); // O mapa agora é [[1,1], [2,2]]\nmyHashMap.get(1);    // retorna 1, O mapa agora é [[1,1], [2,2]]\nmyHashMap.get(3);    // retorna -1 (isto é, não encontrado), O mapa agora é [[1,1], [2,2]]\nmyHashMap.put(2, 1); // O mapa agora é [[1,1], [2,1]] (isto é, atualiza o valor existente)\nmyHashMap.get(2);    // retorna 1, O mapa agora é [[1,1], [2,1]]\nmyHashMap.remove(2); // remove o mapeamento para 2, O mapa agora é [[1,1]]\nmyHashMap.get(2);    // retorna -1 (isto é, não encontrado), O mapa agora é [[1,1]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= key, value &lt;= 10<sup>6</sup></code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>put</code>, <code>get</code> e <code>remove</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "707",
    "paidOnly": false,
    "title": "Design Linked List",
    "titleSlug": "design-linked-list",
    "url": "https://leetcode.com/problems/design-linked-list",
    "description_url": "https://leetcode.com/problems/design-linked-list/description/",
    "description": "<p>Design your implementation of the linked list. You can choose to use a singly or doubly linked list.<br />\nA node in a singly linked list should have two attributes: <code>val</code> and <code>next</code>. <code>val</code> is the value of the current node, and <code>next</code> is a pointer/reference to the next node.<br />\nIf you want to use the doubly linked list, you will need one more attribute <code>prev</code> to indicate the previous node in the linked list. Assume all nodes in the linked list are <strong>0-indexed</strong>.</p>\n\n<p>Implement the <code>MyLinkedList</code> class:</p>\n\n<ul>\n\t<li><code>MyLinkedList()</code> Initializes the <code>MyLinkedList</code> object.</li>\n\t<li><code>int get(int index)</code> Get the value of the <code>index<sup>th</sup></code> node in the linked list. If the index is invalid, return <code>-1</code>.</li>\n\t<li><code>void addAtHead(int val)</code> Add a node of value <code>val</code> before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.</li>\n\t<li><code>void addAtTail(int val)</code> Append a node of value <code>val</code> as the last element of the linked list.</li>\n\t<li><code>void addAtIndex(int index, int val)</code> Add a node of value <code>val</code> before the <code>index<sup>th</sup></code> node in the linked list. If <code>index</code> equals the length of the linked list, the node will be appended to the end of the linked list. If <code>index</code> is greater than the length, the node <strong>will not be inserted</strong>.</li>\n\t<li><code>void deleteAtIndex(int index)</code> Delete the <code>index<sup>th</sup></code> node in the linked list, if the index is valid.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;MyLinkedList&quot;, &quot;addAtHead&quot;, &quot;addAtTail&quot;, &quot;addAtIndex&quot;, &quot;get&quot;, &quot;deleteAtIndex&quot;, &quot;get&quot;]\n[[], [1], [3], [1, 2], [1], [1], [1]]\n<strong>Output</strong>\n[null, null, null, null, 2, null, 3]\n\n<strong>Explanation</strong>\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2);    // linked list becomes 1-&gt;2-&gt;3\nmyLinkedList.get(1);              // return 2\nmyLinkedList.deleteAtIndex(1);    // now the linked list is 1-&gt;3\nmyLinkedList.get(1);              // return 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= index, val &lt;= 1000</code></li>\n\t<li>Please do not use the built-in LinkedList library.</li>\n\t<li>At most <code>2000</code> calls will be made to <code>get</code>, <code>addAtHead</code>, <code>addAtTail</code>, <code>addAtIndex</code> and <code>deleteAtIndex</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/design-linked-list/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass ListNode:\n  def __init__(self, x):\n    self.val = x\n    self.next = None\n\n\nclass MyLinkedList:\n  def __init__(self):\n    self.length = 0\n    self.dummy = ListNode(0)\n\n  def get(self, index: int) -> int:\n    if index < 0 or index >= self.length:\n      return -1\n    curr = self.dummy.next\n    for _ in range(index):\n      curr = curr.next\n    return curr.val\n\n  def addAtHead(self, val: int) -> None:\n    curr = self.dummy.next\n    self.dummy.next = ListNode(val)\n    self.dummy.next.next = curr\n    self.length += 1\n\n  def addAtTail(self, val: int) -> None:\n    curr = self.dummy\n    while curr.next:\n      curr = curr.next\n    curr.next = ListNode(val)\n    self.length += 1\n\n  def addAtIndex(self, index: int, val: int) -> None:\n    if index > self.length:\n      return\n    curr = self.dummy\n    for _ in range(index):\n      curr = curr.next\n    temp = curr.next\n    curr.next = ListNode(val)\n    curr.next.next = temp\n    self.length += 1\n\n  def deleteAtIndex(self, index: int) -> None:\n    if index < 0 or index >= self.length:\n      return\n    curr = self.dummy\n    for _ in range(index):\n      curr = curr.next\n    temp = curr.next\n    curr.next = temp.next\n    self.length -= 1",
    "solution_code_java": "\t\t\t\n\nclass MyLinkedList {\n  private class ListNode {\n    int val;\n    ListNode next;\n    public ListNode(int val) {\n      this.val = val;\n      this.next = null;\n    }\n  }\n\n  public int get(int index) {\n    if (index < 0 || index >= length)\n      return -1;\n    ListNode curr = dummy.next;\n    for (int i = 0; i < index; ++i)\n      curr = curr.next;\n    return curr.val;\n  }\n\n  public void addAtHead(int val) {\n    ListNode head = dummy.next;\n    ListNode node = new ListNode(val);\n    node.next = head;\n    dummy.next = node;\n    ++length;\n  }\n\n  public void addAtTail(int val) {\n    ListNode curr = dummy;\n    while (curr.next != null)\n      curr = curr.next;\n    curr.next = new ListNode(val);\n    ++length;\n  }\n\n  public void addAtIndex(int index, int val) {\n    if (index > length)\n      return;\n    ListNode curr = dummy;\n    for (int i = 0; i < index; ++i)\n      curr = curr.next;\n    ListNode cache = curr.next;\n    ListNode node = new ListNode(val);\n    node.next = cache;\n    curr.next = node;\n    ++length;\n  }\n\n  public void deleteAtIndex(int index) {\n    if (index < 0 || index >= length)\n      return;\n    ListNode curr = dummy;\n    for (int i = 0; i < index; ++i)\n      curr = curr.next;\n    ListNode cache = curr.next;\n    curr.next = cache.next;\n    --length;\n  }\n\n  int length = 0;\n  ListNode dummy = new ListNode(0);\n}",
    "solution_code_cpp": "\t\t\t\n\nclass MyLinkedList {\n  struct ListNode {\n    int val;\n    ListNode* next;\n    ListNode(int x) : val(x), next(nullptr) {}\n  };\n\n public:\n  int get(int index) {\n    if (index < 0 || index >= length)\n      return -1;\n    ListNode* curr = dummy.next;\n    for (int i = 0; i < index; ++i)\n      curr = curr->next;\n    return curr->val;\n  }\n\n  void addAtHead(int val) {\n    ListNode* head = dummy.next;\n    ListNode* node = new ListNode(val);\n    node->next = head;\n    dummy.next = node;\n    ++length;\n  }\n\n  void addAtTail(int val) {\n    ListNode* curr = &dummy;\n    while (curr->next)\n      curr = curr->next;\n    curr->next = new ListNode(val);\n    ++length;\n  }\n\n  void addAtIndex(int index, int val) {\n    if (index > length)\n      return;\n    ListNode* curr = &dummy;\n    for (int i = 0; i < index; ++i)\n      curr = curr->next;\n    ListNode* cache = curr->next;\n    ListNode* node = new ListNode(val);\n    node->next = cache;\n    curr->next = node;\n    ++length;\n  }\n\n  void deleteAtIndex(int index) {\n    if (index < 0 || index >= length)\n      return;\n    ListNode* curr = &dummy;\n    for (int i = 0; i < index; ++i)\n      curr = curr->next;\n    ListNode* cache = curr->next;\n    curr->next = cache->next;\n    --length;\n    delete cache;\n  }\n\n private:\n  int length = 0;\n  ListNode dummy = ListNode(0);\n};",
    "solution_code_url": "https://leetcodehelp.github.io/707.html",
    "category": "Algorithms",
    "acceptance_rate": 28.97285728767049,
    "topics": [
      "Linked List",
      "Design"
    ],
    "hints": [],
    "likes": 2835,
    "dislikes": 1655,
    "similar_questions": "[{\"title\": \"Design Skiplist\", \"titleSlug\": \"design-skiplist\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"405.9K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 405856, \"totalSubmissionRaw\": 1400817, \"acRate\": \"29.0%\"}",
    "title_pt": "Projetar Lista Encadeada",
    "description_pt": "<p>Projete sua implementação da lista encadeada. Você pode escolher usar uma lista encadeada simplesmente ou duplamente encadeada.<br />\nUm nó em uma lista encadeada simplesmente encadeada deve ter dois atributos: <code>val</code> e <code>next</code>. <code>val</code> é o valor do nó atual, e <code>next</code> é um ponteiro/referência para o próximo nó.<br />\nSe você quiser usar a lista encadeada duplamente encadeada, você precisará de mais um atributo <code>prev</code> para indicar o nó anterior na lista encadeada. Assuma que todos os nós na lista encadeada são <strong>indexados em 0</strong>.</p>\n\n<p>Implemente a classe <code>MyLinkedList</code>:</p>\n\n<ul>\n\t<li><code>MyLinkedList()</code> Inicializa o objeto <code>MyLinkedList</code>.</li>\n\t<li><code>int get(int index)</code> Obtém o valor do <code>index<sup>th</sup></code> nó na lista encadeada. Se o índice for inválido, retorne <code>-1</code>.</li>\n\t<li><code>void addAtHead(int val)</code> Adiciona um nó de valor <code>val</code> antes do primeiro elemento da lista encadeada. Após a inserção, o novo nó será o primeiro nó da lista encadeada.</li>\n\t<li><code>void addAtTail(int val)</code> Anexa um nó de valor <code>val</code> como o último elemento da lista encadeada.</li>\n\t<li><code>void addAtIndex(int index, int val)</code> Adiciona um nó de valor <code>val</code> antes do <code>index<sup>th</sup></code> nó na lista encadeada. Se <code>index</code> for igual ao comprimento da lista encadeada, o nó será anexado ao final da lista encadeada. Se <code>index</code> for maior que o comprimento, o nó <strong>não será inserido</strong>.</li>\n\t<li><code>void deleteAtIndex(int index)</code> Exclui o <code>index<sup>th</sup></code> nó na lista encadeada, se o índice for válido.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;MyLinkedList&quot;, &quot;addAtHead&quot;, &quot;addAtTail&quot;, &quot;addAtIndex&quot;, &quot;get&quot;, &quot;deleteAtIndex&quot;, &quot;get&quot;]\n[[], [1], [3], [1, 2], [1], [1], [1]]\n<strong>Saída</strong>\n[null, null, null, null, 2, null, 3]\n\n<strong>Explicação</strong>\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2);    // linked list becomes 1-&gt;2-&gt;3\nmyLinkedList.get(1);              // return 2\nmyLinkedList.deleteAtIndex(1);    // now the linked list is 1-&gt;3\nmyLinkedList.get(1);              // return 3\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>0 &lt;= index, val &lt;= 1000</code></li>\n\t<li>Por favor, não use a biblioteca LinkedList embutida.</li>\n\t<li>No máximo <code>2000</code> chamadas serão feitas a <code>get</code>, <code>addAtHead</code>, <code>addAtTail</code>, <code>addAtIndex</code> e <code>deleteAtIndex</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "709",
    "paidOnly": false,
    "title": "To Lower Case",
    "titleSlug": "to-lower-case",
    "url": "https://leetcode.com/problems/to-lower-case",
    "description_url": "https://leetcode.com/problems/to-lower-case/description/",
    "description": "<p>Given a string <code>s</code>, return <em>the string after replacing every uppercase letter with the same lowercase letter</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;Hello&quot;\n<strong>Output:</strong> &quot;hello&quot;\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;here&quot;\n<strong>Output:</strong> &quot;here&quot;\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> s = &quot;LOVELY&quot;\n<strong>Output:</strong> &quot;lovely&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> consists of printable ASCII characters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/to-lower-case/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def toLowerCase(self, str: str) -> str:\n    return ''.join(chr(ord(c) + 32) if 'A' <= c <= 'Z' else c for c in str)",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public String toLowerCase(String str) {\n    final int diff = 'A' - 'a';\n\n    char[] ans = str.toCharArray();\n\n    for (int i = 0; i < ans.length; ++i)\n      if (ans[i] >= 'A' && ans[i] <= 'Z')\n        ans[i] -= diff;\n\n    return new String(ans);\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  string toLowerCase(string str) {\n    const int diff = 'A' - 'a';\n\n    for (char& c : str)\n      if (c >= 'A' && c <= 'Z')\n        c -= diff;\n\n    return str;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/709.html",
    "category": "Algorithms",
    "acceptance_rate": 84.12678449615795,
    "topics": [
      "String"
    ],
    "hints": [
      "Most languages support lowercase conversion for a string data type. However, that is certainly not the purpose of the problem. Think about how the implementation of the lowercase function call can be done easily.",
      "<b>Think ASCII!</b>",
      "Think about the different capital letters and their ASCII codes and how that relates to their lowercase counterparts. Does there seem to be any pattern there? Any mathematical relationship that we can use?"
    ],
    "likes": 1927,
    "dislikes": 2789,
    "similar_questions": "[{\"title\": \"Capitalize the Title\", \"titleSlug\": \"capitalize-the-title\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"615.4K\", \"totalSubmission\": \"731.5K\", \"totalAcceptedRaw\": 615395, \"totalSubmissionRaw\": 731509, \"acRate\": \"84.1%\"}",
    "title_pt": "Para Minúsculas",
    "description_pt": "<p>Dada uma string <code>s</code>, retorne <em>a string após substituir cada letra maiúscula pela mesma letra minúscula</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;Hello&quot;\n<strong>Saída:</strong> &quot;hello&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;here&quot;\n<strong>Saída:</strong> &quot;here&quot;\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s = &quot;LOVELY&quot;\n<strong>Saída:</strong> &quot;lovely&quot;\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s.length &lt;= 100</code></li>\n\t<li><code>s</code> consiste em caracteres ASCII imprimíveis.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: A maioria das linguagens oferece suporte à conversão para minúsculas para um tipo de dado string. Entretanto, esse certamente não é o propósito do problema. Pense em como a implementação da chamada da função de minúsculas pode ser feita facilmente.",
      "Dica 2: <b>Pense em ASCII!</b>",
      "Dica 3: Pense nas diferentes letras maiúsculas e em seus códigos ASCII e em como isso se relaciona com suas correspondentes minúsculas. Parece haver algum padrão ali? Alguma relação matemática que possamos usar?"
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "710",
    "paidOnly": false,
    "title": "Random Pick with Blacklist",
    "titleSlug": "random-pick-with-blacklist",
    "url": "https://leetcode.com/problems/random-pick-with-blacklist",
    "description_url": "https://leetcode.com/problems/random-pick-with-blacklist/description/",
    "description": "<p>You are given an integer <code>n</code> and an array of <strong>unique</strong> integers <code>blacklist</code>. Design an algorithm to pick a random integer in the range <code>[0, n - 1]</code> that is <strong>not</strong> in <code>blacklist</code>. Any integer that is in the mentioned range and not in <code>blacklist</code> should be <strong>equally likely</strong> to be returned.</p>\n\n<p>Optimize your algorithm such that it minimizes the number of calls to the <strong>built-in</strong> random function of your language.</p>\n\n<p>Implement the <code>Solution</code> class:</p>\n\n<ul>\n\t<li><code>Solution(int n, int[] blacklist)</code> Initializes the object with the integer <code>n</code> and the blacklisted integers <code>blacklist</code>.</li>\n\t<li><code>int pick()</code> Returns a random integer in the range <code>[0, n - 1]</code> and not in <code>blacklist</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]\n<strong>Output</strong>\n[null, 0, 4, 1, 6, 1, 0, 4]\n\n<strong>Explanation</strong>\nSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n                 // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= blacklist.length &lt;= min(10<sup>5</sup>, n - 1)</code></li>\n\t<li><code>0 &lt;= blacklist[i] &lt; n</code></li>\n\t<li>All the values of <code>blacklist</code> are <strong>unique</strong>.</li>\n\t<li>At most <code>2 * 10<sup>4</sup></code> calls will be made to <code>pick</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/random-pick-with-blacklist/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def __init__(self, N: int, blacklist: List[int]):\n    self.validRange = N - len(blacklist)\n    self.dict = {}\n\n    for b in blacklist:\n      self.dict[b] = -1\n\n    for b in blacklist:\n      if b < self.validRange:\n        while N - 1 in self.dict:\n          N -= 1\n        self.dict[b] = N - 1\n        N -= 1\n\n  def pick(self) -> int:\n    value = randint(0, self.validRange - 1)\n\n    if value in self.dict:\n      return self.dict[value]\n\n    return value",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public Solution(int N, int[] blacklist) {\n    validRange = N - blacklist.length;\n\n    for (final int b : blacklist)\n      map.put(b, -1);\n\n    int maxAvailable = N - 1;\n\n    for (final int b : blacklist)\n      if (b < validRange) {\n        while (map.containsKey(maxAvailable))\n          --maxAvailable;\n        map.put(b, maxAvailable--);\n      }\n  }\n\n  public int pick() {\n    final int num = rand.nextInt(validRange);\n    return map.getOrDefault(num, num);\n  }\n\n  private int validRange;\n  private Map<Integer, Integer> map = new HashMap<>();\n  private Random rand = new Random();\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  Solution(int N, vector<int>& blacklist) : validRange(N - blacklist.size()) {\n    for (const int b : blacklist)\n      map[b] = -1;\n\n    int maxAvailable = N - 1;\n\n    for (const int b : blacklist)\n      if (b < validRange) {\n        while (map.count(maxAvailable))  // Find the slot that haven't been used\n          --maxAvailable;\n        map[b] = maxAvailable--;\n      }\n  }\n\n  int pick() {\n    const int num = rand() % validRange;\n    return map.count(num) ? map[num] : num;\n  }\n\n private:\n  const int validRange;\n  unordered_map<int, int> map;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/710.html",
    "category": "Algorithms",
    "acceptance_rate": 33.80094759675762,
    "topics": [
      "Array",
      "Hash Table",
      "Math",
      "Binary Search",
      "Sorting",
      "Randomized"
    ],
    "hints": [],
    "likes": 884,
    "dislikes": 121,
    "similar_questions": "[{\"title\": \"Random Pick Index\", \"titleSlug\": \"random-pick-index\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Random Pick with Weight\", \"titleSlug\": \"random-pick-with-weight\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Unique Binary String\", \"titleSlug\": \"find-unique-binary-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"47.4K\", \"totalSubmission\": \"140.1K\", \"totalAcceptedRaw\": 47370, \"totalSubmissionRaw\": 140144, \"acRate\": \"33.8%\"}",
    "title_pt": "Sorteio Aleatório com Lista Negra",
    "description_pt": "<p>Você recebe um inteiro <code>n</code> e um array de inteiros <strong>únicos</strong> <code>blacklist</code>. Projete um algoritmo para escolher um inteiro aleatório no intervalo <code>[0, n - 1]</code> que <strong>não</strong> esteja em <code>blacklist</code>. Qualquer inteiro que esteja no intervalo mencionado e não esteja em <code>blacklist</code> deve ter a <strong>mesma probabilidade</strong> de ser retornado.</p>\n\n<p>Otimize seu algoritmo de modo que ele minimize o número de chamadas à função aleatória <strong>nativa</strong> da sua linguagem.</p>\n\n<p>Implemente a classe <code>Solution</code>:</p>\n\n<ul>\n\t<li><code>Solution(int n, int[] blacklist)</code> Inicializa o objeto com o inteiro <code>n</code> e os inteiros em lista negra <code>blacklist</code>.</li>\n\t<li><code>int pick()</code> Retorna um inteiro aleatório no intervalo <code>[0, n - 1]</code> e que não esteja em <code>blacklist</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]\n<strong>Saída</strong>\n[null, 0, 4, 1, 6, 1, 0, 4]\n\n<strong>Explicação</strong>\nSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n                 // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li>\n\t<li><code>0 &lt;= blacklist.length &lt;= min(10<sup>5</sup>, n - 1)</code></li>\n\t<li><code>0 &lt;= blacklist[i] &lt; n</code></li>\n\t<li>Todos os valores de <code>blacklist</code> são <strong>únicos</strong>.</li>\n\t<li>No máximo <code>2 * 10<sup>4</sup></code> chamadas serão feitas a <code>pick</code>.</li>\n</ul>",
    "hints_pt": []
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "712",
    "paidOnly": false,
    "title": "Minimum ASCII Delete Sum for Two Strings",
    "titleSlug": "minimum-ascii-delete-sum-for-two-strings",
    "url": "https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings",
    "description_url": "https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/",
    "description": "<p>Given two strings <code>s1</code> and&nbsp;<code>s2</code>, return <em>the lowest <strong>ASCII</strong> sum of deleted characters to make two strings equal</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;sea&quot;, s2 = &quot;eat&quot;\n<strong>Output:</strong> 231\n<strong>Explanation:</strong> Deleting &quot;s&quot; from &quot;sea&quot; adds the ASCII value of &quot;s&quot; (115) to the sum.\nDeleting &quot;t&quot; from &quot;eat&quot; adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> s1 = &quot;delete&quot;, s2 = &quot;leet&quot;\n<strong>Output:</strong> 403\n<strong>Explanation:</strong> Deleting &quot;dee&quot; from &quot;delete&quot; to turn the string into &quot;let&quot;,\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting &quot;e&quot; from &quot;leet&quot; adds 101[e] to the sum.\nAt the end, both strings are equal to &quot;let&quot;, and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into &quot;lee&quot; or &quot;eet&quot;, we would get answers of 433 or 417, which are higher.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 1000</code></li>\n\t<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/solutions/",
    "solution": null,
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int minimumDeleteSum(String s1, String s2) {\n    final int m = s1.length();\n    final int n = s2.length();\n    // dp[i][j] := min cost to make s1[0..i) and s2[0..j) equal\n    int[][] dp = new int[m + 1][n + 1];\n\n    // Delete s1.charAt(i - 1)\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = dp[i - 1][0] + s1.charAt(i - 1);\n\n    // Delete s2.charAt(j - 1)\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = dp[0][j - 1] + s2.charAt(j - 1);\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (s1.charAt(i - 1) == s2.charAt(j - 1))\n          dp[i][j] = dp[i - 1][j - 1];\n        else\n          dp[i][j] = Math.min(dp[i - 1][j] + s1.charAt(i - 1), dp[i][j - 1] + s2.charAt(j - 1));\n\n    return dp[m][n];\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int minimumDeleteSum(string s1, string s2) {\n    const int m = s1.length();\n    const int n = s2.length();\n    // dp[i][j] := min cost to make s1[0..i) and s2[0..j) equal\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n    // Delete s1[i - 1]\n    for (int i = 1; i <= m; ++i)\n      dp[i][0] = dp[i - 1][0] + s1[i - 1];\n\n    // Delete s2[j - 1]\n    for (int j = 1; j <= n; ++j)\n      dp[0][j] = dp[0][j - 1] + s2[j - 1];\n\n    for (int i = 1; i <= m; ++i)\n      for (int j = 1; j <= n; ++j)\n        if (s1[i - 1] == s2[j - 1])\n          dp[i][j] = dp[i - 1][j - 1];\n        else\n          dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]);\n\n    return dp[m][n];\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/712.html",
    "category": "Algorithms",
    "acceptance_rate": 65.66866428675272,
    "topics": [
      "String",
      "Dynamic Programming"
    ],
    "hints": [
      "Let dp(i, j) be the answer for inputs s1[i:] and s2[j:]."
    ],
    "likes": 4063,
    "dislikes": 108,
    "similar_questions": "[{\"title\": \"Edit Distance\", \"titleSlug\": \"edit-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete Operation for Two Strings\", \"titleSlug\": \"delete-operation-for-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"162.6K\", \"totalSubmission\": \"247.6K\", \"totalAcceptedRaw\": 162613, \"totalSubmissionRaw\": 247626, \"acRate\": \"65.7%\"}",
    "title_pt": "Soma Mínima dos Valores ASCII para Deletar em Duas Strings",
    "description_pt": "<p>Dadas duas strings <code>s1</code> e&nbsp;<code>s2</code>, retorne <em>a menor soma de <strong>ASCII</strong> dos caracteres deletados para tornar as duas strings iguais</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;sea&quot;, s2 = &quot;eat&quot;\n<strong>Saída:</strong> 231\n<strong>Explicação:</strong> Deletar &quot;s&quot; de &quot;sea&quot; adiciona o valor ASCII de &quot;s&quot; (115) à soma.\nDeletar &quot;t&quot; de &quot;eat&quot; adiciona 116 à soma.\nNo final, ambas as strings são iguais, e 115 + 116 = 231 é a menor soma possível para atingir isso.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> s1 = &quot;delete&quot;, s2 = &quot;leet&quot;\n<strong>Saída:</strong> 403\n<strong>Explicação:</strong> Deletar &quot;dee&quot; de &quot;delete&quot; para transformar a string em &quot;let&quot;,\nadiciona 100[d] + 101[e] + 101[e] à soma.\nDeletar &quot;e&quot; de &quot;leet&quot; adiciona 101[e] à soma.\nNo final, ambas as strings são iguais a &quot;let&quot;, e a resposta é 100+101+101+101 = 403.\nSe, em vez disso, transformássemos ambas as strings em &quot;lee&quot; ou &quot;eet&quot;, obteríamos respostas de 433 ou 417, que são maiores.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= s1.length, s2.length &lt;= 1000</code></li>\n\t<li><code>s1</code> e <code>s2</code> consistem de letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Seja dp(i, j) a resposta para as entradas s1[i:] e s2[j:]."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "713",
    "paidOnly": false,
    "title": "Subarray Product Less Than K",
    "titleSlug": "subarray-product-less-than-k",
    "url": "https://leetcode.com/problems/subarray-product-less-than-k",
    "description_url": "https://leetcode.com/problems/subarray-product-less-than-k/description/",
    "description": "<p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than </em><code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [10,5,2,6], k = 100\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3], k = 0\n<strong>Output:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>6</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/subarray-product-less-than-k/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given an array of integers `nums` and an integer `k`; the task is to count the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than `k`. \n\n**Key Observations:**\n1. The problem requires counting valid subarrays, not returning the actual subarrays.\n2. The values in the `nums` array are positive.\n\n---\n\n### Approach 1: Using Sliding Window\n\n#### Intuition\n\nThe brute force method involves finding all the subarrays and then selecting those whose products are less than `k`. However, this approach becomes costly in terms of time complexity, reaching $O(n^2)$.\n\nFor a more efficient approach, let's use the sliding window pattern. This pattern is applicable when the problem entails achieving a goal using subarrays, and individual elements cannot be independently selected.\n\nThe concept behind the sliding window pattern is to maintain a window that continuously expands from the right by adding elements and computing their product until the condition is met. Once the condition is satisfied, we adjust the window by shrinking it from the left until the condition is met again.\n\nAs we slide the window across the array, our objective is to identify all subarrays in the `nums` array where the product of its elements remains less than `k`. For each right position, if the product of the window's elements from left to right is less than `k`, adding the element at the right generates new subarrays with products less than `k`.\n\nThe count of such subarrays is determined by the difference `right - left + 1`, which represents the number of subarrays that end at `right` and start at any element between `right` and `left`, inclusive. In essence, this count encompasses the subarray consisting solely of the current element itself, as well as all possible subarrays extending back to the left boundary of the window (`left`).\n\nConsider an example window containing elements 3, 4, and 5. If we include 6 in the window, we need to count all possible subarrays that end with 6. These subarrays can be formed by starting at any element within the current window and extending to 6. Therefore, the subarrays would be:\n\n- `[6]` (subarray consisting only of 6)\n- `[5, 6]` (subarray starting from 5 and ending at 6)\n- `[4, 5, 6]` (subarray starting from 4 and ending at 6)\n- `[3, 4, 5, 6]` (subarray starting from 3 and ending at 6)\n\nBy calculating `right - left + 1`, we enumerate all subarrays that end with the current element of the window (`nums[right]`). This ensures that we count all possible subarrays as we slide the window across the array. As we can observe, adding element 6 to the window created 4 new subarrays.\n\nThe crucial insight is that once the product becomes less than `k`, all possible subarrays formed by selecting subsets of elements within the current window (from left to right) will also have a product strictly less than `k`.\n\nHence, whenever the product is valid, we add the current window size (`right - left + 1`) to the total count of subarrays.\n\nThe following slideshow provides a clearer insight into the underlying approach:\n\n!?!../Documents/713/713_Sliding_Window.json:1020,500!?!\n\n\n#### Algorithm\n\n- Check if `k` is less than or equal to 1. In this case, no subarrays can have a product less than `k`, so return 0.\n- Initialize the variables `totalCount` to 0, to store the final count of subarrays with a product less than `k`, and `product` to 1, representing the product of elements within the window (initially empty).\n- Use two pointers, `left` and `right`, to define the sliding window. Iterate through the `nums` array using a for loop until `right` reaches the end.\n  - Inside the loop, multiply the current `product` by the element at the right pointer (`nums[right]`). This effectively includes the new element in the window.\n  - While the current `product` is greater than or equal to `k`, the window needs to shrink to exclude elements that make the product exceed or equal to `k`.\n    - Divide the `product` by the element at the left pointer (`nums[left]`).\n    - Increment `left` by 1 to move the window one position to the right, effectively excluding the leftmost element.\n  - Update the `totalCount` by adding the number of valid subarrays with the current window size, which is `right - left + 1`.\n- Return the `totalCount`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/3bqwMaz3/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"3bqwMaz3\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the length of `nums`.\n\n* Time complexity: $O(n)$\n\n    The algorithm iterates through the input array `nums` using a single for loop. Inside the loop, there are nested operations for shrinking the window, but since `left` is incremented a total number of `n` times during the whole array traversal, each element in the array is visited at most twice. \n    \n    The nested loop terminates when the product becomes less than `k`, and this can only happen at most `n` times total (once for each element). Therefore, the overall time complexity is $2n$, which we describe as $O(n)$. \n\n* Space complexity: $O(1)$\n\n    The algorithm uses a constant amount of extra space for variables like `totalCount`, `product`, `left`, and `right`. These variables do not depend on the size of the input array. Therefore, the space complexity is considered constant, denoted as $O(1)$.\n\n---\n\n> **Note:** The below approach is generally not anticipated in an interview setting, as many individuals might not be familiar with logarithmic functions, having either forgotten them or not utilized them extensively. So, it's tough for them to come up with this idea on the spot. Moreover, the sliding window approach remains the optimal solution to this problem.\n\n### Approach 2: Using Binary Search\n\n#### Intuition\n\n[Logarithms](https://en.wikipedia.org/wiki/Logarithm) have the property that the sum of logarithms is exactly equal to the logarithm of the product: $\\log(a) + \\log(b) = \\log(ab)$. This property allows us to convert the product of elements in a subarray into the sum of the logarithms of those elements.\n\nThe motivation for this is that the product of some arbitrary subarray may be way too large (potentially $1000^{50000}$).\n\nInteger overflow occurs when the result of an arithmetic operation exceeds the maximum value represented by the data type. This can happen when computing the product of elements in a large subarray, as the result can quickly surpass the integer's capacity, leading to incorrect values due to overflow.\n\nTo mitigate this, we can convert the product operation into a summation of logarithms. Logarithms allow the representation of large values within a manageable range, minimizing the risk of overflow while maintaining accuracy.\n\nThe first step is to transform the problem from finding products to finding sums. This is done by taking the natural logarithm (log) of each element in the array.\n\nThen a prefix sum array (`logsPrefixSum`) is calculated, where each element is the sum of the logarithms of all elements up to that point in the original array. This will allow us to quickly determine if a subarray's sum of logarithms is less than a certain value. Because the prefix sum is a monotonically increasing array, we can use binary search to find valid subarrays.\n\nFor each element in the array, a binary search is performed to find the number of subarrays starting from that element whose sum of logarithms is less than the sum of the logarithms of the current element and `log(K)`. This is done by comparing the midpoint of the search space with the sum of the logarithms of the current element and `log(K)`. If the midpoint is too high, the search space is narrowed to the left; otherwise, it's narrowed to the right. The number of subarrays found is added to the total count.\n\nLogarithmic comparisons have an issue due to the finite precision in floating-point number representation. That is, logarithmic functions can lead to very small differences between numbers that should be equal, especially when dealing with large or small values.\n\nThe product rule is $\\log(a \\cdot b) == \\log(a) + \\log(b)$, but these expressions may not be evaluated as equivalent due to floating-point representation in the computer. It may be $\\log(a \\cdot b) > \\log(a) + \\log(b)$ or $\\log(a \\cdot b) < \\log(a) + \\log(b)$ . When we transform `x` to `log(x)`, we introduce a possible bug.\n\nTo prevent this from causing an issue, we subtract `1e-9` (which is a very small number, 0.000000001), in the comparison condition as a precautionary measure to handle potential precision issues that might arise due to the nature of logarithmic values. This helps mitigate the effect of these precision errors by providing a small buffer or tolerance in the comparison. Even though logarithmic values tend to spread out differences across a wider range, there can still be cases where very close values need to be distinguished, and small discrepancies can occur due to finite precision.\n\nIn essence, it ensures that if `logsPrefixSum[mid]` is very close to `logsPrefixSum[i] + logK`, the former will still be considered less than the latter rather than failing the condition due to slight numerical discrepancies.\n\nThis kind of adjustment is common in numerical math computations where precision matters, especially in conditional algorithms where small discrepancies could lead to incorrect results or sometimes infinite loops.\n\n#### Algorithm\n \n- Check if `k` (target product) is 0. If true, return 0 (no subarrays possible).\n- Calculate the logarithm of `k` and store it in `logK`.\n- Create a vector `logsPrefixSum` of size `nums.size() + 1` to store the prefix sum of logarithms of elements in `nums`.\n- Calculate the prefix sum by iterating over `nums` and adding the logarithm of each element to the previous prefix sum. This creates a running sum of logarithms for efficient product calculation later.\n- Initialize `totalCount` to 0, which will keep track of the total number of subarrays with a product less than `k`.\n- Iterate through `logsPrefixSum` using a loop with index `currIdx`. This loop considers each element (`nums[currIdx]`) as the starting point of a potential subarray.\n  - Inside the loop, initialize two variables, `low` and `high`, to `currIdx + 1` and `m (nums.size() + 1)`, respectively.\n  - Enter a binary search loop to find the first element in `logsPrefixSum` where the subarray product (based on logarithms) exceeds `k`.\n    - Calculate the middle index `mid` between `low` and `high`.\n    - Compare the prefix sum at `mid` with the target prefix sum (`logsPrefixSum[currIdx] + logK`). Here, a small tolerance (`-1e-9`) is used to handle floating-point precision issues.\n    - If the prefix sum at `mid` is less than the target, it means the subarray product ending at `mid` might still be less than `k`.\n      - Move `low` to `mid + 1` to search in the right half of the remaining subarray.\n    - Otherwise, the subarray product ending at `mid` or elements beyond `mid` might exceed `k`.\n      - Move `high` to `mid` to continue searching in the left half for the first exceeding element.\n  - After the binary search loop, the `low` index points to the first element in `logsPrefixSum` where the subarray product (based on logarithms) exceeds `k`. Increment `totalCount` by the number of elements between `currIdx` (inclusive) and `low` (exclusive). This represents the number of valid subarrays ending at `currIdx` with a product less than `k`.\n- Finally, return `totalCount`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/Ja6nxkvo/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"Ja6nxkvo\"></iframe>\n\n#### Complexity Analysis\n\nLet `n` be the length of the `nums` array.\n\n* Time complexity: $O(n \\cdot \\log(n))$\n\n    The time complexity of the overall algorithm is $O(n \\cdot \\log(n))$ due to the binary search performed in each iteration of the outer loop.\n\n* Space complexity: $O(n)$\n\n    The space complexity is $O(n)$ due to the list `logsPrefixSum`, storing logarithmic prefix sums of `nums`, whose length equals that of `nums`.\n\n---\n\n<details>\n<summary><b>Click Here for Discussion on the Tradeoffs of the Approaches</b></summary>\n\n- The sliding window approach is efficient for finding subarrays with a product less than a given value, but it relies on the fact that the integers in the array are positive. This is because when multiplying positive integers, the product will always be positive, and the product of any number of positive integers will also be positive.\n\n- On the other hand, the binary search approach is more versatile and can handle arrays containing both positive and negative integers with some modifications. This is because it operates on the logarithms of the elements rather than the elements themselves.\n\n- After transforming the elements into their logarithmic values, the algorithm compares these values to determine the subarrays with a product less than `k`. However, direct logarithmic values of negative numbers are not defined in the real number scale. Therefore, to handle negative numbers, appropriate shifting of the elements may be necessary to ensure that the logarithmic values used in the algorithm are valid and meaningful.\n\n</details>",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n    if k <= 1:\n      return 0\n\n    ans = 0\n    prod = 1\n\n    j = 0\n    for i, num in enumerate(nums):\n      prod *= num\n      while prod >= k:\n        prod /= nums[j]\n        j += 1\n      ans += i - j + 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int numSubarrayProductLessThanK(int[] nums, int k) {\n    if (k <= 1)\n      return 0;\n\n    int ans = 0;\n    int prod = 1;\n\n    for (int l = 0, r = 0; r < nums.length; ++r) {\n      prod *= nums[r];\n      while (prod >= k)\n        prod /= nums[l++];\n      ans += r - l + 1;\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int numSubarrayProductLessThanK(vector<int>& nums, int k) {\n    if (k <= 1)\n      return 0;\n\n    int ans = 0;\n    int prod = 1;\n\n    for (int l = 0, r = 0; r < nums.size(); ++r) {\n      prod *= nums[r];\n      while (prod >= k)\n        prod /= nums[l++];\n      ans += r - l + 1;\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/713.html",
    "category": "Algorithms",
    "acceptance_rate": 52.742167837864486,
    "topics": [
      "Array",
      "Binary Search",
      "Sliding Window",
      "Prefix Sum"
    ],
    "hints": [
      "For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k.  opt is an increasing function."
    ],
    "likes": 7138,
    "dislikes": 226,
    "similar_questions": "[{\"title\": \"Maximum Product Subarray\", \"titleSlug\": \"maximum-product-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Size Subarray Sum Equals k\", \"titleSlug\": \"maximum-size-subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum Less Than K\", \"titleSlug\": \"two-sum-less-than-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Smooth Descent Periods of a Stock\", \"titleSlug\": \"number-of-smooth-descent-periods-of-a-stock\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Subarrays With Score Less Than K\", \"titleSlug\": \"count-subarrays-with-score-less-than-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"492.1K\", \"totalSubmission\": \"932.9K\", \"totalAcceptedRaw\": 492053, \"totalSubmissionRaw\": 932942, \"acRate\": \"52.7%\"}",
    "title_pt": "Produto de Subarray Menor que K",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>o número de subarrays contíguos nos quais o produto de todos os elementos no subarray é estritamente menor que </em><code>k</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [10,5,2,6], k = 100\n<strong>Saída:</strong> 8\n<strong>Explicação:</strong> Os 8 subarrays que têm produto menor que 100 são:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nObserve que [10, 5, 2] não é incluído, pois o produto de 100 não é estritamente menor que k.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3], k = 0\n<strong>Saída:</strong> 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>\n\t<li><code>0 &lt;= k &lt;= 10<sup>6</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Para cada j, defina opt(j) como o menor i tal que nums[i] * nums[i+1] * ... * nums[j] seja menor que k. opt é uma função crescente."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "714",
    "paidOnly": false,
    "title": "Best Time to Buy and Sell Stock with Transaction Fee",
    "titleSlug": "best-time-to-buy-and-sell-stock-with-transaction-fee",
    "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee",
    "description_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/",
    "description": "<p>You are given an array <code>prices</code> where <code>prices[i]</code> is the price of a given stock on the <code>i<sup>th</sup></code> day, and an integer <code>fee</code> representing a transaction fee.</p>\n\n<p>Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.</p>\n\n<p><strong>Note:</strong></p>\n\n<ul>\n\t<li>You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).</li>\n\t<li>The transaction fee is only charged once for each stock purchase and sale.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1,3,2,8,4,9], fee = 2\n<strong>Output:</strong> 8\n<strong>Explanation:</strong> The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> prices = [1,3,7,5,10,3], fee = 3\n<strong>Output:</strong> 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= prices[i] &lt; 5 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= fee &lt; 5 * 10<sup>4</sup></code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def maxProfit(self, prices: List[int], fee: int) -> int:\n    sell = 0\n    hold = -math.inf\n\n    for price in prices:\n      sell = max(sell, hold + price)\n      hold = max(hold, sell - price - fee)\n\n    return sell",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int maxProfit(int[] prices, int fee) {\n    int sell = 0;\n    int hold = Integer.MIN_VALUE;\n\n    for (final int price : prices) {\n      sell = Math.max(sell, hold + price);\n      hold = Math.max(hold, sell - price - fee);\n    }\n\n    return sell;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int maxProfit(vector<int>& prices, int fee) {\n    int sell = 0;\n    int hold = INT_MIN;\n\n    for (const int price : prices) {\n      sell = max(sell, hold + price);\n      hold = max(hold, sell - price - fee);\n    }\n\n    return sell;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/714.html",
    "category": "Algorithms",
    "acceptance_rate": 70.25721963149589,
    "topics": [
      "Array",
      "Dynamic Programming",
      "Greedy"
    ],
    "hints": [
      "Consider the first K stock prices.  At the end, the only legal states are that you don't own a share of stock, or that you do.  Calculate the most profit you could have under each of these two cases."
    ],
    "likes": 7383,
    "dislikes": 227,
    "similar_questions": "[{\"title\": \"Best Time to Buy and Sell Stock II\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"471.4K\", \"totalSubmission\": \"671K\", \"totalAcceptedRaw\": 471410, \"totalSubmissionRaw\": 670978, \"acRate\": \"70.3%\"}",
    "title_pt": "Melhor Momento para Comprar e Vender Ações com Taxa de Transação",
    "description_pt": "<p>Você recebe um array <code>prices</code> em que <code>prices[i]</code> é o preço de uma determinada ação no <code>i<sup>th</sup></code> dia, e um inteiro <code>fee</code> representando uma taxa de transação.</p>\n\n<p>Encontre o lucro máximo que você pode obter. Você pode realizar quantas transações quiser, mas precisa pagar a taxa de transação para cada transação.</p>\n\n<p><strong>Nota:</strong></p>\n\n<ul>\n\t<li>Você não pode realizar múltiplas transações simultaneamente (ou seja, você deve vender a ação antes de comprar novamente).</li>\n\t<li>A taxa de transação é cobrada apenas uma vez para cada compra e venda de ação.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1,3,2,8,4,9], fee = 2\n<strong>Saída:</strong> 8\n<strong>Explicação:</strong> O lucro máximo pode ser obtido por:\n- Comprando em prices[0] = 1\n- Vendendo em prices[3] = 8\n- Comprando em prices[4] = 4\n- Vendendo em prices[5] = 9\nO lucro total é ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> prices = [1,3,7,5,10,3], fee = 3\n<strong>Saída:</strong> 6\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= prices.length &lt;= 5 * 10<sup>4</sup></code></li>\n\t<li><code>1 &lt;= prices[i] &lt; 5 * 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= fee &lt; 5 * 10<sup>4</sup></code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Considere os primeiros K preços das ações. No final, os únicos estados legais são que você não possui nenhuma ação, ou que você possui. Calcule o maior lucro que você poderia ter em cada um desses dois casos."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "715",
    "paidOnly": false,
    "title": "Range Module",
    "titleSlug": "range-module",
    "url": "https://leetcode.com/problems/range-module",
    "description_url": "https://leetcode.com/problems/range-module/description/",
    "description": "<p>A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as <strong>half-open intervals</strong> and query about them.</p>\n\n<p>A <strong>half-open interval</strong> <code>[left, right)</code> denotes all the real numbers <code>x</code> where <code>left &lt;= x &lt; right</code>.</p>\n\n<p>Implement the <code>RangeModule</code> class:</p>\n\n<ul>\n\t<li><code>RangeModule()</code> Initializes the object of the data structure.</li>\n\t<li><code>void addRange(int left, int right)</code> Adds the <strong>half-open interval</strong> <code>[left, right)</code>, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval <code>[left, right)</code> that are not already tracked.</li>\n\t<li><code>boolean queryRange(int left, int right)</code> Returns <code>true</code> if every real number in the interval <code>[left, right)</code> is currently being tracked, and <code>false</code> otherwise.</li>\n\t<li><code>void removeRange(int left, int right)</code> Stops tracking every real number currently being tracked in the <strong>half-open interval</strong> <code>[left, right)</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input</strong>\n[&quot;RangeModule&quot;, &quot;addRange&quot;, &quot;removeRange&quot;, &quot;queryRange&quot;, &quot;queryRange&quot;, &quot;queryRange&quot;]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\n<strong>Output</strong>\n[null, null, null, true, false, true]\n\n<strong>Explanation</strong>\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= left &lt; right &lt;= 10<sup>9</sup></code></li>\n\t<li>At most <code>10<sup>4</sup></code> calls will be made to <code>addRange</code>, <code>queryRange</code>, and <code>removeRange</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/range-module/solutions/",
    "solution": "[TOC]\n\n\n### Approach #1: Maintain Sorted Disjoint Intervals [Accepted]\n\n**Intuition**\n\nBecause `left, right < 10^9`, we need to deal with the coordinates abstractly. Let's maintain some sorted structure of disjoint intervals. These intervals will be closed (eg. we don't store `[[1, 2], [2, 3]]`; we would store `[[1, 3]]` instead.)\n\nIn this article, we will go over Python and Java versions separately, as the data structures available to us that are relevant to the problem are substantially different.\n\n**Algorithm**\n\nWe will maintain the structure as a *list* `self.ranges = []`.  \n\n*Adding a Range*\n\nWhen we want to add a range, we first find the indices `i, j = self._bounds(left, right)` for which `self.ranges[i: j+1]` touches (in a closed sense - not half open) the given interval `[left, right]`. We can find this in log time by making steps of size 100, 10, then 1 in our linear search from both sides.\n\nEvery interval touched by `[left, right]` will be replaced by the single interval `[min(left, self.ranges[i][0]), max(right, self.ranges[j][1])]`.\n\n*Removing a Range*\n\nAgain, we use `i, j = self._bounds(...)` to only work in the relevant subset of `self.ranges` that is in the neighborhood of our given range `[left, right)`. For each interval `[x, y)` from `self.ranges[i:j+1]`, we may have some subset of that interval to the left and/or right of `[left, right)`. We replace our current interval `[x, y)` with those (up to 2) new intervals.\n\n*Querying a Range*\n\nAs the intervals are sorted, we use binary search to find the single interval that could intersect `[left, right)`, then verify that it does.\n\n<iframe src=\"https://leetcode.com/playground/2cwAuDxK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"2cwAuDxK\"></iframe>\n\n---\n\n**Algorithm (Java)**\n\nWe will maintain the structure as a *TreeSet* `ranges = new TreeSet<Interval>();`. We introduce a new *Comparable* class `Interval` to represent our half-open intervals. They compare by *right-most* coordinate as later we will see that it simplifies our work. Also note that this ordering is consistent with equals, which is important when dealing with *Sets*.\n\n*Adding and Removing a Range*\n\nThe basic structure of adding and removing a range is the same.  First, we must iterate over the relevant subset of `ranges`. This is done using iterators so that we can `itr.remove` on the fly, and break when the intervals go too far to the right.\n\nThe critical logic of `addRange` is simply to make `left, right` the smallest and largest seen coordinates. After, we add one giant interval representing the union of all intervals seen that touched `[left, right]`.\n\nThe logic of `removeRange` is to remember in `todo` the intervals we wanted to replace the removed interval with. After, we can add them all back in.\n\n*Querying a Range*\n\nAs the intervals are sorted, we search to find the single interval that could intersect `[left, right)`, then verify that it does. As the TreeSet uses a balanced (red-black) tree, this has logarithmic complexity.\n\n<iframe src=\"https://leetcode.com/playground/inESDPPR/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"inESDPPR\"></iframe>\n\n**Complexity Analysis**\n\n* Time Complexity: Let $$K$$ be the number of elements in `ranges`. `addRange` and `removeRange` operations have $$O(K)$$ complexity. `queryRange` has $$O(\\log K)$$ complexity. Because `addRange, removeRange` adds at most 1 interval at a time, you can bound these further. For example, if there are $$A$$ `addRange`, $$R$$ `removeRange`, and $$Q$$ `queryRange` number of operations respectively, we can express our complexity as $$O((A+R)^2 Q \\log(A+R))$$. \n\n* Space Complexity: $$O(A+R)$$, the space used by `ranges`.",
    "solution_code_python": "\t\t\t\n\nclass RangeModule {\n  public void addRange(int left, int right) {\n    Integer l = ranges.floorKey(left);\n    Integer r = ranges.floorKey(right);\n\n    if (l != null && ranges.get(l) >= left)\n      left = l;\n    if (r != null && ranges.get(r) > right)\n      right = ranges.get(r);\n\n    ranges.subMap(left, right).clear();\n    ranges.put(left, right);\n  }\n\n  public boolean queryRange(int left, int right) {\n    Integer l = ranges.floorKey(left);\n    return l == null ? false : ranges.get(l) >= right;\n  }\n\n  public void removeRange(int left, int right) {\n    Integer l = ranges.floorKey(left);\n    Integer r = ranges.floorKey(right);\n\n    if (r != null && ranges.get(r) > right)\n      ranges.put(right, ranges.get(r));\n    if (l != null && ranges.get(l) > left)\n      ranges.put(l, left);\n\n    ranges.subMap(left, right).clear();\n  }\n\n  private TreeMap<Integer, Integer> ranges = new TreeMap<>();\n}",
    "solution_code_java": "\t\t\t\n\nclass RangeModule {\n public:\n  void addRange(int left, int right) {\n    const auto [l, r] = getOverlapRanges(left, right);\n    if (l == r) {            // No overlaps\n      ranges[left] = right;  // Add a new range\n      return;\n    }\n\n    auto last = r;\n    const int newLeft = min(l->first, left);\n    const int newRight = max((--last)->second, right);\n    ranges.erase(l, r);\n    ranges[newLeft] = newRight;  // Add a new range\n  }\n\n  bool queryRange(int left, int right) {\n    auto it = ranges.upper_bound(left);\n    return it != begin(ranges) && (--it)->second >= right;\n  }\n\n  void removeRange(int left, int right) {\n    const auto [l, r] = getOverlapRanges(left, right);\n    if (l == r)  // No overlaps\n      return;\n\n    auto last = r;\n    const int newLeft = min(l->first, left);\n    const int newRight = max((--last)->second, right);\n    ranges.erase(l, r);\n    // Add new ranges if needed\n    if (newLeft < left)\n      ranges[newLeft] = left;\n    if (right < newRight)\n      ranges[right] = newRight;\n  }\n\n private:\n  using IT = map<int, int>::iterator;\n  map<int, int> ranges;\n\n  pair<IT, IT> getOverlapRanges(int left, int right) {\n    // Point to 1st element with second >= than left\n    IT l = ranges.upper_bound(left);\n    // Point to 1st element with first > than right\n    IT r = ranges.upper_bound(right);\n    if (l != begin(ranges) && (--l)->second < left)\n      ++l;\n    return {l, r};\n  }\n};",
    "solution_code_cpp": "\t\t\t\n\nstruct SegmentTreeNode {\n  int lo;\n  int hi;\n  bool tracked = false;\n  SegmentTreeNode* left;\n  SegmentTreeNode* right;\n  SegmentTreeNode(int lo, int hi, bool tracked, SegmentTreeNode* left = nullptr,\n                  SegmentTreeNode* right = nullptr)\n      : lo(lo), hi(hi), tracked(tracked), left(left), right(right) {}\n  ~SegmentTreeNode() {\n    delete left;\n    delete right;\n    left = nullptr;\n    right = nullptr;\n  }\n};\n\nclass SegmentTree {\n public:\n  SegmentTree() : root(make_unique<SegmentTreeNode>(0, 1e9, false)) {}\n\n  void addRange(int i, int j) {\n    update(root.get(), i, j, true);\n  }\n\n  bool queryRange(int i, int j) {\n    return query(root.get(), i, j);\n  }\n\n  void removeRange(int i, int j) {\n    update(root.get(), i, j, false);\n  }\n\n private:\n  std::unique_ptr<SegmentTreeNode> root;\n\n  void update(SegmentTreeNode* root, int i, int j, bool tracked) {\n    if (root->lo == i && root->hi == j) {\n      root->tracked = tracked;\n      root->left = nullptr;\n      root->right = nullptr;\n      return;\n    }\n    const int mid = root->lo + (root->hi - root->lo) / 2;\n    if (root->left == nullptr) {\n      root->left = new SegmentTreeNode(root->lo, mid, root->tracked);\n      root->right = new SegmentTreeNode(mid + 1, root->hi, root->tracked);\n    }\n    if (j <= mid)\n      update(root->left, i, j, tracked);\n    else if (i > mid)\n      update(root->right, i, j, tracked);\n    else {\n      update(root->left, i, mid, tracked);\n      update(root->right, mid + 1, j, tracked);\n    }\n    root->tracked = root->left->tracked && root->right->tracked;\n  }\n\n  bool query(SegmentTreeNode* root, int i, int j) {\n    if (root->left == nullptr)\n      return root->tracked;\n    if (root->lo == i && root->hi == j)\n      return root->tracked;\n    const int mid = root->lo + (root->hi - root->lo) / 2;\n    if (j <= mid)\n      return query(root->left, i, j);\n    if (i > mid)\n      return query(root->right, i, j);\n    return query(root->left, i, mid) && query(root->right, mid + 1, j);\n  }\n};\n\nclass RangeModule {\n public:\n  void addRange(int left, int right) {\n    tree.addRange(left, right - 1);\n  }\n\n  bool queryRange(int left, int right) {\n    return tree.queryRange(left, right - 1);\n  }\n\n  void removeRange(int left, int right) {\n    tree.removeRange(left, right - 1);\n  }\n\n private:\n  SegmentTree tree;\n};",
    "solution_code_url": "https://leetcodehelp.github.io/715.html",
    "category": "Algorithms",
    "acceptance_rate": 44.14963415530291,
    "topics": [
      "Design",
      "Segment Tree",
      "Ordered Set"
    ],
    "hints": [
      "Maintain a sorted set of disjoint intervals.  addRange and removeRange can be performed with time complexity linear to the size of this set; queryRange can be performed with time complexity logarithmic to the size of this set."
    ],
    "likes": 1557,
    "dislikes": 132,
    "similar_questions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insert Interval\", \"titleSlug\": \"insert-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Data Stream as Disjoint Intervals\", \"titleSlug\": \"data-stream-as-disjoint-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"84.1K\", \"totalSubmission\": \"190.5K\", \"totalAcceptedRaw\": 84113, \"totalSubmissionRaw\": 190518, \"acRate\": \"44.1%\"}",
    "title_pt": "Módulo de Intervalos",
    "description_pt": "<p>Um Módulo de Intervalos é um módulo que rastreia intervalos de números. Projete uma estrutura de dados para rastrear os intervalos representados como <strong>intervalos semiabertos</strong> e consultar sobre eles.</p>\n\n<p>Um <strong>intervalo semiaberto</strong> <code>[left, right)</code> denota todos os números reais <code>x</code> em que <code>left &lt;= x &lt; right</code>.</p>\n\n<p>Implemente a classe <code>RangeModule</code>:</p>\n\n<ul>\n\t<li><code>RangeModule()</code> Inicializa o objeto da estrutura de dados.</li>\n\t<li><code>void addRange(int left, int right)</code> Adiciona o <strong>intervalo semiaberto</strong> <code>[left, right)</code>, rastreando todo número real nesse intervalo. Adicionar um intervalo que se sobrepõe parcialmente com números atualmente rastreados deve adicionar quaisquer números no intervalo <code>[left, right)</code> que ainda não estejam rastreados.</li>\n\t<li><code>boolean queryRange(int left, int right)</code> Retorna <code>true</code> se todo número real no intervalo <code>[left, right)</code> estiver atualmente sendo rastreado, e <code>false</code> caso contrário.</li>\n\t<li><code>void removeRange(int left, int right)</code> Para de rastrear todo número real atualmente sendo rastreado no <strong>intervalo semiaberto</strong> <code>[left, right)</code>.</li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada</strong>\n[&quot;RangeModule&quot;, &quot;addRange&quot;, &quot;removeRange&quot;, &quot;queryRange&quot;, &quot;queryRange&quot;, &quot;queryRange&quot;]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\n<strong>Saída</strong>\n[null, null, null, true, false, true]\n\n<strong>Explicação</strong>\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // retorna True,(Todo número em [10, 14) está sendo rastreado)\nrangeModule.queryRange(13, 15); // retorna False,(Números como 14, 14.03, 14.17 em [13, 15) não estão sendo rastreados)\nrangeModule.queryRange(16, 17); // retorna True, (O número 16 em [16, 17) ainda está sendo rastreado, apesar da operação de remoção)\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= left &lt; right &lt;= 10<sup>9</sup></code></li>\n\t<li>No máximo <code>10<sup>4</sup></code> chamadas serão feitas para <code>addRange</code>, <code>queryRange</code> e <code>removeRange</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Mantenha um conjunto ordenado de intervalos disjuntos. <code>addRange</code> e <code>removeRange</code> podem ser executados com complexidade de tempo linear ao tamanho desse conjunto; <code>queryRange</code> pode ser executado com complexidade de tempo logarítmica ao tamanho desse conjunto."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "717",
    "paidOnly": false,
    "title": "1-bit and 2-bit Characters",
    "titleSlug": "1-bit-and-2-bit-characters",
    "url": "https://leetcode.com/problems/1-bit-and-2-bit-characters",
    "description_url": "https://leetcode.com/problems/1-bit-and-2-bit-characters/description/",
    "description": "<p>We have two special characters:</p>\n\n<ul>\n\t<li>The first character can be represented by one bit <code>0</code>.</li>\n\t<li>The second character can be represented by two bits (<code>10</code> or <code>11</code>).</li>\n</ul>\n\n<p>Given a binary array <code>bits</code> that ends with <code>0</code>, return <code>true</code> if the last character must be a one-bit character.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> bits = [1,0,0]\n<strong>Output:</strong> true\n<strong>Explanation:</strong> The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> bits = [1,1,1,0]\n<strong>Output:</strong> false\n<strong>Explanation:</strong> The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= bits.length &lt;= 1000</code></li>\n\t<li><code>bits[i]</code> is either <code>0</code> or <code>1</code>.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/1-bit-and-2-bit-characters/solutions/",
    "solution": "[TOC]\n\n\n### Approach 1: Increment Pointer\n\n#### Intuition\n\nWhen reading from the `i`-th position, if `bits[i] == 0`, the next character must be at `i + 1`, because `0` is 1-bit; else if `bits[i] == 1`, the next character must be at `i + 2`, because `1` is only present in 2-bit characters `10` and `11`. We increment our read-pointer `i` to the start of the next character appropriately. At the end, if our pointer is at `bits.length - 1`, then the last character must have a size of 1 bit.\n\n<iframe src=\"https://leetcode.com/playground/ihUtaXrn/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"ihUtaXrn\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `bits`.\n\n* Space Complexity: $$O(1)$$, the space used by `i`.\n\n---\n\n### Approach 2: Greedy\n\n#### Intuition\n\nTo find if the last character in the array is a one-bit character, we can use a parity-based approach. First, we remove the last element, which is the character we want to check. We then initialize a `parity` variable and iterate backward through the array. Each time we encounter a `1`, we toggle `parity` with `parity ^= 1`, effectively flipping its value. This toggle allows us to track whether the number of `1`s is odd or even.\n\nAt the end, if `parity` is `0`, it indicates the last character is a one-bit character; if `parity` is `1`, it’s part of a two-bit sequence.\n\n<iframe src=\"https://leetcode.com/playground/LJvGDaaa/shared\" frameBorder=\"0\" width=\"100%\" height=\"225\" name=\"LJvGDaaa\"></iframe>\n\n#### Complexity Analysis\n\n* Time Complexity: $$O(N)$$, where $$N$$ is the length of `bits`.\n\n* Space Complexity: $$O(1)$$, the space used by `parity` (or `i`).",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def isOneBitCharacter(self, bits: List[int]) -> bool:\n    i = 0\n    while i < len(bits) - 1:\n      i += bits[i] + 1\n\n    return i == len(bits) - 1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public boolean isOneBitCharacter(int[] bits) {\n    final int n = bits.length;\n\n    int i = 0;\n    while (i < n - 1)\n      if (bits[i] == 0)\n        i += 1;\n      else\n        i += 2;\n\n    return i == n - 1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  bool isOneBitCharacter(vector<int>& bits) {\n    const int n = bits.size();\n\n    int i = 0;\n    while (i < n - 1)\n      if (bits[i] == 0)\n        i += 1;\n      else\n        i += 2;\n\n    return i == n - 1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/717.html",
    "category": "Algorithms",
    "acceptance_rate": 45.1146567762319,
    "topics": [
      "Array"
    ],
    "hints": [
      "Keep track of where the next character starts.  At the end, you want to know if you started on the last bit."
    ],
    "likes": 899,
    "dislikes": 2152,
    "similar_questions": "[{\"title\": \"Gray Code\", \"titleSlug\": \"gray-code\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"151.1K\", \"totalSubmission\": \"334.9K\", \"totalAcceptedRaw\": 151075, \"totalSubmissionRaw\": 334869, \"acRate\": \"45.1%\"}",
    "title_pt": "Caracteres de 1 bit e 2 bits",
    "description_pt": "<p>Temos dois caracteres especiais:</p>\n\n<ul>\n\t<li>O primeiro caractere pode ser representado por um bit <code>0</code>.</li>\n\t<li>O segundo caractere pode ser representado por dois bits (<code>10</code> ou <code>11</code>).</li>\n</ul>\n\n<p>Dado um array binário <code>bits</code> que termina com <code>0</code>, retorne <code>true</code> se o último caractere deve ser um caractere de um bit.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> bits = [1,0,0]\n<strong>Saída:</strong> true\n<strong>Explicação:</strong> A única maneira de decodificá-lo é um caractere de dois bits e um caractere de um bit.\nEntão o último caractere é um caractere de um bit.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> bits = [1,1,1,0]\n<strong>Saída:</strong> false\n<strong>Explicação:</strong> A única maneira de decodificá-lo é um caractere de dois bits e um caractere de dois bits.\nEntão o último caractere não é um caractere de um bit.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= bits.length &lt;= 1000</code></li>\n\t<li><code>bits[i]</code> é <code>0</code> ou <code>1</code>.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Acompanhe onde o próximo caractere começa. No final, você quer saber se começou no último bit."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "718",
    "paidOnly": false,
    "title": "Maximum Length of Repeated Subarray",
    "titleSlug": "maximum-length-of-repeated-subarray",
    "url": "https://leetcode.com/problems/maximum-length-of-repeated-subarray",
    "description_url": "https://leetcode.com/problems/maximum-length-of-repeated-subarray/description/",
    "description": "<p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>the maximum length of a subarray that appears in <strong>both</strong> arrays</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong> The repeated subarray with maximum length is [3,2,1].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\n<strong>Output:</strong> 5\n<strong>Explanation:</strong> The repeated subarray with maximum length is [0,0,0,0,0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/maximum-length-of-repeated-subarray/solutions/",
    "solution": "[TOC]\n\n\n### Approach #1: Brute Force with Initial Character Map [Time Limit Exceeded]\n\n**Intuition and Algorithm**\n\nIn a typical brute force, for all starting indices `i` of `A` and `j` of `B`, we will check for the longest matching subarray `A[i: i+k] == B[j: j+k]` of length `k`. This would look roughly like the following pseudocode:\n\n```python\nans = 0\nfor i in [0 .. A.length - 1]:\n    for j in [0 .. B.length - 1]:\n        k = 0\n        while (A[i + k] == B[j + k]): k += 1 #and i + k < A.length etc.\n        ans = max(ans, k)\n```\n\nOur insight is that in typical cases, most of the time `A[i] != B[j]`.  We could instead keep a hashmap `Bstarts[A[i]] = all j such that B[j] == A[i]`, and only loop through those in our `j` loop.\n\n**Python**\n```python\nclass Solution(object):\n    def findLength(self, A, B):\n        ans = 0\n        Bstarts = collections.defaultdict(list)\n        for j, y in enumerate(B):\n            Bstarts[y].append(j)\n\n        for i, x in enumerate(A):\n            for j in Bstarts[x]:\n                k = 0\n                while i + k < len(A) and j + k < len(B) and A[i + k] == B[j + k]:\n                    k += 1\n                ans = max(ans, k)\n        return ans\n```\n\n**Java**\n```java\nclass Solution {\n    public int findLength(int[] A, int[] B) {\n        int ans = 0;\n        Map<Integer, ArrayList<Integer>> Bstarts = new HashMap();\n        for (int j = 0; j < B.length; j++) {\n            Bstarts.computeIfAbsent(B[j], x -> new ArrayList()).add(j);\n        }\n\n        for (int i = 0; i < A.length; i++) if (Bstarts.containsKey(A[i])) {\n            for (int j: Bstarts.get(A[i])) {\n                int k = 0;\n                while (i+k < A.length && j+k < B.length && A[i+k] == B[j+k]) {\n                    k++;\n                }\n                ans = Math.max(ans, k);\n            }\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(M*N*\\min(M, N))$$, where $$M, N$$ are the lengths of `A, B`. The worst case is when all the elements are equal.\n\n* Space Complexity: $$O(N)$$, the space used by `Bstarts` (Of course, we could amend our algorithm to make this $$O(\\min(M, N))$$).\n\n---\n\n### Approach #2: Binary Search with Naive Check [Time Limit Exceeded]\n\n**Intuition**\n\nIf there is a length `k` subarray common to `A` and `B`, then there is a length `j <= k` subarray as well.  \n\nLet `check(length)` be the answer to the question \"Is there a subarray with `length` length, common to `A` and `B`?\"  This is a function with a range that must take the form `[True, True, ..., True, False, False, ..., False]` with at least one `True`.  We can binary search on this function.\n\n**Algorithm**\n\nFocusing on the binary search, our invariant is that `check(hi)` will always be `False`. We'll start with `hi = min(len(A), len(B)) + 1`, clearly `check(hi) is False`.\n\nNow we perform our check in the midpoint `mi` of `lo` and `hi`. When it is possible, then `lo = mi + 1`, and when it isn't, `hi = mi`. This maintains the invariant. At the end of our binary search, `hi == lo` and `lo` is the lowest value such that `check(lo) is False`, so we want `lo - 1`.\n\nAs for the check itself, we can naively check whether any `A[i:i+k] == B[j:j+k]` using set structures.\n\n**Python**\n```python\nclass Solution(object):\n    def findLength(self, A, B):\n        def check(length):\n            seen = set(tuple(A[i:i+length]) \n                       for i in range(len(A) - length + 1))\n            return any(tuple(B[j:j+length]) in seen \n                       for j in range(len(B) - length + 1))\n\n        lo, hi = 0, min(len(A), len(B)) + 1\n        while lo < hi:\n            mi = (lo + hi) // 2\n            if check(mi):\n                lo = mi + 1\n            else:\n                hi = mi\n        return lo - 1\n```\n\n**Java**\n```java\nclass Solution {\n    public boolean check(int length, int[] A, int[] B) {\n        Set<String> seen = new HashSet();\n        for (int i = 0; i + length <= A.length; ++i) {\n            seen.add(Arrays.toString(Arrays.copyOfRange(A, i, i+length)));\n        }\n        for (int j = 0; j + length <= B.length; ++j) {\n            if (seen.contains(Arrays.toString(Arrays.copyOfRange(B, j, j+length)))) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    public int findLength(int[] A, int[] B) {\n        int lo = 0, hi = Math.min(A.length, B.length) + 1;\n        while (lo < hi) {\n            int mi = (lo + hi) / 2;\n            if (check(mi, A, B)) {\n                lo = mi + 1;\n            }\n            else hi = mi;\n        }\n        return lo - 1;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O((M + N) * \\min(M, N) * \\log{(\\min(M, N))})$$, where $$M, N$$ are the lengths of `A, B`. The log factor comes from the binary search. The complexity of our naive check of a given $$\\text{length}$$ is $$O((M+N) * \\text{length})$$, as we will create the `seen` strings with complexity $$O(M * \\text{length})$$, then search for them with complexity $$O(N * \\text{length})$$, and our total complexity when performing our `check` is the addition of these two.\n\n* Space Complexity: $$O(M^2)$$, the space used by `seen`.\n\n---\n\n### Approach #3: Dynamic Programming [Accepted]\n\n**Intuition and Algorithm**\n\nSince a common subarray of `A` and `B` must start at some `A[i]` and `B[j]`, let `dp[i][j]` be the longest common prefix of `A[i:]` and `B[j:]`. Whenever `A[i] == B[j]`, we know `dp[i][j] = dp[i+1][j+1] + 1`.  Also, the answer is `max(dp[i][j])` over all `i, j`.\n\nWe can perform bottom-up dynamic programming to find the answer based on this recurrence. Our loop invariant is that the answer is already calculated correctly and stored in `dp` for any larger `i, j`.\n\n**Python**\n\n```python\nclass Solution(object):\n    def findLength(self, A, B):\n        memo = [[0] * (len(B) + 1) for _ in range(len(A) + 1)]\n        for i in range(len(A) - 1, -1, -1):\n            for j in range(len(B) - 1, -1, -1):\n                if A[i] == B[j]:\n                    memo[i][j] = memo[i + 1][j + 1] + 1\n        return max(max(row) for row in memo)\n```\n\n**Java**\n\n```java\nclass Solution {\n    public int findLength(int[] A, int[] B) {\n        int ans = 0;\n        int[][] memo = new int[A.length + 1][B.length + 1];\n        for (int i = A.length - 1; i >= 0; --i) {\n            for (int j = B.length - 1; j >= 0; --j) {\n                if (A[i] == B[j]) {\n                    memo[i][j] = memo[i+1][j+1] + 1;\n                    if (ans < memo[i][j]) {\n                        ans = memo[i][j];\n                    }\n                }\n            }\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(M*N)$$, where $$M, N$$ are the lengths of `A, B`.\n\n* Space Complexity: $$O(M*N)$$, the space used by `dp`.\n\n---\n\n### Approach #4: Binary Search with Rolling Hash [Accepted]\n\n**Intuition**\n\nAs in *Approach #2*, we will binary search for the answer.  However, we will use a *rolling hash* (Rabin-Karp algorithm) to store hashes in our set structure.\n\n**Algorithm**\n\nFor some prime $$p$$, consider the following function modulo some prime modulus $$\\mathcal{M}$$:\n\n$$\\text{hash}(S) = \\sum_{0 \\leq i < len(S)} p^i * S[i]$$\n\nNotably, $$\\text{hash}(S[1:] + x) = \\frac{(\\text{hash}(S) - S[0])}{p} + p^{n-1} x$$. This shows we can get the hash of all $$A[i:i+\\text{guess}]$$ in linear time.  We will also use the fact that $$p^{-1} = p^{\\mathcal{M}-2} \\mod \\mathcal{M}$$.\n\nFor every `i >= length - 1`, we will want to record the hash of `A[i-length+1], A[i-length+2], ..., A[i]`. After, we will truncate the first element by `h = (h - A[i - (length - 1)]) * Pinv % MOD` to get ready to add the next element.\n\nTo make our algorithm airtight, we also make a naive check when our work with rolling hashes says that we have found a match.\n\n```python\nclass Solution(object):\n    def findLength(self, A, B):\n        P, MOD = 113, 10**9 + 7\n        Pinv = pow(P, MOD - 2, MOD)\n        def check(guess):\n            def rolling(A, length):\n                if length == 0:\n                    yield 0, 0\n                    return\n\n                h, power = 0, 1\n                for i, x in enumerate(A):\n                    h = (h + x * power) % MOD\n                    if i < length - 1:\n                        power = (power * P) % MOD\n                    else:\n                        yield h, i - (length - 1)\n                        h = (h - A[i - (length - 1)]) * Pinv % MOD\n\n            hashes = collections.defaultdict(list)\n            for ha, start in rolling(A, guess):\n                hashes[ha].append(start)\n            for ha, start in rolling(B, guess):\n                iarr = hashes.get(ha, [])\n                if any(A[i: i + guess] == B[start: start + guess] for i in iarr):\n                    return True\n            return False\n\n        lo, hi = 0, min(len(A), len(B)) + 1\n        while lo < hi:\n            mi = (lo + hi) // 2\n            if check(mi):\n                lo = mi + 1\n            else:\n                hi = mi\n        return lo - 1\n```\n\n**Java**\n```java\nimport java.math.BigInteger;\n\nclass Solution {\n    int P = 113;\n    int MOD = 1_000_000_007;\n    int Pinv = BigInteger.valueOf(P).modInverse(BigInteger.valueOf(MOD)).intValue();\n\n    private int[] rolling(int[] source, int length) {\n        int[] ans = new int[source.length - length + 1];\n        long h = 0, power = 1;\n        if (length == 0) {\n            return and;\n        }\n        for (int i = 0; i < source.length; ++i) {\n            h = (h + source[i] * power) % MOD;\n            if (i < length - 1) {\n                power = (power * P) % MOD;\n            } else {\n                ans[i - (length - 1)] = (int) h;\n                h = (h - source[i - (length - 1)]) * Pinv % MOD;\n                if (h < 0) h += MOD;\n            }\n        }\n        return ans;\n    }\n\n    private boolean check(int guess, int[] A, int[] B) {\n        Map<Integer, List<Integer>> hashes = new HashMap();\n        int k = 0;\n        for (int x: rolling(A, guess)) {\n            hashes.computeIfAbsent(x, z -> new ArrayList()).add(k++);\n        }\n        int j = 0;\n        for (int x: rolling(B, guess)) {\n            for (int i: hashes.getOrDefault(x, new ArrayList<Integer>()))\n                if (Arrays.equals(Arrays.copyOfRange(A, i, i+guess),\n                                  Arrays.copyOfRange(B, j, j+guess))) {\n                    return true;\n                }\n            j++;\n        }\n        return false;\n    }\n\n    public int findLength(int[] A, int[] B) {\n        int lo = 0, hi = Math.min(A.length, B.length) + 1;\n        while (lo < hi) {\n            int mi = (lo + hi) / 2;\n            if (check(mi, A, B)) {\n                lo = mi + 1;\n            }\n            else hi = mi;\n        }\n        return lo - 1;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O((M+N) * \\log{(\\min(M, N))})$$, where $$M, N$$ are the lengths of `A, B`. The log factor contributed by the binary search while creating the rolling hashes is $$O(M + N)$$. The checks for duplicate hashes are $$O(1)$$. If we perform a naive check to make sure our answer is correct, it adds a factor of $$O(\\min(M, N))$$ to our cost of `check`, which keeps the complexity the same.\n\n* Space Complexity: $$O(M)$$, the space used to store `hashes` and the subarrays in our final naive check.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n    m = len(nums1)\n    n = len(nums2)\n    ans = 0\n    # dp[i][j] := max length of nums1[i:] and nums2[j:]\n    dp = [[0] * (n + 1) for _ in range(m + 1)]\n\n    for i in reversed(range(m)):\n      for j in reversed(range(n)):\n        if nums1[i] == nums2[j]:\n          dp[i][j] = dp[i + 1][j + 1] + 1\n          ans = max(ans, dp[i][j])\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int findLength(int[] nums1, int[] nums2) {\n    final int m = nums1.length;\n    final int n = nums2.length;\n    int ans = 0;\n    // dp[i][j] := max length of nums1[i:] and nums2[j:]\n    int[][] dp = new int[m + 1][n + 1];\n\n    for (int i = m - 1; i >= 0; --i)\n      for (int j = n - 1; j >= 0; --j)\n        if (nums1[i] == nums2[j]) {\n          dp[i][j] = dp[i + 1][j + 1] + 1;\n          ans = Math.max(ans, dp[i][j]);\n        }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int findLength(vector<int>& nums1, vector<int>& nums2) {\n    const int m = nums1.size();\n    const int n = nums2.size();\n    int ans = 0;\n    // dp[i][j] := max length of nums1[i:] and nums2[j:]\n    vector<vector<int>> dp(m + 1, vector<int>(n + 1));\n\n    for (int i = m - 1; i >= 0; --i)\n      for (int j = n - 1; j >= 0; --j)\n        if (nums1[i] == nums2[j]) {\n          dp[i][j] = dp[i + 1][j + 1] + 1;\n          ans = max(ans, dp[i][j]);\n        }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/718.html",
    "category": "Algorithms",
    "acceptance_rate": 50.99783418204479,
    "topics": [
      "Array",
      "Binary Search",
      "Dynamic Programming",
      "Sliding Window",
      "Rolling Hash",
      "Hash Function"
    ],
    "hints": [
      "Use dynamic programming.  dp[i][j] will be the longest common prefix of A[i:] and B[j:].",
      "The answer is max(dp[i][j]) over all i, j."
    ],
    "likes": 6939,
    "dislikes": 177,
    "similar_questions": "[{\"title\": \"Minimum Size Subarray Sum\", \"titleSlug\": \"minimum-size-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Common Subpath\", \"titleSlug\": \"longest-common-subpath\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of a Good Subsequence II\", \"titleSlug\": \"find-the-maximum-length-of-a-good-subsequence-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Maximum Length of a Good Subsequence I\", \"titleSlug\": \"find-the-maximum-length-of-a-good-subsequence-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"333.9K\", \"totalSubmission\": \"654.7K\", \"totalAcceptedRaw\": 333890, \"totalSubmissionRaw\": 654714, \"acRate\": \"51.0%\"}",
    "title_pt": "Comprimento Máximo de um Subarray Repetido",
    "description_pt": "<p>Dadas duas arrays de inteiros <code>nums1</code> e <code>nums2</code>, retorne <em>o comprimento máximo de um subarray que aparece em <strong>ambas</strong> as arrays</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong> O subarray repetido com comprimento máximo é [3,2,1].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\n<strong>Saída:</strong> 5\n<strong>Explicação:</strong> O subarray repetido com comprimento máximo é [0,0,0,0,0].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>\n\t<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>\n</ul>",
    "hints_pt": [
      "Use programação dinâmica.  <code>dp[i][j]</code> será o maior prefixo comum de <code>A[i:]</code> e <code>B[j:]</code>.",
      "A resposta é <code>max(dp[i][j])</code> para todos <code>i</code>, <code>j</code>."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "719",
    "paidOnly": false,
    "title": "Find K-th Smallest Pair Distance",
    "titleSlug": "find-k-th-smallest-pair-distance",
    "url": "https://leetcode.com/problems/find-k-th-smallest-pair-distance",
    "description_url": "https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/",
    "description": "<p>The <strong>distance of a pair</strong> of integers <code>a</code> and <code>b</code> is defined as the absolute difference between <code>a</code> and <code>b</code>.</p>\n\n<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest <strong>distance among all the pairs</strong></em> <code>nums[i]</code> <em>and</em> <code>nums[j]</code> <em>where</em> <code>0 &lt;= i &lt; j &lt; nums.length</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,3,1], k = 1\n<strong>Output:</strong> 0\n<strong>Explanation:</strong> Here are all the pairs:\n(1,3) -&gt; 2\n(1,1) -&gt; 0\n(3,1) -&gt; 2\nThen the 1<sup>st</sup> smallest distance pair is (1,1), and its distance is 0.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,1,1], k = 2\n<strong>Output:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,6,1], k = 3\n<strong>Output:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= n * (n - 1) / 2</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/find-k-th-smallest-pair-distance/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nThe goal is to find the `k`-th smallest distance between any two different elements in an array `nums`. The distance between two elements `nums[i]` and `nums[j]` is defined as the absolute difference between their values, `|nums[i] - nums[j]|`. We only consider pairs where `i` is less than `j` to avoid counting the same pair twice.\n\nFor example:\n> **Input:** `nums = [1, 3, 1]`, `k = 1`\n> **Output:** `0`\n\nLet's look at all possible pairs of elements and their distances:\n\n1. Pair (1, 3):\n   - Distance: |1 - 3| = 2\n\n2. Pair (1, 1):\n   - Distance: |1 - 1| = 0\n\n3. Pair (3, 1):\n   - Distance: |3 - 1| = 2\n\nSo, the distances are `[2, 0, 2]`.\n\nTo find the `k`-th smallest distance, we sort these distances: `[0, 2, 2]`.\n\nSince `k = 1`, we need the 1st smallest distance, which is `0`.\n\nThus, the result is `0`.\n\nThe brute-force approach involves checking the distance for every possible pair of elements in the array and maintaining the `k` smallest distances using a heap. Specifically, we iterate over all pairs, calculate their absolute distances, and use a max-heap to keep track of the `k` smallest distances. If the heap size exceeds `k`, we remove the largest element. After processing all pairs, the root of the heap will represent the `k-th` smallest distance.\n\nHowever, this method is computationally heavy and will lead to a Time Limit Exceeded (TLE) error. The time complexity is dominated by the need to examine all pairs, which is $O(n^2)$, combined with the overhead of maintaining a heap of size `k`, resulting in an overall time complexity of $O(n^2 \\log k)$, where `n` is the number of elements. This makes the approach impractical for large values of `n`.\n\n---\n\n### Approach 1: Bucket Sort\n\n#### Intuition\n\nGiven that array elements can be as large as `1,000,000`, a direct comparison approach would be computationally expensive. However, since the distances are bounded by the maximum element in the array, we can leverage this property to use a bucket sort approach, which is efficient for problems with a known range of values. This transforms the problem of finding the `k`-th smallest distance into a counting problem within a fixed range.\n\nWe first observe that the range of possible distances is finite and bounded:\n- The minimum distance is 0, occurring when two numbers in the array are identical.\n- The maximum distance is the difference between the largest and smallest numbers in the array.\n\nThis bounded range forms the foundation of our approach. With this range established, we conceptualize a series of \"buckets,\" each representing a specific distance within our range. These buckets serve as counters, allowing us to tally the frequency of each distance without needing to store the actual pairs that produce them. This abstraction significantly reduces memory requirements and computational complexity.\n\nNow for each pair of numbers in the array, calculate the absolute difference and increment the corresponding bucket count.\n\nAfter processing all pairs, our bucket array contains a comprehensive frequency distribution of all distances present in the original array. Now traverse the bucket array from the smallest distance upwards, maintaining a running sum of counts. The distance where this running sum first equals or exceeds is the  k-th smallest distance.\n\n#### Algorithm\n\n- Determine the size of the input array `nums` and store it in `arraySize`.\n\n- Find the maximum element in the array `nums` and store it in `maxElement`.\n\n- Create a bucket array `distanceBucket` with size `maxElement + 1`, initialized to 0, to store the counts of each distance.\n\n- Populate the `distanceBucket` array:\n  - Iterate over all pairs of indices `(i, j)` where `i < j` in the array `nums`.\n    - Calculate the distance between `nums[i]` and `nums[j]` as `abs(nums[i] - nums[j])`.\n    - Increment the count for this distance in the `distanceBucket` array.\n\n- Find the k-th smallest distance:\n  - Iterate over all possible distances from 0 to `maxElement`.\n    - Subtract the count of pairs with the current distance from `k`.\n    - If `k` becomes less than or equal to 0, return the current distance as it is the k-th smallest distance.\n\n- If the function does not return within the loop, return `-1` indicating no distance was found, although this case should not occur with valid inputs.\n\n#### Implementation\n\n> Note: The Python implementation for this approach will encounter a Time Limit Exceeded (TLE) error because Python's inherent slower execution speed.\n\n<iframe src=\"https://leetcode.com/playground/H5scviJc/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"H5scviJc\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of elements and $M$ be the maximum possible distance.\n\n- Time complexity: $O(n^2 + M)$\n\n    The $O(n^2)$ term arises from the nested loops used to calculate all pairwise distances between elements. Since we are examining every possible pair of elements in the array, this results in $n(n-1)/2$ comparisons, which simplifies to $O(n^2)$.\n\n    After calculating all distances, we traverse the `distanceBucket` array to find the k-th smallest distance. This traversal is $O(M)$, where $M$ is the maximum possible distance, which is proportional to the largest element in the array. Thus, the total time complexity is $O(n^2 + M)$, accounting for both the pair distance calculations and the bucket traversal.\n\n- Space complexity: $O(M)$\n\n    The space complexity is dominated by the `distanceBucket` array, which is used to count occurrences of each possible distance. The size of this array is proportional to the maximum possible distance $M$. Aside from this array, the space usage is minimal and does not depend on the number of elements, leading to a space complexity of $O(M)$.\n\n---\n\n### Approach 2: Binary Search + Dynamic Programming (DP)\n\n#### Intuition\n\nWe now explore a sophisticated approach that combines binary search with dynamic programming, especially effective for arrays with a broad range of values where bucket sort might be impractical due to memory constraints.\n\nFirst, recognize that our solution space—the range of possible distances—is bounded. The minimum distance is 0, and the maximum is the difference between the largest and smallest elements in the array. This bounded range allows us to use binary search to efficiently find the `k`-th smallest distance.\n\nOur key insight is that for any given distance `d`, we can count the number of pairs in the array with a distance less than or equal to `d`. If this count is less than `k`, the `k`-th smallest distance must be greater than `d`. Conversely, if the count is at least `k`, the `k`-th smallest distance must be less than or equal to `d`. This forms the basis of our binary search approach.\n\nTo implement this, we first sort the input array. Sorting is crucial because it enables us to efficiently count pairs with distances less than or equal to a given value.\n\nWe then set up our binary search:\n\n- The lower bound of our search range is `0`, and the upper bound is the difference between the maximum and minimum elements in the sorted array.\n- In each iteration, we calculate the midpoint of the current range and count the number of pairs with distances less than or equal to this midpoint.\n\nThe counting process is where dynamic programming comes into play. We use two auxiliary arrays to optimize our pair counting:\n\n1. **prefixCount**: This array maintains the cumulative count of elements up to each value in the sorted array. For any index `i`, `prefixCount[i]` represents the number of elements less than or equal to `i`.\n2. **valueCount**: Implemented as a hash map, `valueCount[i]` stores the count of occurrences of the value `i` in the array.\n\nTo count pairs for a given distance `d`, we iterate through the sorted array. For each element `x`, we calculate:\n\n- The number of elements within distance `d` of `x` using `prefixCount`.\n- The number of pairs formed by duplicate occurrences of `x` using `valueCount`.\n\nBased on the count of pairs at the current midpoint distance, we adjust our binary search range:\n\n- If the count is less than `k`, we need to look at larger distances by adjusting the lower bound.\n- If the count is greater than or equal to `k`, we need to look at smaller distances by adjusting the upper bound.\n\nWe repeat this process, halving the search range each time, until the lower and upper bounds converge, giving us the `k`-th smallest pair distance.\n\n#### Algorithm\n \n- Sort the array `nums` to simplify distance calculations.\n\n- Determine the size of the sorted array `nums` and store it in `arraySize`.\n\n- Find the largest element in the sorted array `nums` and store it in `maxElement`.\n\n- Calculate the maximum possible distance as `maxElement * 2`.\n\n- Initialize arrays and maps:\n  - Create an array `prefixCount` with size `maxPossibleDistance` to store prefix counts of distances.\n  - Create a map `valueCount` to count occurrences of each value in the array.\n\n- Populate the `prefixCount` array:\n  - Iterate through possible distance values from 0 to `maxPossibleDistance - 1`.\n    - For each distance value, determine the number of elements in the array `nums` that are less than or equal to this distance.\n    - Store this count in `prefixCount` for the current distance.\n\n- Populate the `valueCount` map:\n  - Iterate through the array `nums`.\n    - Count occurrences of each value and store in `valueCount`.\n\n- Perform binary search for the k-th smallest distance:\n  - Set `low` to 0 and `high` to `maxElement`.\n  - While `low` is less than `high`:\n    - Calculate the middle point `mid` as `(low + high) / 2`.\n    - Count the number of pairs with distance ≤ `mid` using the helper function `countPairs`.\n    - Adjust the binary search bounds based on whether the count is less than or greater than or equal to `k`.\n\n- Return the smallest distance found by the binary search.\n\n- Helper function `countPairs`:\n  - Count the number of pairs with distance ≤ `maxDistance`:\n    - Iterate through the array `nums`.\n    - Calculate the number of pairs involving the current value that are within the allowed distance.\n    - Accumulate the total count of such pairs.\n  - Return the count of pairs with distance ≤ `maxDistance`.\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/SU4MpYrm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"SU4MpYrm\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of elements and $M$ be the maximum possible distance.\n\n- Time complexity: $O(n \\log n + n \\log M + M)$\n\n    The $O(n \\log n)$ term arises from sorting the array, which is necessary for efficiently calculating distances and performing binary search. Sorting takes $O(n \\log n)$ time.\n    \n    The $O(n \\log M)$ term comes from the binary search over the range of possible distances and counting pairs for each mid-value. Counting pairs involves traversing the array, and the binary search operations are logarithmic with respect to the maximum possible distance $M$. And we populate the `prefixCount` array by iterating through the possible values from 0 to `maxPossibleDistance` - 1 taking $O(M)$. Hence, the combined time complexity is $O(n \\log n + n \\log M + M)$.\n\n- Space complexity: $O(n + M + S)$\n\n    The space complexity includes $O(n)$ for storing the `prefixCount` array and the value counts in the `valueCount` map. The `prefixCount` array tracks the number of elements up to each possible distance, while `valueCount` stores counts of each unique element. Additionally, $O(M)$ is required for the `prefixCount` array. \n    \n    Some extra space is used when we sort an array of size $n$ in place. The space complexity of the sorting algorithm ($S$) depends on the programming language. The value of $S$ depends on the programming language and the sorting algorithm being used:\n    - In Python, the sort method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has a space complexity of $O(n)$\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worst-case space complexity of $O( \\log n )$\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$\n    \n    Thus, the total space complexity of the algorithm is $O(n + M + S)$.\n\n---\n\n### Approach 3: Binary Search + Sliding Window\n\n#### Intuition\n\nThe core idea remains similar to our previous approach: for any given distance `d`, we aim to count the number of pairs in the array with a distance less than or equal to `d`. If this count is less than `k`, we know the `k`-th smallest distance must be greater than `d`. If the count is greater than or equal to `k`, the `k`-th smallest distance must be less than or equal to `d`.\n\nWhere this approach diverges is in how we perform this counting operation. Instead of using pre-computed dynamic programming arrays, we employ a sliding window technique that takes advantage of the sorted nature of our array.\n\nWe begin by sorting the input array and then we set up binary search as before, with the lower bound at 0 and the upper bound at the difference between the maximum and minimum elements in the sorted array. In each iteration of the binary search, we calculate the midpoint of our current range.\n\nThe key innovation in this approach is the sliding window method used to count pairs with distances less than or equal to our current midpoint distance. Here's how it works:\n\n- Start with two pointers, `left` and `right`, both at the start of the array. Move the `right` pointer to check distances.\n- As long as the distance between `right` and `left` is within the allowed range, keep moving `right` forward. Once we find a distance greater than our midpoint, we know that all elements between `left` and `right` (exclusive) form valid pairs with the element at `left`. We add this count to our total and then move the `left` pointer forward. Repeat until all pairs are checked.\n\nThis sliding window technique counts valid pairs in linear time for each binary search iteration. The efficiency arises because the `right` pointer doesn't need to reset for each new `left` position; it continues from where it left off, leveraging the sorted array.\n\nBased on the count of pairs for the current midpoint distance, we adjust our binary search range as follows:\n\n- If the count is less than `k`, we increase the distance by adjusting our lower bound.\n- If the count is greater than or equal to `k`, we decrease the distance by adjusting our upper bound.\n\nWe continue this process, halving our search range each time, until the lower and upper bounds converge. At this point, we identify the `k`-th smallest pair distance.\n\nThe efficiency of this approach is due to the combination of binary search, which reduces the search space logarithmically, and the sliding window technique, which allows us to count pairs in linear time for each binary search iteration, given that the array is sorted.\n\n#### Algorithm\n\n- Sort the array `nums` to simplify distance calculations.\n\n- Determine the size of the sorted array `nums` and store it in `arraySize`.\n\n- Initialize the binary search range:\n  - Set `low` to 0.\n  - Set `high` to the difference between the maximum and minimum elements in `nums` (i.e., `nums[arraySize - 1] - nums[0]`).\n\n- Perform binary search to find the smallest distance:\n  - While `low` is less than `high`:\n    - Calculate the middle point `mid` as `(low + high) / 2`.\n    - Count the number of pairs with distance ≤ `mid` using the helper function `countPairsWithMaxDistance`.\n    - Adjust the binary search bounds:\n      - If the count of pairs is less than `k`, set `low` to `mid + 1`.\n      - Otherwise, set `high` to `mid`.\n\n- Return the smallest distance found by the binary search.\n\n- Helper function `countPairsWithMaxDistance`:\n  - Count the number of pairs with distance ≤ `maxDistance` using a sliding window:\n    - Initialize `count` to 0.\n    - Set `left` pointer to 0.\n    - Iterate with `right` pointer from 0 to the end of the array:\n      - Adjust the `left` pointer to maintain the window where the distance between `nums[right]` and `nums[left]` is ≤ `maxDistance`.\n      - Add the number of valid pairs ending at the current `right` index to `count` (i.e., `right - left`).\n  - Return the total count of pairs with distance ≤ `maxDistance`.\n\nThe algorithm is visualized below:\n\n!?!../Documents/719/approach4.json:980,760!?!\n\n#### Implementation\n\n<iframe src=\"https://leetcode.com/playground/VeCnLoRm/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"VeCnLoRm\"></iframe>\n\n#### Complexity Analysis\n\nLet $n$ be the number of elements and $M$ be the maximum possible distance.\n\n- Time complexity: $O(n \\log M + n \\log n)$\n\n    The $O(n \\log M)$ term arises from the binary search over possible distances, where the search space is up to the maximum possible distance $M$. For each mid-value in the binary search, the `countPairsWithMaxDistance` function is called, which operates in linear time $O(n)$.\n\n    The binary search itself runs in $O(\\log M)$ time. Hence, the combined time complexity is $O(n \\log M + n \\log n)$, where the binary search and pair counting operations are combined.\n\n- Space complexity: $O(S)$\n\n    The space complexity is constant because the algorithm only uses a fixed amount of extra space for the left and right pointers, the mid-value, and counters. It does not require additional data structures that scale with the input size, so the space complexity is $O(1)$, excluding the space used to store the input array.  \n\n    Some extra space is used when we sort an array of size $n$ in place. The space complexity of the sorting algorithm ($S$) depends on the programming language. The value of $S$ depends on the programming language and the sorting algorithm being used:\n    - In Python, the `sort()` method sorts a list using the Timsort algorithm which is a combination of Merge Sort and Insertion Sort and has a space complexity of $O(n)$\n    - In C++, the `sort()` function is implemented as a hybrid of Quick Sort, Heap Sort, and Insertion Sort, with a worst-case space complexity of $O( \\log n )$\n    - In Java, `Arrays.sort()` is implemented using a variant of the Quick Sort algorithm which has a space complexity of $O( \\log n)$\n    \n    Thus, the total space complexity of the algorithm is $O(S)$.\n\n---",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def smallestDistancePair(self, nums: List[int], k: int) -> int:\n    nums.sort()\n\n    l = 0\n    r = nums[-1] - nums[0]\n\n    while l < r:\n      m = (l + r) // 2\n      count = 0\n\n      j = 0\n      for i in range(len(nums)):\n        while j < len(nums) and nums[j] <= nums[i] + m:\n          j += 1\n        count += j - i - 1\n\n      if count < k:\n        l = m + 1\n      else:\n        r = m\n\n    return l",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int smallestDistancePair(int[] nums, int k) {\n    Arrays.sort(nums);\n\n    int l = 0;\n    int r = nums[nums.length - 1] - nums[0];\n\n    while (l < r) {\n      final int m = (l + r) / 2;\n      if (pairDistancesNoGreaterThan(nums, m) >= k)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n\n  private int pairDistancesNoGreaterThan(int[] nums, int m) {\n    int count = 0;\n    int j = 1;\n    // For each index i, find the first index j s.t. nums[j] > nums[i] + m,\n    // So pairDistancesNoGreaterThan for index i will be j - i - 1\n    for (int i = 0; i < nums.length; ++i) {\n      while (j < nums.length && nums[j] <= nums[i] + m)\n        ++j;\n      count += j - i - 1;\n    }\n    return count;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int smallestDistancePair(vector<int>& nums, int k) {\n    sort(begin(nums), end(nums));\n\n    int l = 0;\n    int r = nums.back() - nums.front();\n\n    while (l < r) {\n      const int m = (l + r) / 2;\n      if (pairDistancesNoGreaterThan(nums, m) >= k)\n        r = m;\n      else\n        l = m + 1;\n    }\n\n    return l;\n  }\n\n private:\n  int pairDistancesNoGreaterThan(const vector<int>& nums, int m) {\n    int count = 0;\n    int j = 1;\n    // For each index i, find the first index j s.t. nums[j] > nums[i] + m,\n    // So pairDistancesNoGreaterThan for index i will be j - i - 1\n    for (int i = 0; i < nums.size(); ++i) {\n      while (j < nums.size() && nums[j] <= nums[i] + m)\n        ++j;\n      count += j - i - 1;\n    }\n    return count;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/719.html",
    "category": "Algorithms",
    "acceptance_rate": 45.71708808118743,
    "topics": [
      "Array",
      "Two Pointers",
      "Binary Search",
      "Sorting"
    ],
    "hints": [
      "Binary search for the answer.  How can you check how many pairs have distance <= X?"
    ],
    "likes": 3824,
    "dislikes": 121,
    "similar_questions": "[{\"title\": \"Find K Pairs with Smallest Sums\", \"titleSlug\": \"find-k-pairs-with-smallest-sums\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Element in a Sorted Matrix\", \"titleSlug\": \"kth-smallest-element-in-a-sorted-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find K Closest Elements\", \"titleSlug\": \"find-k-closest-elements\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Number in Multiplication Table\", \"titleSlug\": \"kth-smallest-number-in-multiplication-table\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"K-th Smallest Prime Fraction\", \"titleSlug\": \"k-th-smallest-prime-fraction\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Median of the Uniqueness Array\", \"titleSlug\": \"find-the-median-of-the-uniqueness-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximize Score of Numbers in Ranges\", \"titleSlug\": \"maximize-score-of-numbers-in-ranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"196.2K\", \"totalSubmission\": \"429.2K\", \"totalAcceptedRaw\": 196231, \"totalSubmissionRaw\": 429229, \"acRate\": \"45.7%\"}",
    "title_pt": "Encontrar a K-ésima Menor Distância entre Pares",
    "description_pt": "<p>A <strong>distância de um par</strong> de inteiros <code>a</code> e <code>b</code> é definida como a diferença absoluta entre <code>a</code> e <code>b</code>.</p>\n\n<p>Dado um array de inteiros <code>nums</code> e um inteiro <code>k</code>, retorne <em>a</em> <code>k<sup>th</sup></code> <em>menor <strong>distância entre todos os pares</strong></em> <code>nums[i]</code> <em>e</em> <code>nums[j]</code> <em>onde</em> <code>0 &lt;= i &lt; j &lt; nums.length</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,3,1], k = 1\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong> Aqui estão todos os pares:\n(1,3) -&gt; 2\n(1,1) -&gt; 0\n(3,1) -&gt; 2\nEntão o 1<sup>st</sup> par de menor distância é (1,1), e sua distância é 0.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,1,1], k = 2\n<strong>Saída:</strong> 0\n</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,6,1], k = 3\n<strong>Saída:</strong> 5\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>n == nums.length</code></li>\n\t<li><code>2 &lt;= n &lt;= 10<sup>4</sup></code></li>\n\t<li><code>0 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>\n\t<li><code>1 &lt;= k &lt;= n * (n - 1) / 2</code></li>\n</ul>",
    "hints_pt": [
      "Dica 1: Faça busca binária pela resposta. Como você pode verificar quantos pares têm distância <= X?"
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "720",
    "paidOnly": false,
    "title": "Longest Word in Dictionary",
    "titleSlug": "longest-word-in-dictionary",
    "url": "https://leetcode.com/problems/longest-word-in-dictionary",
    "description_url": "https://leetcode.com/problems/longest-word-in-dictionary/description/",
    "description": "<p>Given an array of strings <code>words</code> representing an English Dictionary, return <em>the longest word in</em> <code>words</code> <em>that can be built one character at a time by other words in</em> <code>words</code>.</p>\n\n<p>If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.</p>\n\n<p>Note that the word should be built from left to right with each additional character being added to the end of a previous word.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;w&quot;,&quot;wo&quot;,&quot;wor&quot;,&quot;worl&quot;,&quot;world&quot;]\n<strong>Output:</strong> &quot;world&quot;\n<strong>Explanation:</strong> The word &quot;world&quot; can be built one character at a time by &quot;w&quot;, &quot;wo&quot;, &quot;wor&quot;, and &quot;worl&quot;.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> words = [&quot;a&quot;,&quot;banana&quot;,&quot;app&quot;,&quot;appl&quot;,&quot;ap&quot;,&quot;apply&quot;,&quot;apple&quot;]\n<strong>Output:</strong> &quot;apple&quot;\n<strong>Explanation:</strong> Both &quot;apply&quot; and &quot;apple&quot; can be built from other words in the dictionary. However, &quot;apple&quot; is lexicographically smaller than &quot;apply&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>words[i]</code> consists of lowercase English letters.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/longest-word-in-dictionary/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Brute Force [Accepted]\n\n**Intuition**\n\nFor each word, check if all prefixes `word[:k]` are present. We can use a `Set` structure to check this quickly.\n\n**Algorithm**\n\nWhenever our found word would be superior, we check if all its prefixes are present, then replace our answer.\n\nAlternatively, we could have sorted the words beforehand, so that we knew the word we were considering would be the answer if all its prefixes were present.\n\n**Python**\n```python\nclass Solution(object):\n    def longestWord(self, words):\n    ans = \"\"\n    wordset = set(words)\n    for word in words:\n        if len(word) > len(ans) or len(word) == len(ans) and word < ans:\n            if all(word[:k] in wordset for k in xrange(1, len(word))):\n                ans = word\n\n    return ans\n```\n\n*Alternate Implementation*\n```python\nclass Solution(object):\n    def longestWord(self, words):\n        wordset = set(words)\n        words.sort(key = lambda c: (-len(c), c))\n        for word in words:\n            if all(word[:k] in wordset for k in xrange(1, len(word))):\n                return word\n\n        return \"\"\n```\n\n**Java**\n\n```java\nclass Solution {\n    public String longestWord(String[] words) {\n        String ans = \"\";\n        Set<String> wordset = new HashSet();\n        for (String word: words) {\n            wordset.add(word);\n        }\n        for (String word: words) {\n            if (word.length() > ans.length() ||\n                    word.length() == ans.length() && word.compareTo(ans) < 0) {\n                boolean good = true;\n                for (int k = 1; k < word.length(); ++k) {\n                    if (!wordset.contains(word.substring(0, k))) {\n                        good = false;\n                        break;\n                    }\n                }\n                if (good) {\n                    ans = word;\n                }\n            }    \n        }\n        return ans;\n    }\n}\n```\n\n*Alternate Implementation*\n```java\nclass Solution {\n    public String longestWord(String[] words) {\n        Set<String> wordset = new HashSet();\n        for (String word: words) {\n            wordset.add(word);\n        }\n        Arrays.sort(words, (a, b) -> a.length() == b.length()\n                    ? a.compareTo(b) : b.length() - a.length());\n        for (String word: words) {\n            boolean good = true;\n            for (int k = 1; k < word.length(); ++k) {\n                if (!wordset.contains(word.substring(0, k))) {\n                    good = false;\n                    break;\n                }\n            }\n            if (good) {\n                return word;\n            }\n        }\n\n        return \"\";\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time complexity : $$O(\\sum w_i^2)$$, where $$w_i$$ is the length of `words[i]`. Checking whether all prefixes of `words[i]` are in the set is $$O(\\sum w_i^2)$$.\n\n* Space complexity : $$O(\\sum w_i^2)$$ to create the substrings.\n\n---\n### Approach #2: Trie + Depth-First Search [Accepted]\n\n**Intuition**\n\nAs prefixes of strings are involved, this is usually a natural fit for a *trie* (a prefix tree.)\n\n**Algorithm**\n\nPut every word in a trie, then depth-first-search from the start of the trie, only searching nodes that ended a word. Every node found (except the root, which is a special case) then represents a word with all its prefixes present.  We take the best such word.\n\nIn Python, we showcase a method using defaultdict, while in Java, we stick to a more general object-oriented approach.\n\n**Python**\n```python\nclass Solution(object):\n    def longestWord(self, words):\n        Trie = lambda: collections.defaultdict(Trie)\n        trie = Trie()\n        END = True\n\n        for i, word in enumerate(words):\n            reduce(dict.__getitem__, word, trie)[END] = i\n\n        stack = trie.values()\n        ans = \"\"\n        while stack:\n            cur = stack.pop()\n            if END in cur:\n                word = words[cur[END]]\n                if len(word) > len(ans) or len(word) == len(ans) and word < ans:\n                    ans = word\n                stack.extend([cur[letter] for letter in cur if letter != END])\n\n        return ans\n```\n\n**Java**\n```java\nclass Solution {\n    public String longestWord(String[] words) {\n        Trie trie = new Trie();\n        int index = 0;\n        for (String word: words) {\n            trie.insert(word, ++index); //indexed by 1\n        }\n        trie.words = words;\n        return trie.dfs();\n    }\n}\nclass Node {\n    char c;\n    HashMap<Character, Node> children = new HashMap();\n    int end;\n    public Node(char c){\n        this.c = c;\n    }\n}\n\nclass Trie {\n    Node root;\n    String[] words;\n    public Trie() {\n        root = new Node('0');\n    }\n\n    public void insert(String word, int index) {\n        Node cur = root;\n        for (char c: word.toCharArray()) {\n            cur.children.putIfAbsent(c, new Node(c));\n            cur = cur.children.get(c);\n        }\n        cur.end = index;\n    }\n\n    public String dfs() {\n        String ans = \"\";\n        Stack<Node> stack = new Stack();\n        stack.push(root);\n        while (!stack.empty()) {\n            Node node = stack.pop();\n            if (node.end > 0 || node == root) {\n                if (node != root) {\n                    String word = words[node.end - 1];\n                    if (word.length() > ans.length() ||\n                            word.length() == ans.length() && word.compareTo(ans) < 0) {\n                        ans = word;\n                    }\n                }\n                for (Node nei: node.children.values()) {\n                    stack.push(nei);\n                }\n            }\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(\\sum w_i)$$, where $$w_i$$ is the length of `words[i]`. This is the complexity to build the trie and to search it.\n\n  If we used a BFS instead of a DFS and ordered the children in an array, we could drop the need to check whether the candidate word at each node is better than the answer, by forcing that the last node visited will be the best answer.\n\n* Space Complexity: $$O(\\sum w_i)$$, the space used by our trie.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def longestWord(self, words: List[str]) -> str:\n    root = {}\n\n    for word in words:\n      node = root\n      for c in word:\n        if c not in node:\n          node[c] = {}\n        node = node[c]\n      node['word'] = word\n\n    def dfs(node: dict) -> str:\n      ans = node['word'] if 'word' in node else ''\n\n      for child in node:\n        if 'word' in node[child] and len(node[child]['word']) > 0:\n          childWord = dfs(node[child])\n          if len(childWord) > len(ans) or (len(childWord) == len(ans) and childWord < ans):\n            ans = childWord\n\n      return ans\n\n    return dfs(root)",
    "solution_code_java": "\t\t\t\n\nclass TrieNode {\n  public TrieNode[] children = new TrieNode[26];\n  public String word;\n}\n\nclass Solution {\n  public String longestWord(String[] words) {\n    for (final String word : words)\n      insert(word);\n    return longestWordFrom(root);\n  }\n\n  private TrieNode root = new TrieNode();\n\n  private void insert(final String word) {\n    TrieNode node = root;\n    for (char c : word.toCharArray()) {\n      final int i = c - 'a';\n      if (node.children[i] == null)\n        node.children[i] = new TrieNode();\n      node = node.children[i];\n    }\n    node.word = word;\n  }\n\n  private String longestWordFrom(TrieNode node) {\n    String ans = node.word == null ? \"\" : node.word;\n\n    for (TrieNode child : node.children)\n      if (child != null && child.word != null) {\n        String childWord = longestWordFrom(child);\n        if (childWord.length() > ans.length())\n          ans = childWord;\n      }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nstruct TrieNode {\n  vector<shared_ptr<TrieNode>> children;\n  const string* word = nullptr;\n  TrieNode() : children(26) {}\n};\n\nclass Solution {\n public:\n  string longestWord(vector<string>& words) {\n    for (const string& word : words)\n      insert(word);\n    return longestWordFrom(root);\n  }\n\n private:\n  shared_ptr<TrieNode> root = make_shared<TrieNode>();\n\n  void insert(const string& word) {\n    shared_ptr<TrieNode> node = root;\n    for (const char c : word) {\n      const int i = c - 'a';\n      if (node->children[i] == nullptr)\n        node->children[i] = make_shared<TrieNode>();\n      node = node->children[i];\n    }\n    node->word = &word;\n  }\n\n  string longestWordFrom(shared_ptr<TrieNode> node) {\n    string ans = node->word ? *node->word : \"\";\n\n    for (shared_ptr<TrieNode> child : node->children)\n      if (child && child->word) {\n        string childWord = longestWordFrom(child);\n        if (childWord.length() > ans.length())\n          ans = childWord;\n      }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/720.html",
    "category": "Algorithms",
    "acceptance_rate": 53.36361197586859,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Trie",
      "Sorting"
    ],
    "hints": [
      "For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set."
    ],
    "likes": 2020,
    "dislikes": 1502,
    "similar_questions": "[{\"title\": \"Longest Word in Dictionary through Deleting\", \"titleSlug\": \"longest-word-in-dictionary-through-deleting\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Implement Magic Dictionary\", \"titleSlug\": \"implement-magic-dictionary\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Longest Word With All Prefixes\", \"titleSlug\": \"longest-word-with-all-prefixes\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"171.1K\", \"totalSubmission\": \"320.6K\", \"totalAcceptedRaw\": 171072, \"totalSubmissionRaw\": 320578, \"acRate\": \"53.4%\"}",
    "title_pt": "Maior Palavra no Dicionário",
    "description_pt": "<p>Dado um array de strings <code>words</code> representando um Dicionário em inglês, retorne <em>a maior palavra em</em> <code>words</code> <em>que pode ser construída um caractere por vez por outras palavras em</em> <code>words</code>.</p>\n\n<p>Se houver mais de uma possível resposta, retorne a maior palavra com a menor ordem lexicográfica. Se não houver resposta, retorne a string vazia.</p>\n\n<p>Observe que a palavra deve ser construída da esquerda para a direita, com cada caractere adicional sendo adicionado ao final de uma palavra anterior.&nbsp;</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;w&quot;,&quot;wo&quot;,&quot;wor&quot;,&quot;worl&quot;,&quot;world&quot;]\n<strong>Saída:</strong> &quot;world&quot;\n<strong>Explicação:</strong> A palavra &quot;world&quot; pode ser construída um caractere por vez por &quot;w&quot;, &quot;wo&quot;, &quot;wor&quot;, e &quot;worl&quot;.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> words = [&quot;a&quot;,&quot;banana&quot;,&quot;app&quot;,&quot;appl&quot;,&quot;ap&quot;,&quot;apply&quot;,&quot;apple&quot;]\n<strong>Saída:</strong> &quot;apple&quot;\n<strong>Explicação:</strong> Tanto &quot;apply&quot; quanto &quot;apple&quot; podem ser construídas a partir de outras palavras no dicionário. No entanto, &quot;apple&quot; é lexicograficamente menor que &quot;apply&quot;.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= words.length &lt;= 1000</code></li>\n\t<li><code>1 &lt;= words[i].length &lt;= 30</code></li>\n\t<li><code>words[i]</code> consiste em letras minúsculas do alfabeto inglês.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Para cada palavra na lista de entrada, podemos verificar se todos os prefixos dessa palavra estão na lista de entrada usando um Set."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "721",
    "paidOnly": false,
    "title": "Accounts Merge",
    "titleSlug": "accounts-merge",
    "url": "https://leetcode.com/problems/accounts-merge",
    "description_url": "https://leetcode.com/problems/accounts-merge/description/",
    "description": "<p>Given a list of <code>accounts</code> where each element <code>accounts[i]</code> is a list of strings, where the first element <code>accounts[i][0]</code> is a name, and the rest of the elements are <strong>emails</strong> representing emails of the account.</p>\n\n<p>Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.</p>\n\n<p>After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails <strong>in sorted order</strong>. The accounts themselves can be returned in <strong>any order</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> accounts = [[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john_newyork@mail.com&quot;],[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john00@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]\n<strong>Output:</strong> [[&quot;John&quot;,&quot;john00@mail.com&quot;,&quot;john_newyork@mail.com&quot;,&quot;johnsmith@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]\n<strong>Explanation:</strong>\nThe first and second John&#39;s are the same person as they have the common email &quot;johnsmith@mail.com&quot;.\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [[&#39;Mary&#39;, &#39;mary@mail.com&#39;], [&#39;John&#39;, &#39;johnnybravo@mail.com&#39;], \n[&#39;John&#39;, &#39;john00@mail.com&#39;, &#39;john_newyork@mail.com&#39;, &#39;johnsmith@mail.com&#39;]] would still be accepted.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> accounts = [[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe3@m.co&quot;,&quot;Gabe1@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;,&quot;Kevin0@m.co&quot;],[&quot;Ethan&quot;,&quot;Ethan5@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan0@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo3@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo0@m.co&quot;],[&quot;Fern&quot;,&quot;Fern5@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern0@m.co&quot;]]\n<strong>Output:</strong> [[&quot;Ethan&quot;,&quot;Ethan0@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan5@m.co&quot;],[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe1@m.co&quot;,&quot;Gabe3@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo0@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo3@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin0@m.co&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;],[&quot;Fern&quot;,&quot;Fern0@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern5@m.co&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= accounts.length &lt;= 1000</code></li>\n\t<li><code>2 &lt;= accounts[i].length &lt;= 10</code></li>\n\t<li><code>1 &lt;= accounts[i][j].length &lt;= 30</code></li>\n\t<li><code>accounts[i][0]</code> consists of English letters.</li>\n\t<li><code>accounts[i][j] (for j &gt; 0)</code> is a valid email.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/accounts-merge/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nWe are given a list of accounts where each account consists of a list containing the name of the person the account belongs to and some emails that belong to the person. One person is allowed to have multiple accounts, but each email can only belong to one person. Therefore, we can say two accounts must belong to the same person if the accounts have an email in common. Note that we cannot just use the user's name to determine which email addresses belong to the same user since different users may have the same name.\n\nOur goal is, for each person, we want to identify all of the emails that belong to that person. Therefore, every time we find two accounts with an email in common, we will merge the two accounts into one.  \n\nWhenever we must work with a set of elements (emails) that are connected (belong to the same user), we should always consider visualizing our input as a graph. In this problem, converting the input into a graph will facilitate the process of \"merging\" two accounts.\n\nEmails can be represented as nodes, and an edge between nodes will signify that they belong to the same person. Since all of the emails in an account belong to the same person, we can connect all of the emails with edges. Thus, each account can be represented by a connected component. What if two accounts have an email in common? Then we can add an edge between the two connected components, effectively merging them into one connected component.  \n</br>\n\n---\n\n### Approach 1: Depth First Search (DFS)\n\n**Intuition**\n\nHere, we will represent emails as nodes, and an edge will signify that two emails are connected and hence belong to the same person. This means that any two emails that are connected by a path of edges must also belong to the same person. Initially, we are given $$N$$ accounts, where each account's emails make up a connected component.  \n\nOur first step should be to ensure that for each account, all of its nodes are connected. Suppose an account has $$K$$ emails, and we want to connect these emails. Since all emails in an account are connected, we can add an edge between every pair of emails. This will create a complete subgraph and require adding $$K \\choose 2$$ edges. However, do we really need that many edges to keep track of which emails belong to the same account? No, as long as two emails are connected by a path of edges, we know they belong to the same account. So instead of creating a complete subgraph for each account, we can create an acyclic graph using only $$K - 1$$ edges. Recall that $$K - 1$$ is the minimum number of edges required to connect $$K$$ nodes. In this approach, we will connect emails in an account in a [star](https://en.wikipedia.org/wiki/Star_(graph_theory)) manner with the first email as the internal node of the star and all other emails as the leaves (as shown below).\n\n![fig](../Figures/721/721A.png)\n\nThe beauty of connecting the emails in each account in this manner is that after connecting an email to a second account, that email will have one edge going to an email in the first account and one edge going to an email in the second account.  Thereby automatically merging the two accounts. The below slideshow depicts the merging process for four accounts that belong to two different people.\n\n!?!../Documents/721_Accounts_Merge_A.json:960,720!?! <br>\n\nAfter iterating over each account and connecting the emails as described above, we will have a one or more connected components. Each connected component will represent one person, and the nodes in the connected component are the person's emails. Now our task is to explore each connected component to find all the emails that belong to each person. Since a depth-first search is guaranteed to explore every node in a connected component, we will perform a DFS on each connected component (person) to find all of the connected emails.\n\nTo do so, we will iterate over all of the nodes and consider starting a DFS. If the node has already been visited, in an earlier DFS, we will not start a DFS.  Otherwise, perform a DFS traversal over the connected component and store all the visited emails together, as they all belong to one person. Each time we visit an email during a DFS, we will mark it as visited to ensure that we do not search the same connected component more than once. To read more about how DFS can be leveraged to find components you can refer to the first approach [here](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/solution/).\n\n\n**Algorithm**\n\n1. Create an adjacency list: For each account add an edge between the first email (`accountFirstEmail`) and each of the other emails in the account.\n2. Traverse over the accounts; for each account, check if the first email in the account (`accountFirstEmail`) was already visited.  If so, then do not start a new DFS. Otherwise, perform DFS with this email as the source node.\n3. During each DFS, store the traversed emails in an array `mergedAccount`, also mark all these emails as visited.\n4. After the DFS traversal is over, sort the emails and add the account name (`accountName`) at the start of the vector `mergedAccount`.\n5. Store the vector `mergedAccount` in the answer list `mergedAccounts`.\n\n\n**Implementation**\n\n\n<iframe src=\"https://leetcode.com/playground/EAjKzRH9/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"EAjKzRH9\"></iframe>\n\n\n**Complexity Analysis**\n\nHere $$N$$ is the number of accounts and $$K$$ is the maximum length of an account.\n\n* Time complexity: $$O(NK \\log{NK})$$\n\n    In the worst case, all the emails will end up belonging to a single person. The total number of emails will be $$N*K$$, and we need to sort these emails. DFS traversal will take $$NK$$ operations as no email will be traversed more than once.\n\n* Space complexity: $$O(NK)$$\n\n  Building the adjacency list will take $$O(NK)$$ space. In the end, `visited` will contain all of the emails hence it will use $$O(NK)$$ space. Also, the call stack for DFS will use $$O(NK)$$ space in the worst case.\n\n  The space complexity of the sorting algorithm depends on the implementation of each programming language. For instance, in Java, Collections.sort() dumps the specified list into an array this will take $$O(NK)$$ space then Arrays.sort() for primitives is implemented as a variant of quicksort algorithm whose space complexity is $$O(\\log NK)$$. In C++ `sort()` function provided by STL is a hybrid of Quick Sort, Heap Sort, and Insertion Sort with the worst-case space complexity of $O(\\log NK)$. \n\n<br/>\n\n---\n\n### Approach 2: Disjoint Set Union (DSU)\n\n**Intuition**\n\nAs in the previous approach, the first step is to find which accounts have an email in common and merge them to form a larger connected component. Any problem that involves merging connected components (accounts) is a natural fit for the Disjoint Set Union (DSU) data structure. If you would like to learn more about the DSU data structure (also known as Union-Find), a tutorial is provided in the [Graph Explore Card](https://leetcode.com/explore/featured/card/graph/618/disjoint-set/3881/). Since most implementations of DSU use an array to record the root (representative) of each component, we will use integers to represent each component for ease of operability. Therefore, we will give each account a unique ID, and we will map all the emails in the account to the account's ID. We will use a map, `emailGroup`, to store this information. \n\nWe chose the account index to be the identifier for all the emails of an account. We will assign the account index as the group when we get the email for the first time and when we get an email that we have already traversed, we will merge the current account and the group that we have previously stored in `emailGroup` using union operation.\n\nAfter traversing over all the accounts, we will find the representative of all the emails which will inform us about their group. Emails with the same representative belong to the same person/group and hence will be stored together. Also, we can retrieve the account name for our final answer using `accountList` as we have `group` which is the index in the original accounts list.\n\n!?!../Documents/721_Accounts_Merge_B.json:960,720!?! <br>\n\n**Algorithm**\n\n1. Traverse over each account, and for each account, traverse over all of its emails.  If we see an email for the first time, then set the group of the email as the index of the current account in `emailGroup` .\n2. Otherwise, if the email has already been seen in another account, then we will union the current group (`i`) and the group the current email belongs to (`emailGroup[email]`).\n3. After traversing over every account and merging the accounts that share a common email, we will now traverse over every email once more. Each email will be added to a map (`components`) where the key is the email's representative, and the value is a list of emails with that representative.\n4. Traverse over `components`, here the keys are the group indices and the value is the list of emails belonging to this group (person). Since the emails must be \"in sorted order\" we will sort the list of emails for each group. Lastly, we can get the account name using the `accountList[group][0]`. In accordance with the instructions, we will insert this name at the beginning of the email list.\n5. Store the list created in step 4 in our final result (`mergedAccount`). \n\n**Implementation**\n\n\n<iframe src=\"https://leetcode.com/playground/cCnGvzFV/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"cCnGvzFV\"></iframe>\n\n\n**Complexity Analysis**\n\nHere $$N$$ is the number of accounts and $$K$$ is the maximum length of an account.\n\n* Time complexity: $$O(NK \\log {NK})$$\n\n   While merging we consider the size of each connected component and we always choose the representative of the larger component to be the new representative of the smaller component, also we have included the path compression so the time complexity for find/union operation is $$\\alpha({N})$$ (Here, $$\\alpha({N})$$ is the inverse Ackermann function that grows so slowly, that it doesn't exceed $$4$$ for all reasonable $$N$$ (approximately $$ N < 10^{600}$$).\n\n  We find the representative of all the emails, hence it will take $$O(NK\\alpha({N}))$$ time. We are also sorting the components and the worst case will be when all emails end up belonging to the same component this will cost $$O(NK(\\log {NK}))$$.\n\n  Hence the total time complexity is $$O(NK \\cdot \\log {NK} + NK \\cdot \\alpha({N}))$$.\n\n* Space complexity: $$O(NK)$$\n\n  List `representative`, `size` store information corresponding to each group so will take $$O(N)$$ space. All emails get stored in `emailGroup` and `component` hence space used is $$O(NK)$$.\n\n  The space complexity of the sorting algorithm depends on the implementation of each programming language. For instance, in Java, Collections.sort() dumps the specified list into an array this will take $$O(NK)$$ space then Arrays.sort() for primitives is implemented as a variant of quicksort algorithm whose space complexity is $$O(\\log NK)$$. In C++ `sort()` function provided by STL is a hybrid of Quick Sort, Heap Sort, and Insertion Sort with the worst-case space complexity of $O(\\log NK)$. \n<br/>\n\n---",
    "solution_code_python": "",
    "solution_code_java": "\t\t\t\n\nclass UnionFind {\n  public UnionFind(List<List<String>> accounts) {\n    for (List<String> account : accounts)\n      for (int i = 1; i < account.size(); ++i) {\n        final String email = account.get(i);\n        id.putIfAbsent(email, email);\n      }\n  }\n\n  public void union(final String u, final String v) {\n    id.put(find(u), find(v));\n  }\n\n  public String find(final String u) {\n    if (u != id.get(u))\n      id.put(u, find(id.get(u)));\n    return id.get(u);\n  }\n\n  private Map<String, String> id = new HashMap<>();\n}\n\nclass Solution {\n  public List<List<String>> accountsMerge(List<List<String>> accounts) {\n    List<List<String>> ans = new ArrayList<>();\n    Map<String, String> emailToName = new HashMap<>();\n    Map<String, TreeSet<String>> idEmailToEmails = new HashMap<>();\n    UnionFind uf = new UnionFind(accounts);\n\n    // Get {email: name} mapping\n    for (final List<String> account : accounts)\n      for (int i = 1; i < account.size(); ++i)\n        emailToName.putIfAbsent(account.get(i), account.get(0));\n\n    // Union emails\n    for (final List<String> account : accounts)\n      for (int i = 2; i < account.size(); ++i)\n        uf.union(account.get(i), account.get(i - 1));\n\n    for (final List<String> account : accounts)\n      for (int i = 1; i < account.size(); ++i) {\n        final String id = uf.find(account.get(i));\n        idEmailToEmails.putIfAbsent(id, new TreeSet<>());\n        idEmailToEmails.get(id).add(account.get(i));\n      }\n\n    for (final String idEmail : idEmailToEmails.keySet()) {\n      List<String> emails = new ArrayList<>(idEmailToEmails.get(idEmail));\n      final String name = emailToName.get(idEmail);\n      emails.add(0, name);\n      ans.add(emails);\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass UnionFind {\n public:\n  UnionFind(int n) : sz(n, 1), id(n) {\n    iota(begin(id), end(id), 0);\n  }\n\n  void unionBySize(int u, int v) {\n    const int i = find(u);\n    const int j = find(v);\n    if (i == j)\n      return;\n    if (sz[i] < sz[j]) {\n      sz[j] += sz[i];\n      id[i] = j;\n    } else {\n      sz[i] += sz[j];\n      id[j] = i;\n    }\n  }\n\n  int find(int u) {\n    return id[u] == u ? u : id[u] = find(id[u]);\n  }\n\n private:\n  vector<int> sz;\n  vector<int> id;\n};\n\nclass Solution {\n public:\n  vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n    vector<vector<string>> ans;\n    unordered_map<string, int> emailToIndex;        // {email: index}\n    unordered_map<int, set<string>> indexToEmails;  // {index: {emails}}\n    UnionFind uf(accounts.size());\n\n    for (int i = 0; i < accounts.size(); ++i) {\n      const string name = accounts[i][0];\n      for (int j = 1; j < accounts[i].size(); ++j) {\n        const string email = accounts[i][j];\n        const auto it = emailToIndex.find(email);\n        if (it == emailToIndex.end()) {\n          // Only record if it's the first time we see thie email\n          emailToIndex[email] = i;\n        } else {\n          // Otherwise, union i w/ emailToIndex[index]\n          uf.unionBySize(i, it->second);\n        }\n      }\n    }\n\n    for (const auto& [email, index] : emailToIndex)\n      indexToEmails[uf.find(index)].insert(email);\n\n    for (const auto& [index, emails] : indexToEmails) {\n      const string name = accounts[index][0];\n      vector<string> row{name};\n      row.insert(end(row), begin(emails), end(emails));\n      ans.push_back(row);\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/721.html",
    "category": "Algorithms",
    "acceptance_rate": 59.310551815804146,
    "topics": [
      "Array",
      "Hash Table",
      "String",
      "Depth-First Search",
      "Breadth-First Search",
      "Union Find",
      "Sorting"
    ],
    "hints": [
      "For every pair of emails in the same account, draw an edge between those emails.  The problem is about enumerating the connected components of this graph."
    ],
    "likes": 7207,
    "dislikes": 1250,
    "similar_questions": "[{\"title\": \"Redundant Connection\", \"titleSlug\": \"redundant-connection\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sentence Similarity\", \"titleSlug\": \"sentence-similarity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sentence Similarity II\", \"titleSlug\": \"sentence-similarity-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"511.8K\", \"totalSubmission\": \"863K\", \"totalAcceptedRaw\": 511821, \"totalSubmissionRaw\": 862950, \"acRate\": \"59.3%\"}",
    "title_pt": "Mesclar Contas",
    "description_pt": "<p>Dada uma lista de <code>accounts</code> em que cada elemento <code>accounts[i]</code> é uma lista de strings, onde o primeiro elemento <code>accounts[i][0]</code> é um nome, e o restante dos elementos são <strong>emails</strong> que representam os emails da conta.</p>\n\n<p>Agora, gostaríamos de mesclar essas contas. Duas contas definitivamente pertencem à mesma pessoa se houver algum email em comum entre ambas as contas. Observe que mesmo que duas contas tenham o mesmo nome, elas podem pertencer a pessoas diferentes, pois pessoas diferentes podem ter o mesmo nome. Uma pessoa pode ter qualquer número de contas inicialmente, mas todas as suas contas definitivamente têm o mesmo nome.</p>\n\n<p>Depois de mesclar as contas, retorne as contas no seguinte formato: o primeiro elemento de cada conta é o nome, e o restante dos elementos são emails <strong>em ordem crescente</strong>. As próprias contas podem ser retornadas em <strong>qualquer ordem</strong>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> accounts = [[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john_newyork@mail.com&quot;],[&quot;John&quot;,&quot;johnsmith@mail.com&quot;,&quot;john00@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]\n<strong>Saída:</strong> [[&quot;John&quot;,&quot;john00@mail.com&quot;,&quot;john_newyork@mail.com&quot;,&quot;johnsmith@mail.com&quot;],[&quot;Mary&quot;,&quot;mary@mail.com&quot;],[&quot;John&quot;,&quot;johnnybravo@mail.com&quot;]]\n<strong>Explicação:</strong>\nO primeiro e o segundo John são a mesma pessoa, pois eles têm o email em comum &quot;johnsmith@mail.com&quot;.\nO terceiro John e Mary são pessoas diferentes, pois nenhum de seus endereços de email é usado por outras contas.\nPoderíamos retornar essas listas em qualquer ordem; por exemplo, a resposta [[&#39;Mary&#39;, &#39;mary@mail.com&#39;], [&#39;John&#39;, &#39;johnnybravo@mail.com&#39;], \n[&#39;John&#39;, &#39;john00@mail.com&#39;, &#39;john_newyork@mail.com&#39;, &#39;johnsmith@mail.com&#39;]] ainda seria aceita.\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> accounts = [[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe3@m.co&quot;,&quot;Gabe1@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;,&quot;Kevin0@m.co&quot;],[&quot;Ethan&quot;,&quot;Ethan5@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan0@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo3@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo0@m.co&quot;],[&quot;Fern&quot;,&quot;Fern5@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern0@m.co&quot;]]\n<strong>Saída:</strong> [[&quot;Ethan&quot;,&quot;Ethan0@m.co&quot;,&quot;Ethan4@m.co&quot;,&quot;Ethan5@m.co&quot;],[&quot;Gabe&quot;,&quot;Gabe0@m.co&quot;,&quot;Gabe1@m.co&quot;,&quot;Gabe3@m.co&quot;],[&quot;Hanzo&quot;,&quot;Hanzo0@m.co&quot;,&quot;Hanzo1@m.co&quot;,&quot;Hanzo3@m.co&quot;],[&quot;Kevin&quot;,&quot;Kevin0@m.co&quot;,&quot;Kevin3@m.co&quot;,&quot;Kevin5@m.co&quot;],[&quot;Fern&quot;,&quot;Fern0@m.co&quot;,&quot;Fern1@m.co&quot;,&quot;Fern5@m.co&quot;]]\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= accounts.length &lt;= 1000</code></li>\n\t<li><code>2 &lt;= accounts[i].length &lt;= 10</code></li>\n\t<li><code>1 &lt;= accounts[i][j].length &lt;= 30</code></li>\n\t<li><code>accounts[i][0]</code> consiste em letras inglesas.</li>\n\t<li><code>accounts[i][j] (for j &gt; 0)</code> é um email válido.</li>\n</ul>",
    "hints_pt": [
      "Dica 1: Para cada par de emails na mesma conta, desenhe uma aresta entre esses emails. O problema consiste em enumerar os componentes conexos desse grafo."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "722",
    "paidOnly": false,
    "title": "Remove Comments",
    "titleSlug": "remove-comments",
    "url": "https://leetcode.com/problems/remove-comments",
    "description_url": "https://leetcode.com/problems/remove-comments/description/",
    "description": "<p>Given a C++ program, remove comments from it. The program source is an array of strings <code>source</code> where <code>source[i]</code> is the <code>i<sup>th</sup></code> line of the source code. This represents the result of splitting the original source code string by the newline character <code>&#39;\\n&#39;</code>.</p>\n\n<p>In C++, there are two types of comments, line comments, and block comments.</p>\n\n<ul>\n\t<li>The string <code>&quot;//&quot;</code> denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.</li>\n\t<li>The string <code>&quot;/*&quot;</code> denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of <code>&quot;*/&quot;</code> should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string <code>&quot;/*/&quot;</code> does not yet end the block comment, as the ending would be overlapping the beginning.</li>\n</ul>\n\n<p>The first effective comment takes precedence over others.</p>\n\n<ul>\n\t<li>For example, if the string <code>&quot;//&quot;</code> occurs in a block comment, it is ignored.</li>\n\t<li>Similarly, if the string <code>&quot;/*&quot;</code> occurs in a line or block comment, it is also ignored.</li>\n</ul>\n\n<p>If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.</p>\n\n<p>There will be no control characters, single quote, or double quote characters.</p>\n\n<ul>\n\t<li>For example, <code>source = &quot;string s = &quot;/* Not a comment. */&quot;;&quot;</code> will not be a test case.</li>\n</ul>\n\n<p>Also, nothing else such as defines or macros will interfere with the comments.</p>\n\n<p>It is guaranteed that every open block comment will eventually be closed, so <code>&quot;/*&quot;</code> outside of a line or block comment always starts a new comment.</p>\n\n<p>Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.</p>\n\n<p>After removing the comments from the source code, return <em>the source code in the same format</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> source = [&quot;/*Test program */&quot;, &quot;int main()&quot;, &quot;{ &quot;, &quot;  // variable declaration &quot;, &quot;int a, b, c;&quot;, &quot;/* This is a test&quot;, &quot;   multiline  &quot;, &quot;   comment for &quot;, &quot;   testing */&quot;, &quot;a = b + c;&quot;, &quot;}&quot;]\n<strong>Output:</strong> [&quot;int main()&quot;,&quot;{ &quot;,&quot;  &quot;,&quot;int a, b, c;&quot;,&quot;a = b + c;&quot;,&quot;}&quot;]\n<strong>Explanation:</strong> The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n  // variable declaration \nint a, b, c;\n/* This is a test\n   multiline  \n   comment for \n   testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n  \nint a, b, c;\na = b + c;\n}\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> source = [&quot;a/*comment&quot;, &quot;line&quot;, &quot;more_comment*/b&quot;]\n<strong>Output:</strong> [&quot;ab&quot;]\n<strong>Explanation:</strong> The original source string is &quot;a/*comment\\nline\\nmore_comment*/b&quot;, where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string &quot;ab&quot;, which when delimited by newline characters becomes [&quot;ab&quot;].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= source.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= source[i].length &lt;= 80</code></li>\n\t<li><code>source[i]</code> consists of printable <strong>ASCII</strong> characters.</li>\n\t<li>Every open block comment is eventually closed.</li>\n\t<li>There are no single-quote or&nbsp;double-quote in the input.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/remove-comments/solutions/",
    "solution": "[TOC]\n\n### Approach #1: Parsing [Accepted]\n\n**Intuition and Algorithm**\n\nWe need to parse the `source` line by line. Our state is that we either are in a block comment or not.\n\n* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.\n\n* If we end a block comment and we are in a block, then we will skip over the next two characters and change our state to be *not* in a block.\n\n* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.\n\n* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.\n\n* At the end of each line, if we aren't in a block, we will record the line.\n\n**Python**\n```python\nclass Solution(object):\n    def removeComments(self, source):\n        in_block = False\n        ans = []\n        for line in source:\n            i = 0\n            if not in_block:\n                newline = []\n            while i < len(line):\n                if line[i:i+2] == '/*' and not in_block:\n                    in_block = True\n                    i += 1\n                elif line[i:i+2] == '*/' and in_block:\n                    in_block = False\n                    i += 1\n                elif not in_block and line[i:i+2] == '//':\n                    break\n                elif not in_block:\n                    newline.append(line[i])\n                i += 1\n            if newline and not in_block:\n                ans.append(\"\".join(newline))\n\n        return ans\n```\n\n**Java**\n```java\nclass Solution {\n    public List<String> removeComments(String[] source) {\n        boolean inBlock = false;\n        StringBuilder newline = new StringBuilder();\n        List<String> ans = new ArrayList();\n        for (String line: source) {\n            int i = 0;\n            char[] chars = line.toCharArray();\n            if (!inBlock) {\n                newline = new StringBuilder();\n            }\n            while (i < line.length()) {\n                if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '*') {\n                    inBlock = true;\n                    i++;\n                } else if (inBlock && i+1 < line.length() && chars[i] == '*' && chars[i+1] == '/') {\n                    inBlock = false;\n                    i++;\n                } else if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '/') {\n                    break;\n                } else if (!inBlock) {\n                    newline.append(chars[i]);\n                }\n                i++;\n            }\n            if (!inBlock && newline.length() > 0) {\n                ans.add(new String(newline));\n            }\n        }\n        return ans;\n    }\n}\n```\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(S)$$, where $$S$$ is the total length of the source code.\n\n* Space Complexity: $$O(S)$$, the space used by recording the source code into `ans`.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def removeComments(self, source: List[str]) -> List[str]:\n    ans = []\n    commenting = False\n    modified = ''\n\n    for line in source:\n      i = 0\n      while i < len(line):\n        if i + 1 == len(line):\n          if not commenting:\n            modified += line[i]\n          i += 1\n          break\n        twoChars = line[i:i + 2]\n        if twoChars == '/*' and not commenting:\n          commenting = True\n          i += 2\n        elif twoChars == '*/' and commenting:\n          commenting = False\n          i += 2\n        elif twoChars == '//':\n          if not commenting:\n            break\n          else:\n            i += 2\n        else:\n          if not commenting:\n            modified += line[i]\n          i += 1\n      if modified and not commenting:\n        ans.append(modified)\n        modified = ''\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public List<String> removeComments(String[] source) {\n    List<String> ans = new ArrayList<>();\n    boolean commenting = false;\n    StringBuilder modified = new StringBuilder();\n\n    for (final String line : source) {\n      for (int i = 0; i < line.length();) {\n        if (i + 1 == line.length()) {\n          if (!commenting)\n            modified.append(line.charAt(i));\n          ++i;\n          break;\n        }\n        String twoChars = line.substring(i, i + 2);\n        if (twoChars.equals(\"/*\") && !commenting) {\n          commenting = true;\n          i += 2;\n        } else if (twoChars.equals(\"*/\") && commenting) {\n          commenting = false;\n          i += 2;\n        } else if (twoChars.equals(\"//\")) {\n          if (!commenting)\n            break;\n          else\n            i += 2;\n        } else {\n          if (!commenting)\n            modified.append(line.charAt(i));\n          ++i;\n        }\n      }\n      if (modified.length() > 0 && !commenting) {\n        ans.add(modified.toString());\n        modified.setLength(0);\n      }\n    }\n\n    return ans;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<string> removeComments(vector<string>& source) {\n    vector<string> ans;\n    bool commenting = false;\n    string modified;\n\n    for (const string& line : source) {\n      for (int i = 0; i < line.length();) {\n        if (i + 1 == line.length()) {\n          if (!commenting)\n            modified += line[i];\n          ++i;\n          break;\n        }\n        const string& twoChars = line.substr(i, 2);\n        if (twoChars == \"/*\" && !commenting) {\n          commenting = true;\n          i += 2;\n        } else if (twoChars == \"*/\" && commenting) {\n          commenting = false;\n          i += 2;\n        } else if (twoChars == \"//\") {\n          if (!commenting)\n            break;\n          else\n            i += 2;\n        } else {\n          if (!commenting)\n            modified += line[i];\n          ++i;\n        }\n      }\n      if (modified.length() > 0 && !commenting) {\n        ans.push_back(modified);\n        modified = \"\";\n      }\n    }\n\n    return ans;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/722.html",
    "category": "Algorithms",
    "acceptance_rate": 39.3558192610635,
    "topics": [
      "Array",
      "String"
    ],
    "hints": [
      "Carefully parse each line according to the following rules:\r\n\r\n* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.\r\n\r\n* If we end a block comment and we are in a block, then we will skip over the next two characters and change our state to be *not* in a block.\r\n\r\n* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.\r\n\r\n* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.\r\n\r\n* At the end of each line, if we aren't in a block, we will record the line."
    ],
    "likes": 737,
    "dislikes": 1834,
    "similar_questions": "[{\"title\": \"Mini Parser\", \"titleSlug\": \"mini-parser\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ternary Expression Parser\", \"titleSlug\": \"ternary-expression-parser\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"79.5K\", \"totalSubmission\": \"202K\", \"totalAcceptedRaw\": 79496, \"totalSubmissionRaw\": 201993, \"acRate\": \"39.4%\"}",
    "title_pt": "Remover Comentários",
    "description_pt": "<p>Dado um programa em C++, remova os comentários dele. O código-fonte do programa é um array de strings <code>source</code> em que <code>source[i]</code> é a <code>i<sup>th</sup></code> linha do código-fonte. Isso representa o resultado de dividir a string original do código-fonte pelo caractere de nova linha <code>&#39;\\n&#39;</code>.</p>\n\n<p>Em C++, há dois tipos de comentários, comentários de linha e comentários de bloco.</p>\n\n<ul>\n\t<li>A string <code>&quot;//&quot;</code> denota um comentário de linha, que representa que ele e o restante dos caracteres à direita dele na mesma linha devem ser ignorados.</li>\n\t<li>A string <code>&quot;/*&quot;</code> denota um comentário de bloco, que representa que todos os caracteres até a próxima ocorrência (sem sobreposição) de <code>&quot;*/&quot;</code> devem ser ignorados. (Aqui, as ocorrências acontecem em ordem de leitura: linha por linha, da esquerda para a direita.) Para ficar claro, a string <code>&quot;/*/&quot;</code> ainda não encerra o comentário de bloco, pois o fim se sobreporia ao início.</li>\n</ul>\n\n<p>O primeiro comentário efetivo tem precedência sobre os demais.</p>\n\n<ul>\n\t<li>Por exemplo, se a string <code>&quot;//&quot;</code> ocorrer dentro de um comentário de bloco, ela será ignorada.</li>\n\t<li>Da mesma forma, se a string <code>&quot;/*&quot;</code> ocorrer dentro de um comentário de linha ou de bloco, ela também será ignorada.</li>\n</ul>\n\n<p>Se uma determinada linha de código ficar vazia após a remoção dos comentários, você não deve exibir essa linha: cada string na lista de პასუხos será não vazia.</p>\n\n<p>Não haverá caracteres de controle, aspas simples ou aspas duplas.</p>\n\n<ul>\n\t<li>Por exemplo, <code>source = &quot;string s = &quot;/* Not a comment. */&quot;;&quot;</code> não será um caso de teste.</li>\n</ul>\n\n<p>Além disso, nada mais, como defines ou macros, interferirá com os comentários.</p>\n\n<p>É garantido que todo comentário de bloco aberto eventualmente será fechado, de modo que <code>&quot;/*&quot;</code> fora de um comentário de linha ou de bloco sempre inicia um novo comentário.</p>\n\n<p>Por fim, caracteres de nova linha implícitos podem ser removidos por comentários de bloco. Consulte os exemplos abaixo para obter detalhes.</p>\n\n<p>Após remover os comentários do código-fonte, retorne <em>o código-fonte no mesmo formato</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> source = [&quot;/*Test program */&quot;, &quot;int main()&quot;, &quot;{ &quot;, &quot;  // variable declaration &quot;, &quot;int a, b, c;&quot;, &quot;/* This is a test&quot;, &quot;   multiline  &quot;, &quot;   comment for &quot;, &quot;   testing */&quot;, &quot;a = b + c;&quot;, &quot;}&quot;]\n<strong>Saída:</strong> [&quot;int main()&quot;,&quot;{ &quot;,&quot;  &quot;,&quot;int a, b, c;&quot;,&quot;a = b + c;&quot;,&quot;}&quot;]\n<strong>Explicação:</strong> O código linha por linha é visualizado como abaixo:\n/*Test program */\nint main()\n{ \n  // variable declaration \nint a, b, c;\n/* This is a test\n   multiline  \n   comment for \n   testing */\na = b + c;\n}\nA string /* denota um comentário de bloco, incluindo a linha 1 e as linhas 6-9. A string // denota a linha 4 como comentários.\nO código de saída linha por linha é visualizado como abaixo:\nint main()\n{ \n  \nint a, b, c;\na = b + c;\n}\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> source = [&quot;a/*comment&quot;, &quot;line&quot;, &quot;more_comment*/b&quot;]\n<strong>Saída:</strong> [&quot;ab&quot;]\n<strong>Explicação:</strong> A string original do código-fonte é &quot;a/*comment\\nline\\nmore_comment*/b&quot;, onde destacamos em negrito os caracteres de nova linha. Após a remoção, os caracteres de nova linha implícitos são removidos, deixando a string &quot;ab&quot;, que, quando delimitada por caracteres de nova linha, torna-se [&quot;ab&quot;].\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= source.length &lt;= 100</code></li>\n\t<li><code>0 &lt;= source[i].length &lt;= 80</code></li>\n\t<li><code>source[i]</code> consiste em caracteres imprimíveis <strong>ASCII</strong>.</li>\n\t<li>Cada comentário de bloco aberto eventualmente é fechado.</li>\n\t<li>Não há aspas simples nem&nbsp;aspas duplas na entrada.</li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Faça o parse cuidadosamente de cada linha de acordo com as seguintes regras:\n\n* Se iniciarmos um comentário de bloco e não estivermos em um bloco, então pularemos os próximos dois caracteres e mudaremos nosso estado para estar em um bloco.\n\n* Se encerrarmos um comentário de bloco e estivermos em um bloco, então pularemos os próximos dois caracteres e mudaremos nosso estado para *não* estar em um bloco.\n\n* Se iniciarmos um comentário de linha e não estivermos em um bloco, então ignoraremos o restante da linha.\n\n* Se não estivermos em um comentário de bloco (e não foi o início de um comentário), registraremos o caractere na posição atual.\n\n* Ao final de cada linha, se não estivermos em um bloco, registraremos a linha."
    ]
  },
  {
    "difficulty": "Easy",
    "frontendQuestionId": "724",
    "paidOnly": false,
    "title": "Find Pivot Index",
    "titleSlug": "find-pivot-index",
    "url": "https://leetcode.com/problems/find-pivot-index",
    "description_url": "https://leetcode.com/problems/find-pivot-index/description/",
    "description": "<p>Given an array of integers <code>nums</code>, calculate the <strong>pivot index</strong> of this array.</p>\n\n<p>The <strong>pivot index</strong> is the index where the sum of all the numbers <strong>strictly</strong> to the left of the index is equal to the sum of all the numbers <strong>strictly</strong> to the index&#39;s right.</p>\n\n<p>If the index is on the left edge of the array, then the left sum is <code>0</code> because there are no elements to the left. This also applies to the right edge of the array.</p>\n\n<p>Return <em>the <strong>leftmost pivot index</strong></em>. If no such index exists, return <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,7,3,6,5,6]\n<strong>Output:</strong> 3\n<strong>Explanation:</strong>\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [1,2,3]\n<strong>Output:</strong> -1\n<strong>Explanation:</strong>\nThere is no index that satisfies the conditions in the problem statement.</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> nums = [2,1,-1]\n<strong>Output:</strong> 0\n<strong>Explanation:</strong>\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Note:</strong> This question is the same as&nbsp;1991:&nbsp;<a href=\"https://leetcode.com/problems/find-the-middle-index-in-array/\" target=\"_blank\">https://leetcode.com/problems/find-the-middle-index-in-array/</a></p>\n",
    "solution_url": "https://leetcode.com/problems/find-pivot-index/solutions/",
    "solution": null,
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def pivotIndex(self, nums: List[int]) -> int:\n    summ = sum(nums)\n    prefix = 0\n\n    for i, num in enumerate(nums):\n      if prefix == summ - prefix - num:\n        return i\n      prefix += num\n\n    return -1",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public int pivotIndex(int[] nums) {\n    final int sum = Arrays.stream(nums).sum();\n    int prefix = 0;\n\n    for (int i = 0; i < nums.length; ++i) {\n      if (prefix == sum - prefix - nums[i])\n        return i;\n      prefix += nums[i];\n    }\n\n    return -1;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  int pivotIndex(vector<int>& nums) {\n    const int sum = accumulate(begin(nums), end(nums), 0);\n    int prefix = 0;\n\n    for (int i = 0; i < nums.size(); ++i) {\n      if (prefix == sum - prefix - nums[i])\n        return i;\n      prefix += nums[i];\n    }\n\n    return -1;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/724.html",
    "category": "Algorithms",
    "acceptance_rate": 60.37610270899917,
    "topics": [
      "Array",
      "Prefix Sum"
    ],
    "hints": [
      "Create an array sumLeft where sumLeft[i] is the sum of all the numbers to the left of index i.",
      "Create an array sumRight where sumRight[i] is the sum of all the numbers to the right of index i.",
      "For each index i, check if sumLeft[i] equals sumRight[i]. If so, return i. If no such i is found, return -1."
    ],
    "likes": 8763,
    "dislikes": 894,
    "similar_questions": "[{\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Middle Index in Array\", \"titleSlug\": \"find-the-middle-index-in-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Split Array\", \"titleSlug\": \"number-of-ways-to-split-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Sum Score of Array\", \"titleSlug\": \"maximum-sum-score-of-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Left and Right Sum Differences\", \"titleSlug\": \"left-and-right-sum-differences\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1383387, \"totalSubmissionRaw\": 2291282, \"acRate\": \"60.4%\"}",
    "title_pt": "Encontrar Índice Pivô",
    "description_pt": "<p>Dado um array de inteiros <code>nums</code>, calcule o <strong>índice pivô</strong> deste array.</p>\n\n<p>O <strong>índice pivô</strong> é o índice em que a soma de todos os números <strong>estritamente</strong> à esquerda do índice é igual à soma de todos os números <strong>estritamente</strong> à direita do índice.</p>\n\n<p>Se o índice estiver na borda esquerda do array, então a soma à esquerda é <code>0</code> porque não há elementos à esquerda. Isso também se aplica à borda direita do array.</p>\n\n<p>Retorne <em>o <strong>índice pivô mais à esquerda</strong></em>. Se nenhum índice assim existir, retorne <code>-1</code>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,7,3,6,5,6]\n<strong>Saída:</strong> 3\n<strong>Explicação:</strong>\nO índice pivô é 3.\nSoma à esquerda = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nSoma à direita = nums[4] + nums[5] = 5 + 6 = 11\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [1,2,3]\n<strong>Saída:</strong> -1\n<strong>Explicação:</strong>\nNão existe nenhum índice que satisfaça as condições no enunciado do problema.</pre>\n\n<p><strong class=\"example\">Exemplo 3:</strong></p>\n\n<pre>\n<strong>Entrada:</strong> nums = [2,1,-1]\n<strong>Saída:</strong> 0\n<strong>Explicação:</strong>\nO índice pivô é 0.\nSoma à esquerda = 0 (nenhum elemento à esquerda do índice 0)\nSoma à direita = nums[1] + nums[2] = 1 + -1 = 0\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>\n\t<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>\n</ul>\n\n<p>&nbsp;</p>\n<p><strong>Nota:</strong> Esta questão é a mesma que&nbsp;1991:&nbsp;<a href=\"https://leetcode.com/problems/find-the-middle-index-in-array/\" target=\"_blank\">https://leetcode.com/problems/find-the-middle-index-in-array/</a></p>",
    "hints_pt": [
      "Dica 1: Crie um array sumLeft em que sumLeft[i] seja a soma de todos os números à esquerda do índice i.",
      "Dica 2: Crie um array sumRight em que sumRight[i] seja a soma de todos os números à direita do índice i.",
      "Dica 3: Para cada índice i, verifique se sumLeft[i] é igual a sumRight[i]. Se for, retorne i. Se nenhum i assim for encontrado, retorne -1."
    ]
  },
  {
    "difficulty": "Medium",
    "frontendQuestionId": "725",
    "paidOnly": false,
    "title": "Split Linked List in Parts",
    "titleSlug": "split-linked-list-in-parts",
    "url": "https://leetcode.com/problems/split-linked-list-in-parts",
    "description_url": "https://leetcode.com/problems/split-linked-list-in-parts/description/",
    "description": "<p>Given the <code>head</code> of a singly linked list and an integer <code>k</code>, split the linked list into <code>k</code> consecutive linked list parts.</p>\n\n<p>The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.</p>\n\n<p>The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.</p>\n\n<p>Return <em>an array of the </em><code>k</code><em> parts</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg\" style=\"width: 400px; height: 134px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3], k = 5\n<strong>Output:</strong> [[1],[2],[3],[],[]]\n<strong>Explanation:</strong>\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg\" style=\"width: 600px; height: 60px;\" />\n<pre>\n<strong>Input:</strong> head = [1,2,3,4,5,6,7,8,9,10], k = 3\n<strong>Output:</strong> [[1,2,3,4],[5,6,7],[8,9,10]]\n<strong>Explanation:</strong>\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li>The number of nodes in the list is in the range <code>[0, 1000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>1 &lt;= k &lt;= 50</code></li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/split-linked-list-in-parts/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n---\n\n### Overview\n\nWe are given a linked list `head` and an integer `k`. We want to split `head` evenly into `k` equally sized parts and return an array of the `k` parts. If `head` cannot be split evenly, the sizes of the `k` parts can differ by at most 1, with the larger parts appearing before the smaller ones.\n\n### Approach 1: Create New Parts\n\n### Intuition\n\nWe can split the linked list into `k` parts by considering two scenarios: when the list can be split evenly and when it cannot.\n\n- **Even Split**: If the list's size `size` is divisible by `k`, each part will have exactly `size / k` nodes.\n- **Uneven Split**: If `size` is not divisible by `k`, a remainder of `size % k` nodes will remain after dividing `size / k` nodes among the parts. To handle this, we add one extra node to the first `size % k` parts, making their size `size / k + 1`. The rest of the parts will have `size / k` nodes.\n\nIn short, each part will have at least `size / k` nodes. If the list doesn't split evenly, the first `size % k` parts will have one extra node.\n\nTo create these parts, we determine each part's size `currentSize`, then use a pointer to traverse the list. We visit the next `currentSize` nodes for each part and build a new linked list. Once the nodes for that part are processed, we assign the new list to the corresponding element in our array. We repeat this process for all `k` parts.\n\n### Algorithm\n\n1. Initialize `ans` array to store the `k` parts.\n2. Initialize `size = 0` and pointer `current = head`. \n3. Iterate through `head` via `current` and increment `size` at each step to find the total size of `head`.\n4. Now that `size` has the total size of the linked list, we can calculate the minimum size for the `k` parts: `splitSize = size / k`.\n5. We can also calculate how many remaining nodes we have: `numRemainingParts = size % k`. \n6. Reset `current` back to `head` so we can iterate through the linked list again to create our `k` parts.\n7. For `i` where `0 < i < k`:\n    * Initialize the head of the new part `newPart` to a dummy node and initialize a new pointer `tail` to keep track of the end of `newPart` for efficient appending\n    * Calculate the current size `currentSize` of the current part:\n        * Initialize `currentSize = splitSize`\n        * If there are any remaining parts (`numRemainingParts > 0`), then increment `currentSize` and decrement `numRemainingParts` to assign the remaining nodes to the first `size % k` parts\n    * Initialize a counter `j = 0`.\n    * While `j < currentSize`:\n        * Copy the current node and append it to `newPart` by performing `tail.next = new ListNode(current.val)`.\n        * Advance `tail` since a new node just got added to the end\n        * Advance `current` to move on to the next node\n        * Increment `j`\n    * Now that `newPart` is fully built, we can assign it in our array: `ans[i] = newPart.next`\n8. Return `ans`\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/S29dXQKK/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"S29dXQKK\"></iframe>\n\n### Complexity Analysis \n\nLet $N$ be the size of the linked list `head.`\n\n* Time Complexity: $O(N)$\n\n    We traverse the entire linked list `head` twice, where each time takes $O(N)$ time. Thus, the total time complexity is $O(N)$.\n\n* Space Complexity: $O(N)$\n\n    There are $N$ new nodes created. This results in a space complexity of $O(N)$. We ignore the $O(K)$ space needed for `ans` since the array is required for the question. \n\n### Approach 2: Modify Linked List\n\n### Intuition\n\nIn the previous approach, we required extra space because we created new nodes for the `k` parts, resulting in a space complexity of $O(N)$. In our second approach, we can modify the input linked list `head` to form the `k` parts directly, eliminating the need for extra space and reducing the space complexity to $O(1)$.\n\nAs before, we iterate through the linked list, processing the next `currentSize` nodes for each part. However, this time, when we reach the last node of a part, we set its `next` field to `null`, effectively dividing the linked list in place without creating new nodes.\n\n> Before presenting this approach to the interviewer, check if modifications are allowed. Some interviewers permit changes, while others do not.\n\n### Algorithm \n\n1. Repeat steps 1-6 from Approach 1 to calculate the total size of the linked list, as well as the minimum size of the `k` parts and the number of remainder nodes.\n2. Initialize a pointer `prev = current` to keep track of the node preceding `current`\n3. For `i` where `0 < i < k`:\n    * Initialize `newPart` to `current`, which will be the head of part `i`.\n    * Calculate the current size `currentSize` of the current part using the same logic in Approach 1\n    * Initialize a counter `j = 0`.\n    * While `j < currentSize`:\n        * Update `prev` to `current`\n        * Advance `current` to next node\n        * Increment `j`\n    * Now, `prev` is pointing to the last node of part `i`, and `current` is pointing to the head of part `i+1`. To cut off the rest of the linked list for part `i`, we reassign `prev.next` to null.\n    * Set `ans[i] = newPart`.\n4. Return `ans`\n\n### Implementation\n\n<iframe src=\"https://leetcode.com/playground/69vsAB8a/shared\" frameBorder=\"0\" width=\"100%\" height=\"500\" name=\"69vsAB8a\"></iframe>\n\n### Complexity Analysis\n\nLet $N$ be the size of the linked list `head.`\n\n* Time Complexity: $O(N)$\n\n    `head` is traversed twice, which takes $O(N)$ time.\n\n* Space Complexity: $O(1)$\n\n    In contrast to Approach 1, no new nodes are created and the input is modified to create `k` parts. Thus, the space complexity is a constant $O(1)$.",
    "solution_code_python": "\t\t\t\n\nclass Solution:\n  def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:\n    ans = [[] for _ in range(k)]\n    length = 0\n    curr = root\n    while curr:\n      length += 1\n      curr = curr.next\n    subLength = length // k\n    remainder = length % k\n\n    prev = None\n    head = root\n\n    for i in range(k):\n      ans[i] = head\n      for j in range(subLength + (1 if remainder > 0 else 0)):\n        prev = head\n        head = head.next\n      if prev:\n        prev.next = None\n      remainder -= 1\n\n    return ans",
    "solution_code_java": "\t\t\t\n\nclass Solution {\n  public ListNode[] splitListToParts(ListNode root, int k) {\n    ListNode[] ans = new ListNode[k];\n    final int length = getLength(root);\n    final int subLength = length / k;\n    int remainder = length % k;\n\n    ListNode prev = null;\n    ListNode head = root;\n\n    for (int i = 0; i < k; ++i, --remainder) {\n      ans[i] = head;\n      for (int j = 0; j < subLength + (remainder > 0 ? 1 : 0); ++j) {\n        prev = head;\n        head = head.next;\n      }\n      if (prev != null)\n        prev.next = null;\n    }\n\n    return ans;\n  }\n\n  private int getLength(ListNode root) {\n    int length = 0;\n    for (ListNode curr = root; curr != null; curr = curr.next)\n      ++length;\n    return length;\n  }\n}",
    "solution_code_cpp": "\t\t\t\n\nclass Solution {\n public:\n  vector<ListNode*> splitListToParts(ListNode* root, int k) {\n    vector<ListNode*> ans(k);\n    const int length = getLength(root);\n    const int subLength = length / k;\n    int remainder = length % k;\n\n    ListNode* prev = nullptr;\n    ListNode* head = root;\n\n    for (int i = 0; i < k; ++i, --remainder) {\n      ans[i] = head;\n      for (int j = 0; j < subLength + (remainder > 0); ++j) {\n        prev = head;\n        head = head->next;\n      }\n      if (prev != nullptr)\n        prev->next = nullptr;\n    }\n\n    return ans;\n  }\n\n private:\n  int getLength(ListNode* root) {\n    int length = 0;\n    for (ListNode* curr = root; curr; curr = curr->next)\n      ++length;\n    return length;\n  }\n};",
    "solution_code_url": "https://leetcodehelp.github.io/725.html",
    "category": "Algorithms",
    "acceptance_rate": 70.14628519570071,
    "topics": [
      "Linked List"
    ],
    "hints": [
      "If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one."
    ],
    "likes": 4553,
    "dislikes": 366,
    "similar_questions": "[{\"title\": \"Rotate List\", \"titleSlug\": \"rotate-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Odd Even Linked List\", \"titleSlug\": \"odd-even-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split a Circular Linked List\", \"titleSlug\": \"split-a-circular-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
    "stats": "{\"totalAccepted\": \"330.8K\", \"totalSubmission\": \"471.6K\", \"totalAcceptedRaw\": 330818, \"totalSubmissionRaw\": 471612, \"acRate\": \"70.1%\"}",
    "title_pt": "Dividir Lista Encadeada em Partes",
    "description_pt": "<p>Dado o <code>head</code> de uma lista encadeada simplesmente encadeada e um inteiro <code>k</code>, divida a lista encadeada em <code>k</code> partes consecutivas de lista encadeada.</p>\n\n<p>O comprimento de cada parte deve ser o mais igual possível: nenhuma duas partes devem ter tamanhos que difiram por mais de um. Isso pode levar a algumas partes sendo null.</p>\n\n<p>As partes devem estar na ordem de ocorrência na lista de entrada, e as partes que ocorrem antes devem sempre ter tamanho maior ou igual ao das partes que ocorrem depois.</p>\n\n<p>Retorne <em>um array das </em><code>k</code><em> partes</em>.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Exemplo 1:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/13/split1-lc.jpg\" style=\"width: 400px; height: 134px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3], k = 5\n<strong>Saída:</strong> [[1],[2],[3],[],[]]\n<strong>Explicação:</strong>\nO primeiro elemento output[0] tem output[0].val = 1, output[0].next = null.\nO último elemento output[4] é null, mas sua representação como string como um ListNode é [].\n</pre>\n\n<p><strong class=\"example\">Exemplo 2:</strong></p>\n<img alt=\"\" src=\"https://assets.leetcode.com/uploads/2021/06/13/split2-lc.jpg\" style=\"width: 600px; height: 60px;\" />\n<pre>\n<strong>Entrada:</strong> head = [1,2,3,4,5,6,7,8,9,10], k = 3\n<strong>Saída:</strong> [[1,2,3,4],[5,6,7],[8,9,10]]\n<strong>Explicação:</strong>\nA entrada foi dividida em partes consecutivas com diferença de tamanho de no máximo 1, e as partes anteriores têm tamanho maior do que as partes posteriores.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Restrições:</strong></p>\n\n<ul>\n\t<li>O número de nós na lista está no intervalo <code>[0, 1000]</code>.</li>\n\t<li><code>0 &lt;= Node.val &lt;= 1000</code></li>\n\t<li><code>1 &lt;= k &lt;= 50</code></li>\n</ul>",
    "hints_pt": [
      "- Dica 1: Se houver N nós na lista, e k partes, então cada parte tem N/k elementos, exceto as primeiras N%k partes, que têm um elemento extra."
    ]
  },
  {
    "difficulty": "Hard",
    "frontendQuestionId": "726",
    "paidOnly": false,
    "title": "Number of Atoms",
    "titleSlug": "number-of-atoms",
    "url": "https://leetcode.com/problems/number-of-atoms",
    "description_url": "https://leetcode.com/problems/number-of-atoms/description/",
    "description": "<p>Given a string <code>formula</code> representing a chemical formula, return <em>the count of each atom</em>.</p>\n\n<p>The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.</p>\n\n<p>One or more digits representing that element&#39;s count may follow if the count is greater than <code>1</code>. If the count is <code>1</code>, no digits will follow.</p>\n\n<ul>\n\t<li>For example, <code>&quot;H2O&quot;</code> and <code>&quot;H2O2&quot;</code> are possible, but <code>&quot;H1O2&quot;</code> is impossible.</li>\n</ul>\n\n<p>Two formulas are concatenated together to produce another formula.</p>\n\n<ul>\n\t<li>For example, <code>&quot;H2O2He3Mg4&quot;</code> is also a formula.</li>\n</ul>\n\n<p>A formula placed in parentheses, and a count (optionally added) is also a formula.</p>\n\n<ul>\n\t<li>For example, <code>&quot;(H2O2)&quot;</code> and <code>&quot;(H2O2)3&quot;</code> are formulas.</li>\n</ul>\n\n<p>Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than <code>1</code>), followed by the second name (in sorted order), followed by its count (if that count is more than <code>1</code>), and so on.</p>\n\n<p>The test cases are generated so that all the values in the output fit in a <strong>32-bit</strong> integer.</p>\n\n<p>&nbsp;</p>\n<p><strong class=\"example\">Example 1:</strong></p>\n\n<pre>\n<strong>Input:</strong> formula = &quot;H2O&quot;\n<strong>Output:</strong> &quot;H2O&quot;\n<strong>Explanation:</strong> The count of elements are {&#39;H&#39;: 2, &#39;O&#39;: 1}.\n</pre>\n\n<p><strong class=\"example\">Example 2:</strong></p>\n\n<pre>\n<strong>Input:</strong> formula = &quot;Mg(OH)2&quot;\n<strong>Output:</strong> &quot;H2MgO2&quot;\n<strong>Explanation:</strong> The count of elements are {&#39;H&#39;: 2, &#39;Mg&#39;: 1, &#39;O&#39;: 2}.\n</pre>\n\n<p><strong class=\"example\">Example 3:</strong></p>\n\n<pre>\n<strong>Input:</strong> formula = &quot;K4(ON(SO3)2)2&quot;\n<strong>Output:</strong> &quot;K4N2O14S4&quot;\n<strong>Explanation:</strong> The count of elements are {&#39;K&#39;: 4, &#39;N&#39;: 2, &#39;O&#39;: 14, &#39;S&#39;: 4}.\n</pre>\n\n<p>&nbsp;</p>\n<p><strong>Constraints:</strong></p>\n\n<ul>\n\t<li><code>1 &lt;= formula.length &lt;= 1000</code></li>\n\t<li><code>formula</code> consists of English letters, digits, <code>&#39;(&#39;</code>, and <code>&#39;)&#39;</code>.</li>\n\t<li><code>formula</code> is always valid.</li>\n</ul>\n",
    "solution_url": "https://leetcode.com/problems/number-of-atoms/solutions/",
    "solution": "[TOC]\n\n## Solution\n\n--- \n\n### Overview\n\nIn this problem, we are given a string `formula`, which represents a **valid** chemical formula. The `formula` follows certain rules, as mentioned in the problem description. We are supposed to return the count of each atom in the formula.\n\n> An atom contains a UPPERCASE letter followed by zero or more lowercase letters. \n\nSince the problem revolves around `formula`, let's dissect the `formula` and understand what it contains.\n\nA `formula` can contain the following\n\n- **UPPERCASE LETTER**: `A`, `B` ... `Z`. Let's denote the group as **U**.\n\n- **lowercase letter**: `a`, `b` ... `z`. Let's denote the group as **L**.\n\n- **Digits**: `0`, `1` ... `9`. Let's denote the group as **D**.\n\n- **Left Parenthesis**: `(`\n\n- **Right Parenthesis**: `)`\n\nCan we have **L** followed by **D**?   \nYes, the formula can contain a lowercase letter followed by a digit.\n\nCan we have **D** followed by **L**?  \nNo, the formula cannot contain a digit followed by a lowercase letter. An atom begins with a UPPERCASE letter.\n\nHence, only certain groups can be followed by certain groups. Let's summarise it in a table. The (row, column) of this table comments on whether the group in the row can be followed by the group in the column, and further explains the significance of the combination.\n\n|   | **U** | **L** | **D** | `(` | `)` |\n|---|---|---|---|---|---|\n| **U** | Yes. It will signify that the current atom has a one-character representation with an immediate count as 1 | Yes. It will signify that the current atom has a multi-character representation | Yes. It will signify that the current atom has a one-character representation with a count greater than 1 | Yes. It will signify that the current atom has a one-character representation with an immediate count as 1 | Yes. It will signify that the current atom has a one-character representation with an immediate count as 1 |\n| **L** | Yes. It signifies that the atom of which this lowercase letter is a part has a multi-character representation with an immediate count as 1 | Yes. It signifies that the atom of which this lowercase letter is a part has a multi-character representation | Yes. It signifies that the atom of which this lowercase letter is a part has a multi-character representation with a count greater than 1 | Yes. It signifies that the atom of which this lowercase letter is a part has a multi-character representation with an immediate count as 1 | Yes. It signifies that the atom of which this lowercase letter is a part has multi-character representation with immediate count as 1 |\n| **D** | Yes. The immediate count of the current atom is greater than 1 | No. A digit cannot be followed by a lowercase letter | Yes. The immediate count of the current atom is greater than or equal to 10 | Yes. The immediate count of the current ato