title stringlengths 1 100 | titleSlug stringlengths 3 77 | Java int64 0 1 | Python3 int64 1 1 | content stringlengths 28 44.4k | voteCount int64 0 3.67k | question_content stringlengths 65 5k | question_hints stringclasses 970
values |
|---|---|---|---|---|---|---|---|
🔥 [Python3] Optimized Heap solution || beats 99.7% 🥷🏼 | kth-largest-element-in-a-stream | 0 | 1 | ### Time and space complexity:\nConsider:\n**N** \u2014 number of elements in the heap,\n**M** \u2014 number elements in initial nums\n**P** \u2014 number of cals method add() :\n**Time complexity is:`O(N + (M-N)log(N) + Plog(N) )` or `O(N + (M+P-N)log(N))`\nSpace complexity is: `O(N)`**\n**M+P** constant can be reduce... | 9 | Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
Implement `KthLargest` class:
* `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
* `int add(int... | null |
🔥 [Python3] Optimized Heap solution || beats 99.7% 🥷🏼 | kth-largest-element-in-a-stream | 0 | 1 | ### Time and space complexity:\nConsider:\n**N** \u2014 number of elements in the heap,\n**M** \u2014 number elements in initial nums\n**P** \u2014 number of cals method add() :\n**Time complexity is:`O(N + (M-N)log(N) + Plog(N) )` or `O(N + (M+P-N)log(N))`\nSpace complexity is: `O(N)`**\n**M+P** constant can be reduce... | 9 | You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point `[0, 0]`, and you are given a destination point `target = [xtarget, ytarget]` that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array `ghosts`, where `ghosts[i] = [xi, y... | null |
Awesome O(Log N) time complexity | binary-search | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 4 | Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,... | null |
Awesome O(Log N) time complexity | binary-search | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 4 | Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For exa... | null |
✔Beats 99.49% TC || Python Solution | binary-search | 0 | 1 | \n\n\n\n# Code\n```\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums) - 1\n if len(nums) == 1 and nums[0] == target:\... | 2 | Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,... | null |
✔Beats 99.49% TC || Python Solution | binary-search | 0 | 1 | \n\n\n\n# Code\n```\nclass Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums) - 1\n if len(nums) == 1 and nums[0] == target:\... | 2 | Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For exa... | null |
simple one liners for each def | design-hashset | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
simple one liners for each def | design-hashset | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
✅Python3 || C++|| Java✅ [Beats 97%] | design-hashset | 1 | 1 | # Please Upvote \uD83D\uDE07\n# Before\n# Python3\n```\nclass MyHashSet:\n\n def __init__(self):\n self.mp=defaultdict(int)\n \n\n def add(self, key: int) -> None:\n self.mp[key]=True\n \n\n def remove(self, key: int) -> None:\n self.mp[key]=False\n\n def contains(self, ke... | 53 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
✅Python3 || C++|| Java✅ [Beats 97%] | design-hashset | 1 | 1 | # Please Upvote \uD83D\uDE07\n# Before\n# Python3\n```\nclass MyHashSet:\n\n def __init__(self):\n self.mp=defaultdict(int)\n \n\n def add(self, key: int) -> None:\n self.mp[key]=True\n \n\n def remove(self, key: int) -> None:\n self.mp[key]=False\n\n def contains(self, ke... | 53 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
PYTHON3 SOLUTION | design-hashset | 0 | 1 | # Code\n```\nclass MyHashSet:\n\n def __init__(self):\n self.arr = set()\n \n def add(self, key: int) -> None:\n self.arr.update({key})\n\n def remove(self, key: int) -> None:\n if key in self.arr:\n self.arr.remove(key)\n return True\n\n def contains(self, ... | 2 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
PYTHON3 SOLUTION | design-hashset | 0 | 1 | # Code\n```\nclass MyHashSet:\n\n def __init__(self):\n self.arr = set()\n \n def add(self, key: int) -> None:\n self.arr.update({key})\n\n def remove(self, key: int) -> None:\n if key in self.arr:\n self.arr.remove(key)\n return True\n\n def contains(self, ... | 2 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | design-hashset | 1 | 1 | **!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u... | 26 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand | design-hashset | 1 | 1 | **!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u... | 26 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
Solution | design-hashset | 1 | 1 | ```C++ []\nclass MyHashSet {\npublic:\n vector<bool> ans;\n MyHashSet() {\n ans.resize(1e6+1,false);\n }\n void add(int key) {\n ans[key]=true;\n }\n void remove(int key) {\n ans[key]=false;\n }\n bool contains(int key) {\n return ans[key];\n }\n};\n```\n\n```P... | 3 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
Solution | design-hashset | 1 | 1 | ```C++ []\nclass MyHashSet {\npublic:\n vector<bool> ans;\n MyHashSet() {\n ans.resize(1e6+1,false);\n }\n void add(int key) {\n ans[key]=true;\n }\n void remove(int key) {\n ans[key]=false;\n }\n bool contains(int key) {\n return ans[key];\n }\n};\n```\n\n```P... | 3 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
✔️ [Python] Simple, Easy Solution with HashTable, Array and LinkedList | design-hashset | 0 | 1 | #### Approach-1: Using Dictionary\n\n```\nclass MyHashSet:\n\n def __init__(self):\n self.d = {}\n\n def add(self, key: int) -> None:\n self.d[key] = 1\n\n def remove(self, key: int) -> None:\n self.d[key] = 0\n\n def contains(self, key: int) -> bool:\n return self.d.get(key,0)!=... | 20 | Design a HashSet without using any built-in hash table libraries.
Implement `MyHashSet` class:
* `void add(key)` Inserts the value `key` into the HashSet.
* `bool contains(key)` Returns whether the value `key` exists in the HashSet or not.
* `void remove(key)` Removes the value `key` in the HashSet. If `key` do... | null |
✔️ [Python] Simple, Easy Solution with HashTable, Array and LinkedList | design-hashset | 0 | 1 | #### Approach-1: Using Dictionary\n\n```\nclass MyHashSet:\n\n def __init__(self):\n self.d = {}\n\n def add(self, key: int) -> None:\n self.d[key] = 1\n\n def remove(self, key: int) -> None:\n self.d[key] = 0\n\n def contains(self, key: int) -> bool:\n return self.d.get(key,0)!=... | 20 | We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for wh... | null |
✅ 85.31% Hash Map | design-hashmap | 0 | 1 | # Intuition\n\nWhen we think of a HashMap or a Dictionary, we imagine a structure where we store key-value pairs. We want quick access to values given a key. But how do we achieve that?\n\nWell, one simple idea is to convert the key to an integer (if it isn\'t already), then use that integer to index into an array, and... | 26 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
✅ 85.31% Hash Map | design-hashmap | 0 | 1 | # Intuition\n\nWhen we think of a HashMap or a Dictionary, we imagine a structure where we store key-value pairs. We want quick access to values given a key. But how do we achieve that?\n\nWell, one simple idea is to convert the key to an integer (if it isn\'t already), then use that integer to index into an array, and... | 26 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3 | design-hashmap | 1 | 1 | # Intuition adn approach discussed in detail in video solution\nhttps://youtu.be/IF0Yv0XWLdc\n# Code\nJava\n```\nclass MyHashMap {\n //this array as will be used our hash map\n // the keys will be your indicies of the array and values will \n // elements stored at those indicies \n int map[] = null;\n pu... | 2 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3 | design-hashmap | 1 | 1 | # Intuition adn approach discussed in detail in video solution\nhttps://youtu.be/IF0Yv0XWLdc\n# Code\nJava\n```\nclass MyHashMap {\n //this array as will be used our hash map\n // the keys will be your indicies of the array and values will \n // elements stored at those indicies \n int map[] = null;\n pu... | 2 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
TC O(1) SC O(10^6) beginner friendly solution using array easy to understand | design-hashmap | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we will use O(10^6) Extra space using array\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is basically a simple solution and we take an Array of size 10^6+1, Initialize all the elements in the array from ... | 2 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
TC O(1) SC O(10^6) beginner friendly solution using array easy to understand | design-hashmap | 1 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we will use O(10^6) Extra space using array\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis is basically a simple solution and we take an Array of size 10^6+1, Initialize all the elements in the array from ... | 2 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
Easiest way to Design HaspMap in Python | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization (Constructor):\n\n- - In the constructor __init__(), the MyHashMap class initializes its attributes.\n- - self.size represents the number of buckets... | 4 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
Easiest way to Design HaspMap in Python | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization (Constructor):\n\n- - In the constructor __init__(), the MyHashMap class initializes its attributes.\n- - self.size represents the number of buckets... | 4 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
One-Liner Short and Concise TC: O(1) SC: O(N) | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1) for put and get operations.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) where N is 10^6\... | 1 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
One-Liner Short and Concise TC: O(1) SC: O(N) | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(1) for put and get operations.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) where N is 10^6\... | 1 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
1 Line functions - Simple Approach - O(1) Get, Put, Remove | design-hashmap | 0 | 1 | # Intuition\nUsed constraints to assist with finding solution.\n\n# Approach\nDefine array with -1 as default value, if the value doesn\'t exist in a get we\'ll return a -1, otherwise just overwrite.\n\n# Complexity\n- Time complexity:\nGET: $$O(1)$$\nPUT: $$O(1)$$\nREMOVE: $$O(1)$$\n\nindex the array / key / index\n\n... | 1 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
1 Line functions - Simple Approach - O(1) Get, Put, Remove | design-hashmap | 0 | 1 | # Intuition\nUsed constraints to assist with finding solution.\n\n# Approach\nDefine array with -1 as default value, if the value doesn\'t exist in a get we\'ll return a -1, otherwise just overwrite.\n\n# Complexity\n- Time complexity:\nGET: $$O(1)$$\nPUT: $$O(1)$$\nREMOVE: $$O(1)$$\n\nindex the array / key / index\n\n... | 1 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
Python3 Solution | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
Python3 Solution | design-hashmap | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
Beginner-friendly || Simple solution with HashMap in Python3/TypeScript | design-hashmap | 0 | 1 | # Intuition\nOur goal is to design the [HashMap DS](https://en.wikipedia.org/wiki/Hash_table).\n\n```\n# This data structure is one of common in using.\n\n# The approximated inner implementation is to map KEYS to VALUES.\n# {"1": "test", "2": "test1"}\n\n# At most cases a key has a string/integer type, while a value\n#... | 1 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
Beginner-friendly || Simple solution with HashMap in Python3/TypeScript | design-hashmap | 0 | 1 | # Intuition\nOur goal is to design the [HashMap DS](https://en.wikipedia.org/wiki/Hash_table).\n\n```\n# This data structure is one of common in using.\n\n# The approximated inner implementation is to map KEYS to VALUES.\n# {"1": "test", "2": "test1"}\n\n# At most cases a key has a string/integer type, while a value\n#... | 1 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
【Video】How we think about a solution - Python, JavaScript, Java, C++ | design-hashmap | 1 | 1 | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nUsing Linked List t... | 24 | Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* ... | null |
【Video】How we think about a solution - Python, JavaScript, Java, C++ | design-hashmap | 1 | 1 | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nUsing Linked List t... | 24 | You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head... | null |
One Liner/List 98%Beast | design-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 3 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
One Liner/List 98%Beast | design-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 3 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
Very Clean Python Solution | design-linked-list | 0 | 1 | Hope this helps someone.\n\n```\nclass ListNode:\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass MyLinkedList(object):\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.head = None\n self.size = 0\n\n def g... | 128 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
Very Clean Python Solution | design-linked-list | 0 | 1 | Hope this helps someone.\n\n```\nclass ListNode:\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass MyLinkedList(object):\n def __init__(self):\n """\n Initialize your data structure here.\n """\n self.head = None\n self.size = 0\n\n def g... | 128 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
Quite Ordinary Solution | design-linked-list | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Node:\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass MyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.lenn = 0\n \n\n... | 9 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
Quite Ordinary Solution | design-linked-list | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Node:\n def __init__(self, val):\n self.val = val\n self.next = None\n\n\nclass MyLinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.lenn = 0\n \n\n... | 9 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
[Python] | [Java] | Dummy Head Node | Very Clean | Easy to Understand | design-linked-list | 1 | 1 | # Approach\nEmploy dummy head node in initializing and traversing linked list.\n\n# Complexity\n- Time complexity: O(1) for addAtHead, O(n) for others\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Python []\nclass... | 1 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
[Python] | [Java] | Dummy Head Node | Very Clean | Easy to Understand | design-linked-list | 1 | 1 | # Approach\nEmploy dummy head node in initializing and traversing linked list.\n\n# Complexity\n- Time complexity: O(1) for addAtHead, O(n) for others\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Python []\nclass... | 1 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
Solution | design-linked-list | 1 | 1 | ```C++ []\nclass MyLinkedList {\npublic:\n vector<int>ans;\n MyLinkedList() {\n }\n int get(int index) {\n for(int i=0;i<ans.size();i++){\n if(i==index)\n return ans[i];\n } \n return -1;\n }\n void addAtHead(int val) {\n ans.insert(ans.begin(),val);\n }\n ... | 2 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
Solution | design-linked-list | 1 | 1 | ```C++ []\nclass MyLinkedList {\npublic:\n vector<int>ans;\n MyLinkedList() {\n }\n int get(int index) {\n for(int i=0;i<ans.size();i++){\n if(i==index)\n return ans[i];\n } \n return -1;\n }\n void addAtHead(int val) {\n ans.insert(ans.begin(),val);\n }\n ... | 2 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
[Python] Singly Linked List & Double Linked List - Clean & Concise | design-linked-list | 0 | 1 | ## 1. Singly Linked List\n<iframe src="https://leetcode.com/playground/FMRev7Ba/shared" frameBorder="0" width="100%" height="920"></iframe>\n\nComplexity:\n- Time: where `N` is length of `nums` array.\n - `get`: O(N)\n - `addAtHead`: O(1)\n - `addAtTail`: O(N), can optimize to (1) if we store `tail` pointer\n ... | 18 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
[Python] Singly Linked List & Double Linked List - Clean & Concise | design-linked-list | 0 | 1 | ## 1. Singly Linked List\n<iframe src="https://leetcode.com/playground/FMRev7Ba/shared" frameBorder="0" width="100%" height="920"></iframe>\n\nComplexity:\n- Time: where `N` is length of `nums` array.\n - `get`: O(N)\n - `addAtHead`: O(1)\n - `addAtTail`: O(N), can optimize to (1) if we store `tail` pointer\n ... | 18 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
Explained Implementation (Python3) | design-linked-list | 0 | 1 | Hope it is helpful to you\n\n```\n"""\n Singly LinkedList Implementation\n"""\n\nclass ListNode:\n """\n Init ListNode Object\n """\n def __init__(self, val):\n self.val = val \n self.next = None\n \nclass MyLinkedList(object):\n """\n Init your data structure \n """\n #T... | 13 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
Explained Implementation (Python3) | design-linked-list | 0 | 1 | Hope it is helpful to you\n\n```\n"""\n Singly LinkedList Implementation\n"""\n\nclass ListNode:\n """\n Init ListNode Object\n """\n def __init__(self, val):\n self.val = val \n self.next = None\n \nclass MyLinkedList(object):\n """\n Init your data structure \n """\n #T... | 13 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
All time easiest solution | design-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
All time easiest solution | design-linked-list | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
87% TC and 85% Sc easy python solution using singly linked list | design-linked-list | 0 | 1 | ```\nclass Node:\n def __init__(self, val, n=None):\n self.val = val\n self.next = n\nclass MyLinkedList: \n def __init__(self):\n self.head = None\n self.tail = None\n self.l = 0\n\n def get(self, index: int) -> int:\n if(index >= self.l):\n return -1\n ... | 1 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
87% TC and 85% Sc easy python solution using singly linked list | design-linked-list | 0 | 1 | ```\nclass Node:\n def __init__(self, val, n=None):\n self.val = val\n self.next = n\nclass MyLinkedList: \n def __init__(self):\n self.head = None\n self.tail = None\n self.l = 0\n\n def get(self, index: int) -> int:\n if(index >= self.l):\n return -1\n ... | 1 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
EAZY PYTHON SOLUTION | design-linked-list | 0 | 1 | ```\nclass ListNode: \n def __init__(self,val, next = None):\n self.val = val\n self.next = next\n\nclass MyLinkedList:\n def __init__(self):\n self.head = None\n self.size = 0 \n \n def get(self, index: int) -> int:\n if index >= self.size:\n return -1\n ... | 2 | Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: `val` and `next`. `val` is the value of the current node, and `next` is a pointer/reference to the next node.
If you want to use the doubly linked list, you... | null |
EAZY PYTHON SOLUTION | design-linked-list | 0 | 1 | ```\nclass ListNode: \n def __init__(self,val, next = None):\n self.val = val\n self.next = next\n\nclass MyLinkedList:\n def __init__(self):\n self.head = None\n self.size = 0 \n \n def get(self, index: int) -> int:\n if index >= self.size:\n return -1\n ... | 2 | There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the righ... | null |
toLowerCase | to-lower-case | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n answerString = ""\n for i in s:\n if \'A\' <= i <= \'Z\':\n answerString = answerString + chr(ord(i)+32)\n else:\n answerString = answerString + i\n\n return answerStri... | 1 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
toLowerCase | to-lower-case | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n answerString = ""\n for i in s:\n if \'A\' <= i <= \'Z\':\n answerString = answerString + chr(ord(i)+32)\n else:\n answerString = answerString + i\n\n return answerStri... | 1 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
Python one liner | to-lower-case | 0 | 1 | # Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n \n``` | 1 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
Python one liner | to-lower-case | 0 | 1 | # Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n \n``` | 1 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
🔥Simple ASCII-Based Uppercase to Lowercase Transformation🔥 | to-lower-case | 0 | 1 | \n# Approach\n1. Iterate through the input string character by character.\n2. For each character, check if it\'s an uppercase letter by comparing its ASCII code with the range [65, 90], which corresponds to \'A\' to \'Z\'.\n3. If an uppercase character is found, convert it to lowercase by adding 32 to its ASCII code us... | 1 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
🔥Simple ASCII-Based Uppercase to Lowercase Transformation🔥 | to-lower-case | 0 | 1 | \n# Approach\n1. Iterate through the input string character by character.\n2. For each character, check if it\'s an uppercase letter by comparing its ASCII code with the range [65, 90], which corresponds to \'A\' to \'Z\'.\n3. If an uppercase character is found, convert it to lowercase by adding 32 to its ASCII code us... | 1 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
One Line Code | to-lower-case | 0 | 1 | \n\n# Complexity\n- Time complexity: Faster than 88=%\n\n- Space complexity: 95.36%\n\n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n``` | 1 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
One Line Code | to-lower-case | 0 | 1 | \n\n# Complexity\n- Time complexity: Faster than 88=%\n\n- Space complexity: 95.36%\n\n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n``` | 1 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
ASCII Code || Simply Method | to-lower-case | 0 | 1 | # Intuition\nThe first thought that comes to mind when trying to convert a string to lowercase is to loop through the string character by character and check if each character is uppercase. If it is, we can convert it to lowercase by adding 32 to its ASCII code.\n\n\n# Approach\nThe approach is straightforward and eff... | 5 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
ASCII Code || Simply Method | to-lower-case | 0 | 1 | # Intuition\nThe first thought that comes to mind when trying to convert a string to lowercase is to loop through the string character by character and check if each character is uppercase. If it is, we can convert it to lowercase by adding 32 to its ASCII code.\n\n\n# Approach\nThe approach is straightforward and eff... | 5 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
1 Line solution | to-lower-case | 0 | 1 | \n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n``` | 1 | Given a string `s`, return _the string after replacing every uppercase letter with the same lowercase letter_.
**Example 1:**
**Input:** s = "Hello "
**Output:** "hello "
**Example 2:**
**Input:** s = "here "
**Output:** "here "
**Example 3:**
**Input:** s = "LOVELY "
**Output:** "lovely "
**Constraints:**... | null |
1 Line solution | to-lower-case | 0 | 1 | \n# Code\n```\nclass Solution:\n def toLowerCase(self, s: str) -> str:\n return s.lower()\n``` | 1 | Given the `root` of a binary tree where every node has **a unique value** and a target integer `k`, return _the value of the **nearest leaf node** to the target_ `k` _in the tree_.
**Nearest to a leaf** means the least number of edges traveled on the binary tree to reach any leaf of the tree. Also, a node is called a ... | 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. Think ASCII! Think about the different capital letters and their ASCII codes and how that relates to their ... |
710. Random Pick with Blacklist - Beats 100% | random-pick-with-blacklist | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n ***$$O(1)$$*** \n\n---\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n---\n\n# Code\n```\nk = 10\nclass Solution:\n def __init__(self, n: int, blacklist: List[int]):\n self.da... | 1 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
710. Random Pick with Blacklist - Beats 100% | random-pick-with-blacklist | 0 | 1 | # Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n ***$$O(1)$$*** \n\n---\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n---\n\n# Code\n```\nk = 10\nclass Solution:\n def __init__(self, n: int, blacklist: List[int]):\n self.da... | 1 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Solution | random-pick-with-blacklist | 1 | 1 | ```C++ []\nstatic const auto init = []{\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n return false;\n}();\nint prefsum[100005];\nint psz = 0;\n\nclass Solution {\npublic:\n Solution(int n, vector<int>& blacklist) {\n ::sort(begin(blacklist), end(blacklist));\n psz = 0;\n int pre ... | 1 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
Solution | random-pick-with-blacklist | 1 | 1 | ```C++ []\nstatic const auto init = []{\n cin.tie(nullptr);\n ios::sync_with_stdio(false);\n return false;\n}();\nint prefsum[100005];\nint psz = 0;\n\nclass Solution {\npublic:\n Solution(int n, vector<int>& blacklist) {\n ::sort(begin(blacklist), end(blacklist));\n psz = 0;\n int pre ... | 1 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
[Python] pick from list of valid ranges | random-pick-with-blacklist | 0 | 1 | ```\n"""\nStore array of valid ranges, then pick random range, and random\nvalue from that range.\n"""\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n self.n = n\n self.r = []\n\n if not blacklist:\n self.r.append((0, n - 1))\n return\n\n b =... | 1 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
[Python] pick from list of valid ranges | random-pick-with-blacklist | 0 | 1 | ```\n"""\nStore array of valid ranges, then pick random range, and random\nvalue from that range.\n"""\nclass Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n self.n = n\n self.r = []\n\n if not blacklist:\n self.r.append((0, n - 1))\n return\n\n b =... | 1 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
[Python3] hash solution using dict (92.28%) | random-pick-with-blacklist | 0 | 1 | Hash map blacklisted value in `[0, N-len(blacklist))` to whitelisted value in `[N-len(blacklist), N)`, and then randomly pick number in `[0, N-len(blacklist))`. \n```\nfrom random import randint\n\nclass Solution:\n\n def __init__(self, N: int, blacklist: List[int]):\n blacklist = set(blacklist) #to avoid TL... | 35 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
[Python3] hash solution using dict (92.28%) | random-pick-with-blacklist | 0 | 1 | Hash map blacklisted value in `[0, N-len(blacklist))` to whitelisted value in `[N-len(blacklist), N)`, and then randomly pick number in `[0, N-len(blacklist))`. \n```\nfrom random import randint\n\nclass Solution:\n\n def __init__(self, N: int, blacklist: List[int]):\n blacklist = set(blacklist) #to avoid TL... | 35 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Python Optimal Method Using Hash Table and Dividing Array | random-pick-with-blacklist | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have 0 to n - len(blacklist) choices. This may contain bad numbers.\n\nConsider 0 - goodIntervalEnd as the left side, and goodIntervalEnd to n as right side.\n\nWe want left side to hold all good numbers, and if there are bad numbers, ... | 0 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
Python Optimal Method Using Hash Table and Dividing Array | random-pick-with-blacklist | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have 0 to n - len(blacklist) choices. This may contain bad numbers.\n\nConsider 0 - goodIntervalEnd as the left side, and goodIntervalEnd to n as right side.\n\nWe want left side to hold all good numbers, and if there are bad numbers, ... | 0 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Python A Multi-modal Approach (Runtime 75%) | random-pick-with-blacklist | 0 | 1 | # Intuition\nBasically, when dealing with random generation over a large range and with blacklists, there are two general approaches:\n\n1. Create a uniform mapping between blacklisted numbers and valid numbers, so whenever we encounter a blacklisted result, we can immediately look up its mapped value.\n2. Use the stra... | 0 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
Python A Multi-modal Approach (Runtime 75%) | random-pick-with-blacklist | 0 | 1 | # Intuition\nBasically, when dealing with random generation over a large range and with blacklists, there are two general approaches:\n\n1. Create a uniform mapping between blacklisted numbers and valid numbers, so whenever we encounter a blacklisted result, we can immediately look up its mapped value.\n2. Use the stra... | 0 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
random pick with blacklist | random-pick-with-blacklist | 0 | 1 | \nclass Solution:\n def __init__(self, N: int, blacklist: List[int]):\n # return range from 0 to n-len(blacklist)\n self.sz = N - len(blacklist)\n # give bigger val to elements in blacklist in order to avoid pick\n self.mapping = {}\n for b in blacklist:\n self.mapping[b... | 0 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
random pick with blacklist | random-pick-with-blacklist | 0 | 1 | \nclass Solution:\n def __init__(self, N: int, blacklist: List[int]):\n # return range from 0 to n-len(blacklist)\n self.sz = N - len(blacklist)\n # give bigger val to elements in blacklist in order to avoid pick\n self.mapping = {}\n for b in blacklist:\n self.mapping[b... | 0 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Python3 Solution | random-pick-with-blacklist | 0 | 1 | # Intuition\nInspired by labuladong\'s note, we could consider the range from 0 to $$n$$ as an array, and switch elements in the `blacklist` to the end of this array to minimize the time complexity.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n1. The `Solution` class is initiali... | 0 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
Python3 Solution | random-pick-with-blacklist | 0 | 1 | # Intuition\nInspired by labuladong\'s note, we could consider the range from 0 to $$n$$ as an array, and switch elements in the `blacklist` to the end of this array to minimize the time complexity.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\n1. The `Solution` class is initiali... | 0 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Simple python solution | random-pick-with-blacklist | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(B) preprocessing; O(1) for pick\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(B)\n<!-- Add your ... | 0 | You are given an integer `n` and an array of **unique** integers `blacklist`. Design an algorithm to pick a random integer in the range `[0, n - 1]` that is **not** in `blacklist`. Any integer that is in the mentioned range and not in `blacklist` should be **equally likely** to be returned.
Optimize your algorithm suc... | null |
Simple python solution | random-pick-with-blacklist | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(B) preprocessing; O(1) for pick\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(B)\n<!-- Add your ... | 0 | Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**.
A **full binary tree** is a binary tr... | null |
Python3 Solution | minimum-ascii-delete-sum-for-two-strings | 0 | 1 | \n```\nclass Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n n=len(s1)\n m=len(s2)\n dp=[[0 for x in range(m+1)] for x in range(n+1)]\n for i in range(1,n+1):\n dp[i][0]=dp[i-1][0]+ord(s1[i-1])\n\n for i in range(1,m+1):\n dp[0][i]=dp[0][i-1... | 6 | Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to ... | Let dp(i, j) be the answer for inputs s1[i:] and s2[j:]. |
🔥 100% DP [VIDEO] Decoding Approach to Minimum ASCII Delete Sum 📝 | minimum-ascii-delete-sum-for-two-strings | 1 | 1 | # Intuition\nThe problem is asking us to make two strings equal by deleting characters, while also minimizing the sum of the ASCII values of the deleted characters. This immediately brings to mind dynamic programming, as we can leverage the overlapping subproblems inherent in this task - that is, making smaller substri... | 24 | Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to ... | Let dp(i, j) be the answer for inputs s1[i:] and s2[j:]. |
Variation of the [1143. Longest Common Subsequence] problem | minimum-ascii-delete-sum-for-two-strings | 1 | 1 | # Similar Problem:\nVery popular problem: [1143. Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/description/)\n\n# Intuition\nBasic recursion + memoization problem.\n\n- Start from `i=0, j=0`\n- Each time compare `s1.charAt(i)` with `s2.charAt(j)`.\n- If they are equal, move to `re... | 3 | Given two strings `s1` and `s2`, return _the lowest **ASCII** sum of deleted characters to make two strings equal_.
**Example 1:**
**Input:** s1 = "sea ", s2 = "eat "
**Output:** 231
**Explanation:** Deleting "s " from "sea " adds the ASCII value of "s " (115) to the sum.
Deleting "t " from "eat " adds 116 to ... | Let dp(i, j) be the answer for inputs s1[i:] and s2[j:]. |
Solution | subarray-product-less-than-k | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int numSubarrayProductLessThanK(vector<int>& nums, int k) {\n ios_base::sync_with_stdio(false);\n cin.tie(0); cout.tie(0);\n int j=0;\n int n=nums.size();\n int s=1;\n int c=0;\n for(int i=0;i<n;i++)\n {\n s*=nums[i];\n ... | 2 | Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
... | 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. |
Python Simple Solution Explained (video + code) (Fastest) | subarray-product-less-than-k | 0 | 1 | [](https://www.youtube.com/watch?v=4775IgUKfww)\nhttps://www.youtube.com/watch?v=4775IgUKfww\n```\nclass Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: \n l = 0\n res = 0\n product = 1\n \n for r in range(len(nums)):\n product *... | 35 | Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
... | 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. |
Python simple solution with sliding window pattern | subarray-product-less-than-k | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is a classic sliding window problem. We need to find a subarray where the product of all elements is less than a given value \'k\'. If we start from each index and try to find a subarray, the time complexity will be high. The... | 3 | Given an array of integers `nums` and an integer `k`, return _the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than_ `k`.
**Example 1:**
**Input:** nums = \[10,5,2,6\], k = 100
**Output:** 8
**Explanation:** The 8 subarrays that have product less than 100 are:
... | 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. |
✅Beats 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | best-time-to-buy-and-sell-stock-with-transaction-fee | 1 | 1 | **Explore Related Problems to Enhance Conceptual Understanding**\n1. [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)\n2. [Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)\n3. [Best Time to Buy... | 202 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
Easiest Python Solution beating 81% | best-time-to-buy-and-sell-stock-with-transaction-fee | 0 | 1 | \n# Code\n```\nclass Solution(object):\n def maxProfit(self, prices, fee):\n """\n :type prices: List[int]\n :type fee: int\n :rtype: int\n """\n pos=-prices[0]\n profit=0\n n=len(prices)\n for i in range(1,n):\n pos=max(pos,profit-prices[i])\... | 1 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
Python | O(n) time, O(1) space | Iterate through array | Beats 96 %for time | best-time-to-buy-and-sell-stock-with-transaction-fee | 0 | 1 | # Intuition\nYou know what they say, hindsight is 20/20. Going through the array backwards would allow us to identify the starting point as the high price a sale happened at, and the ending point as the lowest point preceding that. If we keep a running tally that changes as we pass the end of the transaction, we will h... | 1 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
Solution | best-time-to-buy-and-sell-stock-with-transaction-fee | 1 | 1 | ```C++ []\nconst static auto initialize = [] { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }();\nclass Solution {\npublic:\n\tint maxProfit(std::vector<int>& prices, int fee)\n\t{\n\t\tauto buy_state = -1 * prices[0];\n\t\tauto sell_state = 0;\n\t\tfor (auto i = 1; i... | 4 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
Python || DP || Recursion->Space Optimization | best-time-to-buy-and-sell-stock-with-transaction-fee | 0 | 1 | ```\n#Recursion \n#Time Complexity: O(2^n)\n#Space Complexity: O(n)\nclass Solution1:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n def solve(ind,buy):\n if ind==n:\n return 0\n profit=0\n if buy==0: #buy a stock\n take=-prices[ind]... | 3 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
Easy C++/Python/C solutions|| buy & sell | best-time-to-buy-and-sell-stock-with-transaction-fee | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedy to solve several stock problems.\nUse buy and sell!!\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSeveral stock profit problems are solved in the similar manner.\n[Please turn on English subtitles if necces... | 5 | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
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.
**Note:** You... | 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. |
717. 1-bit and 2-bit Characters, Solution with step by step explanation | 1-bit-and-2-bit-characters | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo solve this problem, we can use a greedy approach. The main insight here is that whenever we encounter a 1, it will always consume the next bit because 1 represents the start of a two-bit character. Hence, when we see a 1,... | 2 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Basic Python Solution - Iterative Method | 1-bit-and-2-bit-characters | 0 | 1 | # Code\n```\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n i = 0\n while i < len(bits):\n if bits[i] == 0:\n if i == len(bits) - 1:\n return True\n i = i + 1\n else:\n i = i + 2\n re... | 1 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.