id
int64 1
3.71k
| title
stringlengths 3
79
| difficulty
stringclasses 3
values | description
stringlengths 430
25.4k
| tags
stringlengths 0
131
| language
stringclasses 19
values | solution
stringlengths 47
20.6k
|
|---|---|---|---|---|---|---|
458
|
Poor Pigs
|
Hard
|
<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>
<p>You can feed the pigs according to these steps:</p>
<ol>
<li>Choose some live pigs to feed.</li>
<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>
<li>Wait for <code>minutesToDie</code> minutes. You may <strong>not</strong> feed any other pigs during this time.</li>
<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>
<li>Repeat this process until you run out of time.</li>
</ol>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 15
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> buckets = 4, minutesToDie = 15, minutesToTest = 30
<strong>Output:</strong> 2
<strong>Explanation:</strong> We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= buckets <= 1000</code></li>
<li><code>1 <= minutesToDie <= minutesToTest <= 100</code></li>
</ul>
|
Math; Dynamic Programming; Combinatorics
|
Python
|
class Solution:
def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:
base = minutesToTest // minutesToDie + 1
res, p = 0, 1
while p < buckets:
p *= base
res += 1
return res
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
C++
|
class Solution {
public:
bool repeatedSubstringPattern(string s) {
return (s + s).find(s, 1) < s.size();
}
};
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
Go
|
func repeatedSubstringPattern(s string) bool {
return strings.Index(s[1:]+s, s) < len(s)-1
}
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
Java
|
class Solution {
public boolean repeatedSubstringPattern(String s) {
String str = s + s;
return str.substring(1, str.length() - 1).contains(s);
}
}
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
Python
|
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).index(s, 1) < len(s)
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
Rust
|
impl Solution {
pub fn repeated_substring_pattern(s: String) -> bool {
(s.clone() + &s)[1..s.len() * 2 - 1].contains(&s)
}
}
|
459
|
Repeated Substring Pattern
|
Easy
|
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "abab"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "ab" twice.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aba"
<strong>Output:</strong> false
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "abcabcabcabc"
<strong>Output:</strong> true
<strong>Explanation:</strong> It is the substring "abc" four times or the substring "abcabc" twice.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>4</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; String Matching
|
TypeScript
|
function repeatedSubstringPattern(s: string): boolean {
return (s + s).slice(1, (s.length << 1) - 1).includes(s);
}
|
460
|
LFU Cache
|
Hard
|
<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>
<p>Implement the <code>LFUCache</code> class:</p>
<ul>
<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>
<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>
<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>
</ul>
<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>
<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>
<p>The functions <code data-stringify-type="code">get</code> and <code data-stringify-type="code">put</code> must each run in <code>O(1)</code> average time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
<strong>Output</strong>
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
<strong>Explanation</strong>
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= capacity <= 10<sup>4</sup></code></li>
<li><code>0 <= key <= 10<sup>5</sup></code></li>
<li><code>0 <= value <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
<p> </p>
<span style="display: none;"> </span>
|
Design; Hash Table; Linked List; Doubly-Linked List
|
C++
|
class Node {
public:
int key;
int value;
int freq;
Node* prev;
Node* next;
Node(int key, int value) {
this->key = key;
this->value = value;
this->freq = 1;
this->prev = nullptr;
this->next = nullptr;
}
};
class DoublyLinkedList {
public:
Node* head;
Node* tail;
DoublyLinkedList() {
this->head = new Node(-1, -1);
this->tail = new Node(-1, -1);
this->head->next = this->tail;
this->tail->prev = this->head;
}
void addFirst(Node* node) {
node->prev = this->head;
node->next = this->head->next;
this->head->next->prev = node;
this->head->next = node;
}
Node* remove(Node* node) {
node->next->prev = node->prev;
node->prev->next = node->next;
node->next = nullptr;
node->prev = nullptr;
return node;
}
Node* removeLast() {
return remove(this->tail->prev);
}
bool isEmpty() {
return this->head->next == this->tail;
}
};
class LFUCache {
public:
LFUCache(int capacity) {
this->capacity = capacity;
this->minFreq = 0;
}
int get(int key) {
if (capacity == 0 || map.find(key) == map.end()) {
return -1;
}
Node* node = map[key];
incrFreq(node);
return node->value;
}
void put(int key, int value) {
if (capacity == 0) {
return;
}
if (map.find(key) != map.end()) {
Node* node = map[key];
node->value = value;
incrFreq(node);
return;
}
if (map.size() == capacity) {
DoublyLinkedList* list = freqMap[minFreq];
Node* node = list->removeLast();
map.erase(node->key);
}
Node* node = new Node(key, value);
addNode(node);
map[key] = node;
minFreq = 1;
}
private:
int capacity;
int minFreq;
unordered_map<int, Node*> map;
unordered_map<int, DoublyLinkedList*> freqMap;
void incrFreq(Node* node) {
int freq = node->freq;
DoublyLinkedList* list = freqMap[freq];
list->remove(node);
if (list->isEmpty()) {
freqMap.erase(freq);
if (freq == minFreq) {
minFreq++;
}
}
node->freq++;
addNode(node);
}
void addNode(Node* node) {
int freq = node->freq;
if (freqMap.find(freq) == freqMap.end()) {
freqMap[freq] = new DoublyLinkedList();
}
DoublyLinkedList* list = freqMap[freq];
list->addFirst(node);
freqMap[freq] = list;
}
};
/**
* Your LFUCache object will be instantiated and called as such:
* LFUCache* obj = new LFUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
|
460
|
LFU Cache
|
Hard
|
<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>
<p>Implement the <code>LFUCache</code> class:</p>
<ul>
<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>
<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>
<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>
</ul>
<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>
<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>
<p>The functions <code data-stringify-type="code">get</code> and <code data-stringify-type="code">put</code> must each run in <code>O(1)</code> average time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
<strong>Output</strong>
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
<strong>Explanation</strong>
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= capacity <= 10<sup>4</sup></code></li>
<li><code>0 <= key <= 10<sup>5</sup></code></li>
<li><code>0 <= value <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
<p> </p>
<span style="display: none;"> </span>
|
Design; Hash Table; Linked List; Doubly-Linked List
|
Go
|
type LFUCache struct {
cache map[int]*node
freqMap map[int]*list
minFreq int
capacity int
}
func Constructor(capacity int) LFUCache {
return LFUCache{
cache: make(map[int]*node),
freqMap: make(map[int]*list),
capacity: capacity,
}
}
func (this *LFUCache) Get(key int) int {
if this.capacity == 0 {
return -1
}
n, ok := this.cache[key]
if !ok {
return -1
}
this.incrFreq(n)
return n.val
}
func (this *LFUCache) Put(key int, value int) {
if this.capacity == 0 {
return
}
n, ok := this.cache[key]
if ok {
n.val = value
this.incrFreq(n)
return
}
if len(this.cache) == this.capacity {
l := this.freqMap[this.minFreq]
delete(this.cache, l.removeBack().key)
}
n = &node{key: key, val: value, freq: 1}
this.addNode(n)
this.cache[key] = n
this.minFreq = 1
}
func (this *LFUCache) incrFreq(n *node) {
l := this.freqMap[n.freq]
l.remove(n)
if l.empty() {
delete(this.freqMap, n.freq)
if n.freq == this.minFreq {
this.minFreq++
}
}
n.freq++
this.addNode(n)
}
func (this *LFUCache) addNode(n *node) {
l, ok := this.freqMap[n.freq]
if !ok {
l = newList()
this.freqMap[n.freq] = l
}
l.pushFront(n)
}
type node struct {
key int
val int
freq int
prev *node
next *node
}
type list struct {
head *node
tail *node
}
func newList() *list {
head := new(node)
tail := new(node)
head.next = tail
tail.prev = head
return &list{
head: head,
tail: tail,
}
}
func (l *list) pushFront(n *node) {
n.prev = l.head
n.next = l.head.next
l.head.next.prev = n
l.head.next = n
}
func (l *list) remove(n *node) {
n.prev.next = n.next
n.next.prev = n.prev
n.next = nil
n.prev = nil
}
func (l *list) removeBack() *node {
n := l.tail.prev
l.remove(n)
return n
}
func (l *list) empty() bool {
return l.head.next == l.tail
}
|
460
|
LFU Cache
|
Hard
|
<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>
<p>Implement the <code>LFUCache</code> class:</p>
<ul>
<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>
<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>
<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>
</ul>
<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>
<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>
<p>The functions <code data-stringify-type="code">get</code> and <code data-stringify-type="code">put</code> must each run in <code>O(1)</code> average time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
<strong>Output</strong>
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
<strong>Explanation</strong>
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= capacity <= 10<sup>4</sup></code></li>
<li><code>0 <= key <= 10<sup>5</sup></code></li>
<li><code>0 <= value <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
<p> </p>
<span style="display: none;"> </span>
|
Design; Hash Table; Linked List; Doubly-Linked List
|
Java
|
class LFUCache {
private final Map<Integer, Node> map;
private final Map<Integer, DoublyLinkedList> freqMap;
private final int capacity;
private int minFreq;
public LFUCache(int capacity) {
this.capacity = capacity;
map = new HashMap<>(capacity, 1);
freqMap = new HashMap<>();
}
public int get(int key) {
if (capacity == 0) {
return -1;
}
if (!map.containsKey(key)) {
return -1;
}
Node node = map.get(key);
incrFreq(node);
return node.value;
}
public void put(int key, int value) {
if (capacity == 0) {
return;
}
if (map.containsKey(key)) {
Node node = map.get(key);
node.value = value;
incrFreq(node);
return;
}
if (map.size() == capacity) {
DoublyLinkedList list = freqMap.get(minFreq);
map.remove(list.removeLast().key);
}
Node node = new Node(key, value);
addNode(node);
map.put(key, node);
minFreq = 1;
}
private void incrFreq(Node node) {
int freq = node.freq;
DoublyLinkedList list = freqMap.get(freq);
list.remove(node);
if (list.isEmpty()) {
freqMap.remove(freq);
if (freq == minFreq) {
minFreq++;
}
}
node.freq++;
addNode(node);
}
private void addNode(Node node) {
int freq = node.freq;
DoublyLinkedList list = freqMap.getOrDefault(freq, new DoublyLinkedList());
list.addFirst(node);
freqMap.put(freq, list);
}
private static class Node {
int key;
int value;
int freq;
Node prev;
Node next;
Node(int key, int value) {
this.key = key;
this.value = value;
this.freq = 1;
}
}
private static class DoublyLinkedList {
private final Node head;
private final Node tail;
public DoublyLinkedList() {
head = new Node(-1, -1);
tail = new Node(-1, -1);
head.next = tail;
tail.prev = head;
}
public void addFirst(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
public Node remove(Node node) {
node.next.prev = node.prev;
node.prev.next = node.next;
node.next = null;
node.prev = null;
return node;
}
public Node removeLast() {
return remove(tail.prev);
}
public boolean isEmpty() {
return head.next == tail;
}
}
}
|
460
|
LFU Cache
|
Hard
|
<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>
<p>Implement the <code>LFUCache</code> class:</p>
<ul>
<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>
<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>
<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>
</ul>
<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>
<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>
<p>The functions <code data-stringify-type="code">get</code> and <code data-stringify-type="code">put</code> must each run in <code>O(1)</code> average time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
<strong>Output</strong>
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
<strong>Explanation</strong>
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= capacity <= 10<sup>4</sup></code></li>
<li><code>0 <= key <= 10<sup>5</sup></code></li>
<li><code>0 <= value <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
<p> </p>
<span style="display: none;"> </span>
|
Design; Hash Table; Linked List; Doubly-Linked List
|
Python
|
class Node:
def __init__(self, key: int, value: int) -> None:
self.key = key
self.value = value
self.freq = 1
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self) -> None:
self.head = Node(-1, -1)
self.tail = Node(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
def add_first(self, node: Node) -> None:
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def remove(self, node: Node) -> Node:
node.next.prev = node.prev
node.prev.next = node.next
node.next, node.prev = None, None
return node
def remove_last(self) -> Node:
return self.remove(self.tail.prev)
def is_empty(self) -> bool:
return self.head.next == self.tail
class LFUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.min_freq = 0
self.map = defaultdict(Node)
self.freq_map = defaultdict(DoublyLinkedList)
def get(self, key: int) -> int:
if self.capacity == 0 or key not in self.map:
return -1
node = self.map[key]
self.incr_freq(node)
return node.value
def put(self, key: int, value: int) -> None:
if self.capacity == 0:
return
if key in self.map:
node = self.map[key]
node.value = value
self.incr_freq(node)
return
if len(self.map) == self.capacity:
ls = self.freq_map[self.min_freq]
node = ls.remove_last()
self.map.pop(node.key)
node = Node(key, value)
self.add_node(node)
self.map[key] = node
self.min_freq = 1
def incr_freq(self, node: Node) -> None:
freq = node.freq
ls = self.freq_map[freq]
ls.remove(node)
if ls.is_empty():
self.freq_map.pop(freq)
if freq == self.min_freq:
self.min_freq += 1
node.freq += 1
self.add_node(node)
def add_node(self, node: Node) -> None:
freq = node.freq
ls = self.freq_map[freq]
ls.add_first(node)
self.freq_map[freq] = ls
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
460
|
LFU Cache
|
Hard
|
<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>
<p>Implement the <code>LFUCache</code> class:</p>
<ul>
<li><code>LFUCache(int capacity)</code> Initializes the object with the <code>capacity</code> of the data structure.</li>
<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>
<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>
</ul>
<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>
<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>
<p>The functions <code data-stringify-type="code">get</code> and <code data-stringify-type="code">put</code> must each run in <code>O(1)</code> average time complexity.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input</strong>
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
<strong>Output</strong>
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
<strong>Explanation</strong>
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= capacity <= 10<sup>4</sup></code></li>
<li><code>0 <= key <= 10<sup>5</sup></code></li>
<li><code>0 <= value <= 10<sup>9</sup></code></li>
<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
<p> </p>
<span style="display: none;"> </span>
|
Design; Hash Table; Linked List; Doubly-Linked List
|
Rust
|
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
struct Node {
key: i32,
value: i32,
freq: i32,
prev: Option<Rc<RefCell<Node>>>,
next: Option<Rc<RefCell<Node>>>,
}
impl Node {
fn new(key: i32, value: i32) -> Self {
Self {
key,
value,
freq: 1,
prev: None,
next: None,
}
}
}
struct LinkedList {
head: Option<Rc<RefCell<Node>>>,
tail: Option<Rc<RefCell<Node>>>,
}
impl LinkedList {
fn new() -> Self {
Self {
head: None,
tail: None,
}
}
fn push_front(&mut self, node: &Rc<RefCell<Node>>) {
match self.head.take() {
Some(head) => {
head.borrow_mut().prev = Some(Rc::clone(node));
node.borrow_mut().prev = None;
node.borrow_mut().next = Some(head);
self.head = Some(Rc::clone(node));
}
None => {
node.borrow_mut().prev = None;
node.borrow_mut().next = None;
self.head = Some(Rc::clone(node));
self.tail = Some(Rc::clone(node));
}
};
}
fn remove(&mut self, node: &Rc<RefCell<Node>>) {
match (node.borrow().prev.as_ref(), node.borrow().next.as_ref()) {
(None, None) => {
self.head = None;
self.tail = None;
}
(None, Some(next)) => {
self.head = Some(Rc::clone(next));
next.borrow_mut().prev = None;
}
(Some(prev), None) => {
self.tail = Some(Rc::clone(prev));
prev.borrow_mut().next = None;
}
(Some(prev), Some(next)) => {
next.borrow_mut().prev = Some(Rc::clone(prev));
prev.borrow_mut().next = Some(Rc::clone(next));
}
};
}
fn pop_back(&mut self) -> Option<Rc<RefCell<Node>>> {
match self.tail.take() {
Some(tail) => {
self.remove(&tail);
Some(tail)
}
None => None,
}
}
fn is_empty(&self) -> bool {
self.head.is_none()
}
}
struct LFUCache {
cache: HashMap<i32, Rc<RefCell<Node>>>,
freq_map: HashMap<i32, LinkedList>,
min_freq: i32,
capacity: usize,
}
/**
* `&self` means the method takes an immutable reference.
* If you need a mutable reference, change it to `&mut self` instead.
*/
impl LFUCache {
fn new(capacity: i32) -> Self {
Self {
cache: HashMap::new(),
freq_map: HashMap::new(),
min_freq: 0,
capacity: capacity as usize,
}
}
fn get(&mut self, key: i32) -> i32 {
if self.capacity == 0 {
return -1;
}
match self.cache.get(&key) {
Some(node) => {
let node = Rc::clone(node);
self.incr_freq(&node);
let value = node.borrow().value;
value
}
None => -1,
}
}
fn put(&mut self, key: i32, value: i32) {
if self.capacity == 0 {
return;
}
match self.cache.get(&key) {
Some(node) => {
let node = Rc::clone(node);
node.borrow_mut().value = value;
self.incr_freq(&node);
}
None => {
if self.cache.len() == self.capacity {
let list = self.freq_map.get_mut(&self.min_freq).unwrap();
self.cache.remove(&list.pop_back().unwrap().borrow().key);
}
let node = Rc::new(RefCell::new(Node::new(key, value)));
self.add_node(&node);
self.cache.insert(key, node);
self.min_freq = 1;
}
};
}
fn incr_freq(&mut self, node: &Rc<RefCell<Node>>) {
let freq = node.borrow().freq;
let list = self.freq_map.get_mut(&freq).unwrap();
list.remove(node);
if list.is_empty() {
self.freq_map.remove(&freq);
if freq == self.min_freq {
self.min_freq += 1;
}
}
node.borrow_mut().freq += 1;
self.add_node(node);
}
fn add_node(&mut self, node: &Rc<RefCell<Node>>) {
let freq = node.borrow().freq;
match self.freq_map.get_mut(&freq) {
Some(list) => {
list.push_front(node);
}
None => {
let mut list = LinkedList::new();
list.push_front(node);
self.freq_map.insert(node.borrow().freq, list);
}
};
}
}
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
C++
|
class Solution {
public:
int hammingDistance(int x, int y) {
return __builtin_popcount(x ^ y);
}
};
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Go
|
func hammingDistance(x int, y int) int {
return bits.OnesCount(uint(x ^ y))
}
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Java
|
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
JavaScript
|
/**
* @param {number} x
* @param {number} y
* @return {number}
*/
var hammingDistance = function (x, y) {
x ^= y;
let ans = 0;
while (x) {
x -= x & -x;
++ans;
}
return ans;
};
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Python
|
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return (x ^ y).bit_count()
|
461
|
Hamming Distance
|
Easy
|
<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>
<p>Given two integers <code>x</code> and <code>y</code>, return <em>the <strong>Hamming distance</strong> between them</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> x = 1, y = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> x = 3, y = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>0 <= x, y <= 2<sup>31</sup> - 1</code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
TypeScript
|
function hammingDistance(x: number, y: number): number {
x ^= y;
let ans = 0;
while (x) {
x -= x & -x;
++ans;
}
return ans;
}
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
C++
|
class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
int k = nums[nums.size() >> 1];
int ans = 0;
for (int& v : nums) {
ans += abs(v - k);
}
return ans;
}
};
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
Go
|
func minMoves2(nums []int) int {
sort.Ints(nums)
k := nums[len(nums)>>1]
ans := 0
for _, v := range nums {
ans += abs(v - k)
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
Java
|
class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int k = nums[nums.length >> 1];
int ans = 0;
for (int v : nums) {
ans += Math.abs(v - k);
}
return ans;
}
}
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
Python
|
class Solution:
def minMoves2(self, nums: List[int]) -> int:
nums.sort()
k = nums[len(nums) >> 1]
return sum(abs(v - k) for v in nums)
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
Rust
|
impl Solution {
pub fn min_moves2(mut nums: Vec<i32>) -> i32 {
nums.sort();
let k = nums[nums.len() / 2];
let mut ans = 0;
for num in nums.iter() {
ans += (num - k).abs();
}
ans
}
}
|
462
|
Minimum Moves to Equal Array Elements II
|
Medium
|
<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>
<p>In one move, you can increment or decrement an element of the array by <code>1</code>.</p>
<p>Test cases are designed so that the answer will fit in a <strong>32-bit</strong> integer.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Only two moves are needed (remember each move increments or decrements one element):
[<u>1</u>,2,3] => [2,2,<u>3</u>] => [2,2,2]
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [1,10,2,9]
<strong>Output:</strong> 16
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>n == nums.length</code></li>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Math; Sorting
|
TypeScript
|
function minMoves2(nums: number[]): number {
nums.sort((a, b) => a - b);
const k = nums[nums.length >> 1];
return nums.reduce((r, v) => r + Math.abs(v - k), 0);
}
|
463
|
Island Perimeter
|
Easy
|
<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents land and <code>grid[i][j] = 0</code> represents water.</p>
<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>
<p>The island doesn't have "lakes", meaning the water inside isn'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't exceed 100. Determine the perimeter of the island.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0463.Island%20Perimeter/images/island.png" style="width: 221px; height: 213px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>row == grid.length</code></li>
<li><code>col == grid[i].length</code></li>
<li><code>1 <= row, col <= 100</code></li>
<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li>There is exactly one island in <code>grid</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
C++
|
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
ans += 4;
if (i < m - 1 && grid[i + 1][j] == 1) ans -= 2;
if (j < n - 1 && grid[i][j + 1] == 1) ans -= 2;
}
}
}
return ans;
}
};
|
463
|
Island Perimeter
|
Easy
|
<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents land and <code>grid[i][j] = 0</code> represents water.</p>
<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>
<p>The island doesn't have "lakes", meaning the water inside isn'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't exceed 100. Determine the perimeter of the island.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0463.Island%20Perimeter/images/island.png" style="width: 221px; height: 213px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>row == grid.length</code></li>
<li><code>col == grid[i].length</code></li>
<li><code>1 <= row, col <= 100</code></li>
<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li>There is exactly one island in <code>grid</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Go
|
func islandPerimeter(grid [][]int) int {
m, n := len(grid), len(grid[0])
ans := 0
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 1 {
ans += 4
if i < m-1 && grid[i+1][j] == 1 {
ans -= 2
}
if j < n-1 && grid[i][j+1] == 1 {
ans -= 2
}
}
}
}
return ans
}
|
463
|
Island Perimeter
|
Easy
|
<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents land and <code>grid[i][j] = 0</code> represents water.</p>
<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>
<p>The island doesn't have "lakes", meaning the water inside isn'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't exceed 100. Determine the perimeter of the island.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0463.Island%20Perimeter/images/island.png" style="width: 221px; height: 213px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>row == grid.length</code></li>
<li><code>col == grid[i].length</code></li>
<li><code>1 <= row, col <= 100</code></li>
<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li>There is exactly one island in <code>grid</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Java
|
class Solution {
public int islandPerimeter(int[][] grid) {
int ans = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
ans += 4;
if (i < m - 1 && grid[i + 1][j] == 1) {
ans -= 2;
}
if (j < n - 1 && grid[i][j + 1] == 1) {
ans -= 2;
}
}
}
}
return ans;
}
}
|
463
|
Island Perimeter
|
Easy
|
<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents land and <code>grid[i][j] = 0</code> represents water.</p>
<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>
<p>The island doesn't have "lakes", meaning the water inside isn'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't exceed 100. Determine the perimeter of the island.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0463.Island%20Perimeter/images/island.png" style="width: 221px; height: 213px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>row == grid.length</code></li>
<li><code>col == grid[i].length</code></li>
<li><code>1 <= row, col <= 100</code></li>
<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li>There is exactly one island in <code>grid</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
Python
|
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
ans += 4
if i < m - 1 and grid[i + 1][j] == 1:
ans -= 2
if j < n - 1 and grid[i][j + 1] == 1:
ans -= 2
return ans
|
463
|
Island Perimeter
|
Easy
|
<p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents land and <code>grid[i][j] = 0</code> represents water.</p>
<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>
<p>The island doesn't have "lakes", meaning the water inside isn'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't exceed 100. Determine the perimeter of the island.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0463.Island%20Perimeter/images/island.png" style="width: 221px; height: 213px;" />
<pre>
<strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1]]
<strong>Output:</strong> 4
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> grid = [[1,0]]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>row == grid.length</code></li>
<li><code>col == grid[i].length</code></li>
<li><code>1 <= row, col <= 100</code></li>
<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
<li>There is exactly one island in <code>grid</code>.</li>
</ul>
|
Depth-First Search; Breadth-First Search; Array; Matrix
|
TypeScript
|
function islandPerimeter(grid: number[][]): number {
let m = grid.length,
n = grid[0].length;
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
let top = 0,
left = 0;
if (i > 0) {
top = grid[i - 1][j];
}
if (j > 0) {
left = grid[i][j - 1];
}
let cur = grid[i][j];
if (cur != top) ++ans;
if (cur != left) ++ans;
}
}
// 最后一行, 最后一列
for (let i = 0; i < m; ++i) {
if (grid[i][n - 1] == 1) ++ans;
}
for (let j = 0; j < n; ++j) {
if (grid[m - 1][j] == 1) ++ans;
}
return ans;
}
|
464
|
Can I Win
|
Medium
|
<p>In the "100 game" 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>
<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>
<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 >= 100.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11
<strong>Output:</strong> false
<strong>Explanation:</strong>
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1
<strong>Output:</strong> true
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maxChoosableInteger <= 20</code></li>
<li><code>0 <= desiredTotal <= 300</code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Bitmask; Game Theory
|
C++
|
class Solution {
public:
bool canIWin(int maxChoosableInteger, int desiredTotal) {
if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) {
return false;
}
unordered_map<int, int> f;
function<bool(int, int)> dfs = [&](int mask, int s) {
if (f.contains(mask)) {
return f[mask];
}
for (int i = 0; i < maxChoosableInteger; ++i) {
if (mask >> i & 1 ^ 1) {
if (s + i + 1 >= desiredTotal || !dfs(mask | 1 << i, s + i + 1)) {
return f[mask] = true;
}
}
}
return f[mask] = false;
};
return dfs(0, 0);
}
};
|
464
|
Can I Win
|
Medium
|
<p>In the "100 game" 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>
<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>
<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 >= 100.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11
<strong>Output:</strong> false
<strong>Explanation:</strong>
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1
<strong>Output:</strong> true
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maxChoosableInteger <= 20</code></li>
<li><code>0 <= desiredTotal <= 300</code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Bitmask; Game Theory
|
Go
|
func canIWin(maxChoosableInteger int, desiredTotal int) bool {
if (1+maxChoosableInteger)*maxChoosableInteger/2 < desiredTotal {
return false
}
f := map[int]bool{}
var dfs func(int, int) bool
dfs = func(mask, s int) bool {
if v, ok := f[mask]; ok {
return v
}
for i := 1; i <= maxChoosableInteger; i++ {
if mask>>i&1 == 0 {
if s+i >= desiredTotal || !dfs(mask|1<<i, s+i) {
f[mask] = true
return true
}
}
}
f[mask] = false
return false
}
return dfs(0, 0)
}
|
464
|
Can I Win
|
Medium
|
<p>In the "100 game" 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>
<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>
<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 >= 100.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11
<strong>Output:</strong> false
<strong>Explanation:</strong>
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1
<strong>Output:</strong> true
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maxChoosableInteger <= 20</code></li>
<li><code>0 <= desiredTotal <= 300</code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Bitmask; Game Theory
|
Java
|
class Solution {
private Map<Integer, Boolean> f = new HashMap<>();
private int maxChoosableInteger;
private int desiredTotal;
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) {
return false;
}
this.maxChoosableInteger = maxChoosableInteger;
this.desiredTotal = desiredTotal;
return dfs(0, 0);
}
private boolean dfs(int mask, int s) {
if (f.containsKey(mask)) {
return f.get(mask);
}
for (int i = 0; i < maxChoosableInteger; ++i) {
if ((mask >> i & 1) == 0) {
if (s + i + 1 >= desiredTotal || !dfs(mask | 1 << i, s + i + 1)) {
f.put(mask, true);
return true;
}
}
}
f.put(mask, false);
return false;
}
}
|
464
|
Can I Win
|
Medium
|
<p>In the "100 game" 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>
<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>
<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 >= 100.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11
<strong>Output:</strong> false
<strong>Explanation:</strong>
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1
<strong>Output:</strong> true
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maxChoosableInteger <= 20</code></li>
<li><code>0 <= desiredTotal <= 300</code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Bitmask; Game Theory
|
Python
|
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
@cache
def dfs(mask: int, s: int) -> bool:
for i in range(1, maxChoosableInteger + 1):
if mask >> i & 1 ^ 1:
if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i):
return True
return False
if (1 + maxChoosableInteger) * maxChoosableInteger // 2 < desiredTotal:
return False
return dfs(0, 0)
|
464
|
Can I Win
|
Medium
|
<p>In the "100 game" 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>
<p>What if we change the game so that players <strong>cannot</strong> re-use integers?</p>
<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 >= 100.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 11
<strong>Output:</strong> false
<strong>Explanation:</strong>
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 0
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> maxChoosableInteger = 10, desiredTotal = 1
<strong>Output:</strong> true
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= maxChoosableInteger <= 20</code></li>
<li><code>0 <= desiredTotal <= 300</code></li>
</ul>
|
Bit Manipulation; Memoization; Math; Dynamic Programming; Bitmask; Game Theory
|
TypeScript
|
function canIWin(maxChoosableInteger: number, desiredTotal: number): boolean {
if (((1 + maxChoosableInteger) * maxChoosableInteger) / 2 < desiredTotal) {
return false;
}
const f: Record<string, boolean> = {};
const dfs = (mask: number, s: number): boolean => {
if (f.hasOwnProperty(mask)) {
return f[mask];
}
for (let i = 1; i <= maxChoosableInteger; ++i) {
if (((mask >> i) & 1) ^ 1) {
if (s + i >= desiredTotal || !dfs(mask ^ (1 << i), s + i)) {
return (f[mask] = true);
}
}
}
return (f[mask] = false);
};
return dfs(0, 0);
}
|
465
|
Optimal Account Balancing
|
Hard
|
<p>You are given an array of transactions <code>transactions</code> where <code>transactions[i] = [from<sub>i</sub>, to<sub>i</sub>, amount<sub>i</sub>]</code> indicates that the person with <code>ID = from<sub>i</sub></code> gave <code>amount<sub>i</sub> $</code> to the person with <code>ID = to<sub>i</sub></code>.</p>
<p>Return <em>the minimum number of transactions required to settle the debt</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[2,0,5]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= transactions.length <= 8</code></li>
<li><code>transactions[i].length == 3</code></li>
<li><code>0 <= from<sub>i</sub>, to<sub>i</sub> < 12</code></li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
<li><code>1 <= amount<sub>i</sub> <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
C++
|
class Solution {
public:
int minTransfers(vector<vector<int>>& transactions) {
int g[12]{};
for (auto& t : transactions) {
g[t[0]] -= t[2];
g[t[1]] += t[2];
}
vector<int> nums;
for (int x : g) {
if (x) {
nums.push_back(x);
}
}
int m = nums.size();
int f[1 << m];
memset(f, 0x3f, sizeof(f));
f[0] = 0;
for (int i = 1; i < 1 << m; ++i) {
int s = 0;
for (int j = 0; j < m; ++j) {
if (i >> j & 1) {
s += nums[j];
}
}
if (s == 0) {
f[i] = __builtin_popcount(i) - 1;
for (int j = (i - 1) & i; j; j = (j - 1) & i) {
f[i] = min(f[i], f[j] + f[i ^ j]);
}
}
}
return f[(1 << m) - 1];
}
};
|
465
|
Optimal Account Balancing
|
Hard
|
<p>You are given an array of transactions <code>transactions</code> where <code>transactions[i] = [from<sub>i</sub>, to<sub>i</sub>, amount<sub>i</sub>]</code> indicates that the person with <code>ID = from<sub>i</sub></code> gave <code>amount<sub>i</sub> $</code> to the person with <code>ID = to<sub>i</sub></code>.</p>
<p>Return <em>the minimum number of transactions required to settle the debt</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[2,0,5]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= transactions.length <= 8</code></li>
<li><code>transactions[i].length == 3</code></li>
<li><code>0 <= from<sub>i</sub>, to<sub>i</sub> < 12</code></li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
<li><code>1 <= amount<sub>i</sub> <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Go
|
func minTransfers(transactions [][]int) int {
g := [12]int{}
for _, t := range transactions {
g[t[0]] -= t[2]
g[t[1]] += t[2]
}
nums := []int{}
for _, x := range g {
if x != 0 {
nums = append(nums, x)
}
}
m := len(nums)
f := make([]int, 1<<m)
for i := 1; i < 1<<m; i++ {
f[i] = 1 << 29
s := 0
for j, x := range nums {
if i>>j&1 == 1 {
s += x
}
}
if s == 0 {
f[i] = bits.OnesCount(uint(i)) - 1
for j := (i - 1) & i; j > 0; j = (j - 1) & i {
f[i] = min(f[i], f[j]+f[i^j])
}
}
}
return f[1<<m-1]
}
|
465
|
Optimal Account Balancing
|
Hard
|
<p>You are given an array of transactions <code>transactions</code> where <code>transactions[i] = [from<sub>i</sub>, to<sub>i</sub>, amount<sub>i</sub>]</code> indicates that the person with <code>ID = from<sub>i</sub></code> gave <code>amount<sub>i</sub> $</code> to the person with <code>ID = to<sub>i</sub></code>.</p>
<p>Return <em>the minimum number of transactions required to settle the debt</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[2,0,5]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= transactions.length <= 8</code></li>
<li><code>transactions[i].length == 3</code></li>
<li><code>0 <= from<sub>i</sub>, to<sub>i</sub> < 12</code></li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
<li><code>1 <= amount<sub>i</sub> <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Java
|
class Solution {
public int minTransfers(int[][] transactions) {
int[] g = new int[12];
for (var t : transactions) {
g[t[0]] -= t[2];
g[t[1]] += t[2];
}
List<Integer> nums = new ArrayList<>();
for (int x : g) {
if (x != 0) {
nums.add(x);
}
}
int m = nums.size();
int[] f = new int[1 << m];
Arrays.fill(f, 1 << 29);
f[0] = 0;
for (int i = 1; i < 1 << m; ++i) {
int s = 0;
for (int j = 0; j < m; ++j) {
if ((i >> j & 1) == 1) {
s += nums.get(j);
}
}
if (s == 0) {
f[i] = Integer.bitCount(i) - 1;
for (int j = (i - 1) & i; j > 0; j = (j - 1) & i) {
f[i] = Math.min(f[i], f[j] + f[i ^ j]);
}
}
}
return f[(1 << m) - 1];
}
}
|
465
|
Optimal Account Balancing
|
Hard
|
<p>You are given an array of transactions <code>transactions</code> where <code>transactions[i] = [from<sub>i</sub>, to<sub>i</sub>, amount<sub>i</sub>]</code> indicates that the person with <code>ID = from<sub>i</sub></code> gave <code>amount<sub>i</sub> $</code> to the person with <code>ID = to<sub>i</sub></code>.</p>
<p>Return <em>the minimum number of transactions required to settle the debt</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[2,0,5]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= transactions.length <= 8</code></li>
<li><code>transactions[i].length == 3</code></li>
<li><code>0 <= from<sub>i</sub>, to<sub>i</sub> < 12</code></li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
<li><code>1 <= amount<sub>i</sub> <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Python
|
class Solution:
def minTransfers(self, transactions: List[List[int]]) -> int:
g = defaultdict(int)
for f, t, x in transactions:
g[f] -= x
g[t] += x
nums = [x for x in g.values() if x]
m = len(nums)
f = [inf] * (1 << m)
f[0] = 0
for i in range(1, 1 << m):
s = 0
for j, x in enumerate(nums):
if i >> j & 1:
s += x
if s == 0:
f[i] = i.bit_count() - 1
j = (i - 1) & i
while j > 0:
f[i] = min(f[i], f[j] + f[i ^ j])
j = (j - 1) & i
return f[-1]
|
465
|
Optimal Account Balancing
|
Hard
|
<p>You are given an array of transactions <code>transactions</code> where <code>transactions[i] = [from<sub>i</sub>, to<sub>i</sub>, amount<sub>i</sub>]</code> indicates that the person with <code>ID = from<sub>i</sub></code> gave <code>amount<sub>i</sub> $</code> to the person with <code>ID = to<sub>i</sub></code>.</p>
<p>Return <em>the minimum number of transactions required to settle the debt</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[2,0,5]]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= transactions.length <= 8</code></li>
<li><code>transactions[i].length == 3</code></li>
<li><code>0 <= from<sub>i</sub>, to<sub>i</sub> < 12</code></li>
<li><code>from<sub>i</sub> != to<sub>i</sub></code></li>
<li><code>1 <= amount<sub>i</sub> <= 100</code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
TypeScript
|
function minTransfers(transactions: number[][]): number {
const g: number[] = new Array(12).fill(0);
for (const [f, t, x] of transactions) {
g[f] -= x;
g[t] += x;
}
const nums = g.filter(x => x !== 0);
const m = nums.length;
const f: number[] = new Array(1 << m).fill(1 << 29);
f[0] = 0;
for (let i = 1; i < 1 << m; ++i) {
let s = 0;
for (let j = 0; j < m; ++j) {
if (((i >> j) & 1) === 1) {
s += nums[j];
}
}
if (s === 0) {
f[i] = bitCount(i) - 1;
for (let j = (i - 1) & i; j; j = (j - 1) & i) {
f[i] = Math.min(f[i], f[j] + f[i ^ j]);
}
}
}
return f[(1 << m) - 1];
}
function bitCount(i: number): number {
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
|
466
|
Count The Repetitions
|
Hard
|
<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>
<ul>
<li>For example, <code>str == ["abc", 3] =="abcabcabc"</code>.</li>
</ul>
<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>
<ul>
<li>For example, <code>s1 = "abc"</code> can be obtained from <code>s2 = "ab<strong><u>dbe</u></strong>c"</code> based on our definition by removing the bolded underlined characters.</li>
</ul>
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 100</code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
<li><code>1 <= n1, n2 <= 10<sup>6</sup></code></li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int getMaxRepetitions(string s1, int n1, string s2, int n2) {
int m = s1.size(), n = s2.size();
vector<pair<int, int>> d;
for (int i = 0; i < n; ++i) {
int j = i;
int cnt = 0;
for (int k = 0; k < m; ++k) {
if (s1[k] == s2[j]) {
if (++j == n) {
++cnt;
j = 0;
}
}
}
d.emplace_back(cnt, j);
}
int ans = 0;
for (int j = 0; n1; --n1) {
ans += d[j].first;
j = d[j].second;
}
return ans / n2;
}
};
|
466
|
Count The Repetitions
|
Hard
|
<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>
<ul>
<li>For example, <code>str == ["abc", 3] =="abcabcabc"</code>.</li>
</ul>
<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>
<ul>
<li>For example, <code>s1 = "abc"</code> can be obtained from <code>s2 = "ab<strong><u>dbe</u></strong>c"</code> based on our definition by removing the bolded underlined characters.</li>
</ul>
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 100</code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
<li><code>1 <= n1, n2 <= 10<sup>6</sup></code></li>
</ul>
|
String; Dynamic Programming
|
Go
|
func getMaxRepetitions(s1 string, n1 int, s2 string, n2 int) (ans int) {
n := len(s2)
d := make([][2]int, n)
for i := 0; i < n; i++ {
j := i
cnt := 0
for k := range s1 {
if s1[k] == s2[j] {
j++
if j == n {
cnt++
j = 0
}
}
}
d[i] = [2]int{cnt, j}
}
for j := 0; n1 > 0; n1-- {
ans += d[j][0]
j = d[j][1]
}
ans /= n2
return
}
|
466
|
Count The Repetitions
|
Hard
|
<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>
<ul>
<li>For example, <code>str == ["abc", 3] =="abcabcabc"</code>.</li>
</ul>
<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>
<ul>
<li>For example, <code>s1 = "abc"</code> can be obtained from <code>s2 = "ab<strong><u>dbe</u></strong>c"</code> based on our definition by removing the bolded underlined characters.</li>
</ul>
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 100</code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
<li><code>1 <= n1, n2 <= 10<sup>6</sup></code></li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
int m = s1.length(), n = s2.length();
int[][] d = new int[n][0];
for (int i = 0; i < n; ++i) {
int j = i;
int cnt = 0;
for (int k = 0; k < m; ++k) {
if (s1.charAt(k) == s2.charAt(j)) {
if (++j == n) {
j = 0;
++cnt;
}
}
}
d[i] = new int[] {cnt, j};
}
int ans = 0;
for (int j = 0; n1 > 0; --n1) {
ans += d[j][0];
j = d[j][1];
}
return ans / n2;
}
}
|
466
|
Count The Repetitions
|
Hard
|
<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>
<ul>
<li>For example, <code>str == ["abc", 3] =="abcabcabc"</code>.</li>
</ul>
<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>
<ul>
<li>For example, <code>s1 = "abc"</code> can be obtained from <code>s2 = "ab<strong><u>dbe</u></strong>c"</code> based on our definition by removing the bolded underlined characters.</li>
</ul>
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 100</code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
<li><code>1 <= n1, n2 <= 10<sup>6</sup></code></li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
n = len(s2)
d = {}
for i in range(n):
cnt = 0
j = i
for c in s1:
if c == s2[j]:
j += 1
if j == n:
cnt += 1
j = 0
d[i] = (cnt, j)
ans = 0
j = 0
for _ in range(n1):
cnt, j = d[j]
ans += cnt
return ans // n2
|
466
|
Count The Repetitions
|
Hard
|
<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>
<ul>
<li>For example, <code>str == ["abc", 3] =="abcabcabc"</code>.</li>
</ul>
<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>
<ul>
<li>For example, <code>s1 = "abc"</code> can be obtained from <code>s2 = "ab<strong><u>dbe</u></strong>c"</code> based on our definition by removing the bolded underlined characters.</li>
</ul>
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 4, s2 = "ab", n2 = 2
<strong>Output:</strong> 2
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s1 = "acb", n1 = 1, s2 = "acb", n2 = 1
<strong>Output:</strong> 1
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s1.length, s2.length <= 100</code></li>
<li><code>s1</code> and <code>s2</code> consist of lowercase English letters.</li>
<li><code>1 <= n1, n2 <= 10<sup>6</sup></code></li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function getMaxRepetitions(s1: string, n1: number, s2: string, n2: number): number {
const n = s2.length;
const d: number[][] = new Array(n).fill(0).map(() => new Array(2).fill(0));
for (let i = 0; i < n; ++i) {
let j = i;
let cnt = 0;
for (const c of s1) {
if (c === s2[j]) {
if (++j === n) {
j = 0;
++cnt;
}
}
}
d[i] = [cnt, j];
}
let ans = 0;
for (let j = 0; n1 > 0; --n1) {
ans += d[j][0];
j = d[j][1];
}
return Math.floor(ans / n2);
}
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
int findSubstringInWraproundString(string s) {
int f[26]{};
int n = s.length();
for (int i = 0, k = 0; i < n; ++i) {
if (i && (s[i] - s[i - 1] + 26) % 26 == 1) {
++k;
} else {
k = 1;
}
f[s[i] - 'a'] = max(f[s[i] - 'a'], k);
}
return accumulate(begin(f), end(f), 0);
}
};
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func findSubstringInWraproundString(s string) (ans int) {
f := [26]int{}
k := 0
for i := range s {
if i > 0 && (s[i]-s[i-1]+26)%26 == 1 {
k++
} else {
k = 1
}
f[s[i]-'a'] = max(f[s[i]-'a'], k)
}
for _, x := range f {
ans += x
}
return
}
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
public int findSubstringInWraproundString(String s) {
int[] f = new int[26];
int n = s.length();
for (int i = 0, k = 0; i < n; ++i) {
if (i > 0 && (s.charAt(i) - s.charAt(i - 1) + 26) % 26 == 1) {
++k;
} else {
k = 1;
}
f[s.charAt(i) - 'a'] = Math.max(f[s.charAt(i) - 'a'], k);
}
return Arrays.stream(f).sum();
}
}
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def findSubstringInWraproundString(self, s: str) -> int:
f = defaultdict(int)
k = 0
for i, c in enumerate(s):
if i and (ord(c) - ord(s[i - 1])) % 26 == 1:
k += 1
else:
k = 1
f[c] = max(f[c], k)
return sum(f.values())
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Rust
|
impl Solution {
pub fn find_substring_in_wrapround_string(s: String) -> i32 {
let idx = |c: u8| -> usize { (c - b'a') as usize };
let mut f = vec![0; 26];
let n = s.len();
let s = s.as_bytes();
let mut k = 0;
for i in 0..n {
let j = idx(s[i]);
if i > 0 && ((j as i32) - (idx(s[i - 1]) as i32) + 26) % 26 == 1 {
k += 1;
} else {
k = 1;
}
f[j] = f[j].max(k);
}
f.iter().sum()
}
}
|
467
|
Unique Substrings in Wraparound String
|
Medium
|
<p>We define the string <code>base</code> to be the infinite wraparound string of <code>"abcdefghijklmnopqrstuvwxyz"</code>, so <code>base</code> will look like this:</p>
<ul>
<li><code>"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."</code>.</li>
</ul>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "a"
<strong>Output:</strong> 1
<strong>Explanation:</strong> Only the substring "a" of s is in base.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "cac"
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two substrings ("a", "c") of s in base.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "zab"
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 10<sup>5</sup></code></li>
<li><code>s</code> consists of lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function findSubstringInWraproundString(s: string): number {
const idx = (c: string): number => c.charCodeAt(0) - 97;
const f: number[] = Array(26).fill(0);
const n = s.length;
for (let i = 0, k = 0; i < n; ++i) {
const j = idx(s[i]);
if (i && (j - idx(s[i - 1]) + 26) % 26 === 1) {
++k;
} else {
k = 1;
}
f[j] = Math.max(f[j], k);
}
return f.reduce((acc, cur) => acc + cur, 0);
}
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
C++
|
class Solution {
public:
string validIPAddress(string queryIP) {
if (isIPv4(queryIP)) {
return "IPv4";
}
if (isIPv6(queryIP)) {
return "IPv6";
}
return "Neither";
}
private:
bool isIPv4(const string& s) {
if (s.empty() || s.back() == '.') {
return false;
}
vector<string> ss = split(s, '.');
if (ss.size() != 4) {
return false;
}
for (const string& t : ss) {
if (t.empty() || (t.size() > 1 && t[0] == '0')) {
return false;
}
int x = convert(t);
if (x < 0 || x > 255) {
return false;
}
}
return true;
}
bool isIPv6(const string& s) {
if (s.empty() || s.back() == ':') {
return false;
}
vector<string> ss = split(s, ':');
if (ss.size() != 8) {
return false;
}
for (const string& t : ss) {
if (t.size() < 1 || t.size() > 4) {
return false;
}
for (char c : t) {
if (!isxdigit(c)) {
return false;
}
}
}
return true;
}
int convert(const string& s) {
int x = 0;
for (char c : s) {
if (!isdigit(c)) {
return -1;
}
x = x * 10 + (c - '0');
if (x > 255) {
return x;
}
}
return x;
}
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream iss(s);
while (getline(iss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
};
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
Go
|
func validIPAddress(queryIP string) string {
if isIPv4(queryIP) {
return "IPv4"
}
if isIPv6(queryIP) {
return "IPv6"
}
return "Neither"
}
func isIPv4(s string) bool {
if strings.HasSuffix(s, ".") {
return false
}
ss := strings.Split(s, ".")
if len(ss) != 4 {
return false
}
for _, t := range ss {
if len(t) == 0 || (len(t) > 1 && t[0] == '0') {
return false
}
x := convert(t)
if x < 0 || x > 255 {
return false
}
}
return true
}
func isIPv6(s string) bool {
if strings.HasSuffix(s, ":") {
return false
}
ss := strings.Split(s, ":")
if len(ss) != 8 {
return false
}
for _, t := range ss {
if len(t) < 1 || len(t) > 4 {
return false
}
for _, c := range t {
if !unicode.IsDigit(c) && !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return false
}
}
}
return true
}
func convert(s string) int {
x := 0
for _, c := range s {
if !unicode.IsDigit(c) {
return -1
}
x = x*10 + int(c-'0')
if x > 255 {
return x
}
}
return x
}
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
Java
|
class Solution {
public String validIPAddress(String queryIP) {
if (isIPv4(queryIP)) {
return "IPv4";
}
if (isIPv6(queryIP)) {
return "IPv6";
}
return "Neither";
}
private boolean isIPv4(String s) {
if (s.endsWith(".")) {
return false;
}
String[] ss = s.split("\\.");
if (ss.length != 4) {
return false;
}
for (String t : ss) {
if (t.length() == 0 || t.length() > 1 && t.charAt(0) == '0') {
return false;
}
int x = convert(t);
if (x < 0 || x > 255) {
return false;
}
}
return true;
}
private boolean isIPv6(String s) {
if (s.endsWith(":")) {
return false;
}
String[] ss = s.split(":");
if (ss.length != 8) {
return false;
}
for (String t : ss) {
if (t.length() < 1 || t.length() > 4) {
return false;
}
for (char c : t.toCharArray()) {
if (!Character.isDigit(c)
&& !"0123456789abcdefABCDEF".contains(String.valueOf(c))) {
return false;
}
}
}
return true;
}
private int convert(String s) {
int x = 0;
for (char c : s.toCharArray()) {
if (!Character.isDigit(c)) {
return -1;
}
x = x * 10 + (c - '0');
if (x > 255) {
return x;
}
}
return x;
}
}
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
Python
|
class Solution:
def validIPAddress(self, queryIP: str) -> str:
def is_ipv4(s: str) -> bool:
ss = s.split(".")
if len(ss) != 4:
return False
for t in ss:
if len(t) > 1 and t[0] == "0":
return False
if not t.isdigit() or not 0 <= int(t) <= 255:
return False
return True
def is_ipv6(s: str) -> bool:
ss = s.split(":")
if len(ss) != 8:
return False
for t in ss:
if not 1 <= len(t) <= 4:
return False
if not all(c in "0123456789abcdefABCDEF" for c in t):
return False
return True
if is_ipv4(queryIP):
return "IPv4"
if is_ipv6(queryIP):
return "IPv6"
return "Neither"
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
Rust
|
impl Solution {
pub fn valid_ip_address(query_ip: String) -> String {
if Self::is_ipv4(&query_ip) {
return "IPv4".to_string();
}
if Self::is_ipv6(&query_ip) {
return "IPv6".to_string();
}
"Neither".to_string()
}
fn is_ipv4(s: &str) -> bool {
if s.ends_with('.') {
return false;
}
let ss: Vec<&str> = s.split('.').collect();
if ss.len() != 4 {
return false;
}
for t in ss {
if t.is_empty() || (t.len() > 1 && t.starts_with('0')) {
return false;
}
match Self::convert(t) {
Some(x) if x <= 255 => {
continue;
}
_ => {
return false;
}
}
}
true
}
fn is_ipv6(s: &str) -> bool {
if s.ends_with(':') {
return false;
}
let ss: Vec<&str> = s.split(':').collect();
if ss.len() != 8 {
return false;
}
for t in ss {
if t.len() < 1 || t.len() > 4 {
return false;
}
if !t.chars().all(|c| c.is_digit(16)) {
return false;
}
}
true
}
fn convert(s: &str) -> Option<i32> {
let mut x = 0;
for c in s.chars() {
if !c.is_digit(10) {
return None;
}
x = x * 10 + (c.to_digit(10).unwrap() as i32);
if x > 255 {
return Some(x);
}
}
Some(x)
}
}
|
468
|
Validate IP Address
|
Medium
|
<p>Given a string <code>queryIP</code>, return <code>"IPv4"</code> if IP is a valid IPv4 address, <code>"IPv6"</code> if IP is a valid IPv6 address or <code>"Neither"</code> if IP is not a correct IP of any type.</p>
<p><strong>A valid IPv4</strong> address is an IP in the form <code>"x<sub>1</sub>.x<sub>2</sub>.x<sub>3</sub>.x<sub>4</sub>"</code> where <code>0 <= x<sub>i</sub> <= 255</code> and <code>x<sub>i</sub></code> <strong>cannot contain</strong> leading zeros. For example, <code>"192.168.1.1"</code> and <code>"192.168.1.0"</code> are valid IPv4 addresses while <code>"192.168.01.1"</code>, <code>"192.168.1.00"</code>, and <code>"192.168@1.1"</code> are invalid IPv4 addresses.</p>
<p><strong>A valid IPv6</strong> address is an IP in the form <code>"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>"</code> where:</p>
<ul>
<li><code>1 <= x<sub>i</sub>.length <= 4</code></li>
<li><code>x<sub>i</sub></code> is a <strong>hexadecimal string</strong> which may contain digits, lowercase English letter (<code>'a'</code> to <code>'f'</code>) and upper-case English letters (<code>'A'</code> to <code>'F'</code>).</li>
<li>Leading zeros are allowed in <code>x<sub>i</sub></code>.</li>
</ul>
<p>For example, "<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> and "<code>2001:db8:85a3:0:0:8A2E:0370:7334"</code> are valid IPv6 addresses, while "<code>2001:0db8:85a3::8A2E:037j:7334"</code> and "<code>02001:0db8:85a3:0000:0000:8a2e:0370:7334"</code> are invalid IPv6 addresses.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "172.16.254.1"
<strong>Output:</strong> "IPv4"
<strong>Explanation:</strong> This is a valid IPv4 address, return "IPv4".
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"
<strong>Output:</strong> "IPv6"
<strong>Explanation:</strong> This is a valid IPv6 address, return "IPv6".
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> queryIP = "256.256.256.256"
<strong>Output:</strong> "Neither"
<strong>Explanation:</strong> This is neither a IPv4 address nor a IPv6 address.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>queryIP</code> consists only of English letters, digits and the characters <code>'.'</code> and <code>':'</code>.</li>
</ul>
|
String
|
TypeScript
|
function validIPAddress(queryIP: string): string {
if (isIPv4(queryIP)) {
return 'IPv4';
}
if (isIPv6(queryIP)) {
return 'IPv6';
}
return 'Neither';
}
function isIPv4(s: string): boolean {
if (s.endsWith('.')) {
return false;
}
const ss = s.split('.');
if (ss.length !== 4) {
return false;
}
for (const t of ss) {
if (t.length === 0 || (t.length > 1 && t[0] === '0')) {
return false;
}
const x = convert(t);
if (x < 0 || x > 255) {
return false;
}
}
return true;
}
function isIPv6(s: string): boolean {
if (s.endsWith(':')) {
return false;
}
const ss = s.split(':');
if (ss.length !== 8) {
return false;
}
for (const t of ss) {
if (t.length < 1 || t.length > 4) {
return false;
}
for (const c of t) {
if (!isHexDigit(c)) {
return false;
}
}
}
return true;
}
function convert(s: string): number {
let x = 0;
for (const c of s) {
if (!isDigit(c)) {
return -1;
}
x = x * 10 + (c.charCodeAt(0) - '0'.charCodeAt(0));
if (x > 255) {
return x;
}
}
return x;
}
function isDigit(c: string): boolean {
return c >= '0' && c <= '9';
}
function isHexDigit(c: string): boolean {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
|
469
|
Convex Polygon
|
Medium
|
<p>You are given an array of points on the <strong>X-Y</strong> plane <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. The points form a polygon when joined sequentially.</p>
<p>Return <code>true</code> if this polygon is <a href="http://en.wikipedia.org/wiki/Convex_polygon" target="_blank">convex</a> and <code>false</code> otherwise.</p>
<p>You may assume the polygon formed by given points is always a <a href="http://en.wikipedia.org/wiki/Simple_polygon" target="_blank">simple polygon</a>. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly1-plane.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,5],[5,5],[5,0]]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly2-plane.jpg" style="width: 300px; height: 303px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>4</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Geometry; Array; Math
|
C++
|
class Solution {
public:
bool isConvex(vector<vector<int>>& points) {
int n = points.size();
long long pre = 0, cur = 0;
for (int i = 0; i < n; ++i) {
int x1 = points[(i + 1) % n][0] - points[i][0];
int y1 = points[(i + 1) % n][1] - points[i][1];
int x2 = points[(i + 2) % n][0] - points[i][0];
int y2 = points[(i + 2) % n][1] - points[i][1];
cur = 1L * x1 * y2 - x2 * y1;
if (cur != 0) {
if (cur * pre < 0) {
return false;
}
pre = cur;
}
}
return true;
}
};
|
469
|
Convex Polygon
|
Medium
|
<p>You are given an array of points on the <strong>X-Y</strong> plane <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. The points form a polygon when joined sequentially.</p>
<p>Return <code>true</code> if this polygon is <a href="http://en.wikipedia.org/wiki/Convex_polygon" target="_blank">convex</a> and <code>false</code> otherwise.</p>
<p>You may assume the polygon formed by given points is always a <a href="http://en.wikipedia.org/wiki/Simple_polygon" target="_blank">simple polygon</a>. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly1-plane.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,5],[5,5],[5,0]]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly2-plane.jpg" style="width: 300px; height: 303px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>4</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Geometry; Array; Math
|
Go
|
func isConvex(points [][]int) bool {
n := len(points)
pre, cur := 0, 0
for i := range points {
x1 := points[(i+1)%n][0] - points[i][0]
y1 := points[(i+1)%n][1] - points[i][1]
x2 := points[(i+2)%n][0] - points[i][0]
y2 := points[(i+2)%n][1] - points[i][1]
cur = x1*y2 - x2*y1
if cur != 0 {
if cur*pre < 0 {
return false
}
pre = cur
}
}
return true
}
|
469
|
Convex Polygon
|
Medium
|
<p>You are given an array of points on the <strong>X-Y</strong> plane <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. The points form a polygon when joined sequentially.</p>
<p>Return <code>true</code> if this polygon is <a href="http://en.wikipedia.org/wiki/Convex_polygon" target="_blank">convex</a> and <code>false</code> otherwise.</p>
<p>You may assume the polygon formed by given points is always a <a href="http://en.wikipedia.org/wiki/Simple_polygon" target="_blank">simple polygon</a>. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly1-plane.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,5],[5,5],[5,0]]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly2-plane.jpg" style="width: 300px; height: 303px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>4</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Geometry; Array; Math
|
Java
|
class Solution {
public boolean isConvex(List<List<Integer>> points) {
int n = points.size();
long pre = 0, cur = 0;
for (int i = 0; i < n; ++i) {
var p1 = points.get(i);
var p2 = points.get((i + 1) % n);
var p3 = points.get((i + 2) % n);
int x1 = p2.get(0) - p1.get(0);
int y1 = p2.get(1) - p1.get(1);
int x2 = p3.get(0) - p1.get(0);
int y2 = p3.get(1) - p1.get(1);
cur = x1 * y2 - x2 * y1;
if (cur != 0) {
if (cur * pre < 0) {
return false;
}
pre = cur;
}
}
return true;
}
}
|
469
|
Convex Polygon
|
Medium
|
<p>You are given an array of points on the <strong>X-Y</strong> plane <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>. The points form a polygon when joined sequentially.</p>
<p>Return <code>true</code> if this polygon is <a href="http://en.wikipedia.org/wiki/Convex_polygon" target="_blank">convex</a> and <code>false</code> otherwise.</p>
<p>You may assume the polygon formed by given points is always a <a href="http://en.wikipedia.org/wiki/Simple_polygon" target="_blank">simple polygon</a>. In other words, we ensure that exactly two edges intersect at each vertex and that edges otherwise don't intersect each other.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly1-plane.jpg" style="width: 300px; height: 294px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,5],[5,5],[5,0]]
<strong>Output:</strong> true
</pre>
<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0469.Convex%20Polygon/images/covpoly2-plane.jpg" style="width: 300px; height: 303px;" />
<pre>
<strong>Input:</strong> points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
<strong>Output:</strong> false
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>3 <= points.length <= 10<sup>4</sup></code></li>
<li><code>points[i].length == 2</code></li>
<li><code>-10<sup>4</sup> <= x<sub>i</sub>, y<sub>i</sub> <= 10<sup>4</sup></code></li>
<li>All the given points are <strong>unique</strong>.</li>
</ul>
|
Geometry; Array; Math
|
Python
|
class Solution:
def isConvex(self, points: List[List[int]]) -> bool:
n = len(points)
pre = cur = 0
for i in range(n):
x1 = points[(i + 1) % n][0] - points[i][0]
y1 = points[(i + 1) % n][1] - points[i][1]
x2 = points[(i + 2) % n][0] - points[i][0]
y2 = points[(i + 2) % n][1] - points[i][1]
cur = x1 * y2 - x2 * y1
if cur != 0:
if cur * pre < 0:
return False
pre = cur
return True
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
C++
|
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
while (1) {
int i = rand7() - 1;
int j = rand7();
int x = i * 7 + j;
if (x <= 40) {
return x % 10 + 1;
}
}
}
};
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
Go
|
func rand10() int {
for {
i := rand7() - 1
j := rand7()
x := i*7 + j
if x <= 40 {
return x%10 + 1
}
}
}
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
Java
|
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
while (true) {
int i = rand7() - 1;
int j = rand7();
int x = i * 7 + j;
if (x <= 40) {
return x % 10 + 1;
}
}
}
}
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
Python
|
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
while 1:
i = rand7() - 1
j = rand7()
x = i * 7 + j
if x <= 40:
return x % 10 + 1
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
Rust
|
/**
* The rand7() API is already defined for you.
* @return a random integer in the range 1 to 7
* fn rand7() -> i32;
*/
impl Solution {
pub fn rand10() -> i32 {
loop {
let i = rand7() - 1;
let j = rand7();
let x = i * 7 + j;
if x <= 40 {
return (x % 10) + 1;
}
}
}
}
|
470
|
Implement Rand10() Using Rand7()
|
Medium
|
<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't call any other API. Please <strong>do not</strong> use a language's built-in random API.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> [2]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> [2,8]
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,8,10]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 10<sup>5</sup></code></li>
</ul>
<p> </p>
<p><strong>Follow up:</strong></p>
<ul>
<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>
<li>Could you minimize the number of calls to <code>rand7()</code>?</li>
</ul>
|
Math; Rejection Sampling; Probability and Statistics; Randomized
|
TypeScript
|
/**
* The rand7() API is already defined for you.
* function rand7(): number {}
* @return a random integer in the range 1 to 7
*/
function rand10(): number {
while (true) {
const i = rand7() - 1;
const j = rand7();
const x = i * 7 + j;
if (x <= 40) {
return (x % 10) + 1;
}
}
}
|
471
|
Encode String with Shortest Length
|
Hard
|
<p>Given a string <code>s</code>, encode the string such that its encoded length is the shortest.</p>
<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. <code>k</code> should be a positive integer.</p>
<p>If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaa"
<strong>Output:</strong> "aaa"
<strong>Explanation:</strong> There is no way to encode it such that it is shorter than the input string, so we do not encode it.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> "5[a]"
<strong>Explanation:</strong> "5[a]" is shorter than "aaaaa" by 1 character.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaaaaaaa"
<strong>Output:</strong> "10[a]"
<strong>Explanation:</strong> "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 150</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
C++
|
class Solution {
public:
string encode(string s) {
int n = s.size();
vector<vector<string>> f(n, vector<string>(n));
auto g = [&](int i, int j) {
string t = s.substr(i, j - i + 1);
if (t.size() < 5) {
return t;
}
int k = (t + t).find(t, 1);
if (k < t.size()) {
int cnt = t.size() / k;
return to_string(cnt) + "[" + f[i][i + k - 1] + "]";
}
return t;
};
for (int i = n - 1; ~i; --i) {
for (int j = i; j < n; ++j) {
f[i][j] = g(i, j);
if (j - i + 1 > 4) {
for (int k = i; k < j; ++k) {
string t = f[i][k] + f[k + 1][j];
if (t.size() < f[i][j].size()) {
f[i][j] = t;
}
}
}
}
}
return f[0][n - 1];
}
};
|
471
|
Encode String with Shortest Length
|
Hard
|
<p>Given a string <code>s</code>, encode the string such that its encoded length is the shortest.</p>
<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. <code>k</code> should be a positive integer.</p>
<p>If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaa"
<strong>Output:</strong> "aaa"
<strong>Explanation:</strong> There is no way to encode it such that it is shorter than the input string, so we do not encode it.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> "5[a]"
<strong>Explanation:</strong> "5[a]" is shorter than "aaaaa" by 1 character.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaaaaaaa"
<strong>Output:</strong> "10[a]"
<strong>Explanation:</strong> "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 150</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Go
|
func encode(s string) string {
n := len(s)
f := make([][]string, n)
for i := range f {
f[i] = make([]string, n)
}
g := func(i, j int) string {
t := s[i : j+1]
if len(t) < 5 {
return t
}
k := strings.Index((t + t)[1:], t) + 1
if k < len(t) {
cnt := len(t) / k
return strconv.Itoa(cnt) + "[" + f[i][i+k-1] + "]"
}
return t
}
for i := n - 1; i >= 0; i-- {
for j := i; j < n; j++ {
f[i][j] = g(i, j)
if j-i+1 > 4 {
for k := i; k < j; k++ {
t := f[i][k] + f[k+1][j]
if len(t) < len(f[i][j]) {
f[i][j] = t
}
}
}
}
}
return f[0][n-1]
}
|
471
|
Encode String with Shortest Length
|
Hard
|
<p>Given a string <code>s</code>, encode the string such that its encoded length is the shortest.</p>
<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. <code>k</code> should be a positive integer.</p>
<p>If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaa"
<strong>Output:</strong> "aaa"
<strong>Explanation:</strong> There is no way to encode it such that it is shorter than the input string, so we do not encode it.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> "5[a]"
<strong>Explanation:</strong> "5[a]" is shorter than "aaaaa" by 1 character.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaaaaaaa"
<strong>Output:</strong> "10[a]"
<strong>Explanation:</strong> "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 150</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Java
|
class Solution {
private String s;
private String[][] f;
public String encode(String s) {
this.s = s;
int n = s.length();
f = new String[n][n];
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
f[i][j] = g(i, j);
if (j - i + 1 > 4) {
for (int k = i; k < j; ++k) {
String t = f[i][k] + f[k + 1][j];
if (f[i][j].length() > t.length()) {
f[i][j] = t;
}
}
}
}
}
return f[0][n - 1];
}
private String g(int i, int j) {
String t = s.substring(i, j + 1);
if (t.length() < 5) {
return t;
}
int k = (t + t).indexOf(t, 1);
if (k < t.length()) {
int cnt = t.length() / k;
return String.format("%d[%s]", cnt, f[i][i + k - 1]);
}
return t;
}
}
|
471
|
Encode String with Shortest Length
|
Hard
|
<p>Given a string <code>s</code>, encode the string such that its encoded length is the shortest.</p>
<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. <code>k</code> should be a positive integer.</p>
<p>If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaa"
<strong>Output:</strong> "aaa"
<strong>Explanation:</strong> There is no way to encode it such that it is shorter than the input string, so we do not encode it.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> "5[a]"
<strong>Explanation:</strong> "5[a]" is shorter than "aaaaa" by 1 character.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaaaaaaa"
<strong>Output:</strong> "10[a]"
<strong>Explanation:</strong> "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 150</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
Python
|
class Solution:
def encode(self, s: str) -> str:
def g(i: int, j: int) -> str:
t = s[i : j + 1]
if len(t) < 5:
return t
k = (t + t).index(t, 1)
if k < len(t):
cnt = len(t) // k
return f"{cnt}[{f[i][i + k - 1]}]"
return t
n = len(s)
f = [[None] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
f[i][j] = g(i, j)
if j - i + 1 > 4:
for k in range(i, j):
t = f[i][k] + f[k + 1][j]
if len(f[i][j]) > len(t):
f[i][j] = t
return f[0][-1]
|
471
|
Encode String with Shortest Length
|
Hard
|
<p>Given a string <code>s</code>, encode the string such that its encoded length is the shortest.</p>
<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. <code>k</code> should be a positive integer.</p>
<p>If an encoding process does not make the string shorter, then do not encode it. If there are several solutions, return <strong>any of them</strong>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> s = "aaa"
<strong>Output:</strong> "aaa"
<strong>Explanation:</strong> There is no way to encode it such that it is shorter than the input string, so we do not encode it.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaa"
<strong>Output:</strong> "5[a]"
<strong>Explanation:</strong> "5[a]" is shorter than "aaaaa" by 1 character.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> s = "aaaaaaaaaa"
<strong>Output:</strong> "10[a]"
<strong>Explanation:</strong> "a9[a]" or "9[a]a" are also valid solutions, both of them have the same length = 5, which is the same as "10[a]".
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= s.length <= 150</code></li>
<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
|
String; Dynamic Programming
|
TypeScript
|
function encode(s: string): string {
const n = s.length;
const f: string[][] = new Array(n).fill(0).map(() => new Array(n).fill(''));
const g = (i: number, j: number): string => {
const t = s.slice(i, j + 1);
if (t.length < 5) {
return t;
}
const k = t.repeat(2).indexOf(t, 1);
if (k < t.length) {
const cnt = Math.floor(t.length / k);
return cnt + '[' + f[i][i + k - 1] + ']';
}
return t;
};
for (let i = n - 1; i >= 0; --i) {
for (let j = i; j < n; ++j) {
f[i][j] = g(i, j);
if (j - i + 1 > 4) {
for (let k = i; k < j; ++k) {
const t = f[i][k] + f[k + 1][j];
if (t.length < f[i][j].length) {
f[i][j] = t;
}
}
}
}
}
return f[0][n - 1];
}
|
472
|
Concatenated Words
|
Hard
|
<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>
<p>A <strong>concatenated word</strong> is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
<strong>Output:</strong> ["catsdogcats","dogcatsdog","ratcatdogcat"]
<strong>Explanation:</strong> "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","dog","catdog"]
<strong>Output:</strong> ["catdog"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= 30</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>
<li><code>1 <= sum(words[i].length) <= 10<sup>5</sup></code></li>
</ul>
|
Depth-First Search; Trie; Array; String; Dynamic Programming; Sorting
|
C++
|
class Trie {
public:
vector<Trie*> children;
bool isEnd;
Trie()
: children(26)
, isEnd(false) {}
void insert(string w) {
Trie* node = this;
for (char c : w) {
c -= 'a';
if (!node->children[c]) node->children[c] = new Trie();
node = node->children[c];
}
node->isEnd = true;
}
};
class Solution {
public:
Trie* trie = new Trie();
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
sort(words.begin(), words.end(), [&](const string& a, const string& b) {
return a.size() < b.size();
});
vector<string> ans;
for (auto& w : words) {
if (dfs(w))
ans.push_back(w);
else
trie->insert(w);
}
return ans;
}
bool dfs(string w) {
if (w == "") return true;
Trie* node = trie;
for (int i = 0; i < w.size(); ++i) {
int idx = w[i] - 'a';
if (!node->children[idx]) return false;
node = node->children[idx];
if (node->isEnd && dfs(w.substr(i + 1))) return true;
}
return false;
}
};
|
472
|
Concatenated Words
|
Hard
|
<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>
<p>A <strong>concatenated word</strong> is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
<strong>Output:</strong> ["catsdogcats","dogcatsdog","ratcatdogcat"]
<strong>Explanation:</strong> "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","dog","catdog"]
<strong>Output:</strong> ["catdog"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= 30</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>
<li><code>1 <= sum(words[i].length) <= 10<sup>5</sup></code></li>
</ul>
|
Depth-First Search; Trie; Array; String; Dynamic Programming; Sorting
|
Go
|
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func findAllConcatenatedWordsInADict(words []string) (ans []string) {
sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })
trie := newTrie()
var dfs func(string) bool
dfs = func(w string) bool {
if w == "" {
return true
}
node := trie
for i, c := range w {
c -= 'a'
if node.children[c] == nil {
return false
}
node = node.children[c]
if node.isEnd && dfs(w[i+1:]) {
return true
}
}
return false
}
for _, w := range words {
if dfs(w) {
ans = append(ans, w)
} else {
trie.insert(w)
}
}
return
}
|
472
|
Concatenated Words
|
Hard
|
<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>
<p>A <strong>concatenated word</strong> is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
<strong>Output:</strong> ["catsdogcats","dogcatsdog","ratcatdogcat"]
<strong>Explanation:</strong> "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","dog","catdog"]
<strong>Output:</strong> ["catdog"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= 30</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>
<li><code>1 <= sum(words[i].length) <= 10<sup>5</sup></code></li>
</ul>
|
Depth-First Search; Trie; Array; String; Dynamic Programming; Sorting
|
Java
|
class Trie {
Trie[] children = new Trie[26];
boolean isEnd;
void insert(String w) {
Trie node = this;
for (char c : w.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
}
class Solution {
private Trie trie = new Trie();
public List<String> findAllConcatenatedWordsInADict(String[] words) {
Arrays.sort(words, (a, b) -> a.length() - b.length());
List<String> ans = new ArrayList<>();
for (String w : words) {
if (dfs(w)) {
ans.add(w);
} else {
trie.insert(w);
}
}
return ans;
}
private boolean dfs(String w) {
if ("".equals(w)) {
return true;
}
Trie node = trie;
for (int i = 0; i < w.length(); ++i) {
int idx = w.charAt(i) - 'a';
if (node.children[idx] == null) {
return false;
}
node = node.children[idx];
if (node.isEnd && dfs(w.substring(i + 1))) {
return true;
}
}
return false;
}
}
|
472
|
Concatenated Words
|
Hard
|
<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>
<p>A <strong>concatenated word</strong> is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
<strong>Output:</strong> ["catsdogcats","dogcatsdog","ratcatdogcat"]
<strong>Explanation:</strong> "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["cat","dog","catdog"]
<strong>Output:</strong> ["catdog"]
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 10<sup>4</sup></code></li>
<li><code>1 <= words[i].length <= 30</code></li>
<li><code>words[i]</code> consists of only lowercase English letters.</li>
<li>All the strings of <code>words</code> are <strong>unique</strong>.</li>
<li><code>1 <= sum(words[i].length) <= 10<sup>5</sup></code></li>
</ul>
|
Depth-First Search; Trie; Array; String; Dynamic Programming; Sorting
|
Python
|
class Trie:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, w):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.is_end = True
class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
def dfs(w):
if not w:
return True
node = trie
for i, c in enumerate(w):
idx = ord(c) - ord('a')
if node.children[idx] is None:
return False
node = node.children[idx]
if node.is_end and dfs(w[i + 1 :]):
return True
return False
trie = Trie()
ans = []
words.sort(key=lambda x: len(x))
for w in words:
if dfs(w):
ans.append(w)
else:
trie.insert(w)
return ans
|
473
|
Matchsticks to Square
|
Medium
|
<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>
<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0473.Matchsticks%20to%20Square/images/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= matchsticks.length <= 15</code></li>
<li><code>1 <= matchsticks[i] <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
C++
|
class Solution {
public:
bool makesquare(vector<int>& matchsticks) {
int s = 0, mx = 0;
for (int& v : matchsticks) {
s += v;
mx = max(mx, v);
}
int x = s / 4, mod = s % 4;
if (mod != 0 || x < mx) return false;
sort(matchsticks.begin(), matchsticks.end(), greater<int>());
vector<int> edges(4);
return dfs(0, x, matchsticks, edges);
}
bool dfs(int u, int x, vector<int>& matchsticks, vector<int>& edges) {
if (u == matchsticks.size()) return true;
for (int i = 0; i < 4; ++i) {
if (i > 0 && edges[i - 1] == edges[i]) continue;
edges[i] += matchsticks[u];
if (edges[i] <= x && dfs(u + 1, x, matchsticks, edges)) return true;
edges[i] -= matchsticks[u];
}
return false;
}
};
|
473
|
Matchsticks to Square
|
Medium
|
<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>
<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0473.Matchsticks%20to%20Square/images/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= matchsticks.length <= 15</code></li>
<li><code>1 <= matchsticks[i] <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Go
|
func makesquare(matchsticks []int) bool {
s := 0
for _, v := range matchsticks {
s += v
}
if s%4 != 0 {
return false
}
sort.Sort(sort.Reverse(sort.IntSlice(matchsticks)))
edges := make([]int, 4)
var dfs func(u, x int) bool
dfs = func(u, x int) bool {
if u == len(matchsticks) {
return true
}
for i := 0; i < 4; i++ {
if i > 0 && edges[i-1] == edges[i] {
continue
}
edges[i] += matchsticks[u]
if edges[i] <= x && dfs(u+1, x) {
return true
}
edges[i] -= matchsticks[u]
}
return false
}
return dfs(0, s/4)
}
|
473
|
Matchsticks to Square
|
Medium
|
<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>
<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0473.Matchsticks%20to%20Square/images/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= matchsticks.length <= 15</code></li>
<li><code>1 <= matchsticks[i] <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Java
|
class Solution {
public boolean makesquare(int[] matchsticks) {
int s = 0, mx = 0;
for (int v : matchsticks) {
s += v;
mx = Math.max(mx, v);
}
int x = s / 4, mod = s % 4;
if (mod != 0 || x < mx) {
return false;
}
Arrays.sort(matchsticks);
int[] edges = new int[4];
return dfs(matchsticks.length - 1, x, matchsticks, edges);
}
private boolean dfs(int u, int x, int[] matchsticks, int[] edges) {
if (u < 0) {
return true;
}
for (int i = 0; i < 4; ++i) {
if (i > 0 && edges[i - 1] == edges[i]) {
continue;
}
edges[i] += matchsticks[u];
if (edges[i] <= x && dfs(u - 1, x, matchsticks, edges)) {
return true;
}
edges[i] -= matchsticks[u];
}
return false;
}
}
|
473
|
Matchsticks to Square
|
Medium
|
<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>
<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0473.Matchsticks%20to%20Square/images/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= matchsticks.length <= 15</code></li>
<li><code>1 <= matchsticks[i] <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Python
|
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
def dfs(u):
if u == len(matchsticks):
return True
for i in range(4):
if i > 0 and edges[i - 1] == edges[i]:
continue
edges[i] += matchsticks[u]
if edges[i] <= x and dfs(u + 1):
return True
edges[i] -= matchsticks[u]
return False
x, mod = divmod(sum(matchsticks), 4)
if mod or x < max(matchsticks):
return False
edges = [0] * 4
matchsticks.sort(reverse=True)
return dfs(0)
|
473
|
Matchsticks to Square
|
Medium
|
<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>
<p>Return <code>true</code> if you can make this square and <code>false</code> otherwise.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0400-0499/0473.Matchsticks%20to%20Square/images/matchsticks1-grid.jpg" style="width: 253px; height: 253px;" />
<pre>
<strong>Input:</strong> matchsticks = [1,1,2,2,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> You can form a square with length 2, one side of the square came two sticks with length 1.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> matchsticks = [3,3,3,3,4]
<strong>Output:</strong> false
<strong>Explanation:</strong> You cannot find a way to form a square with all the matchsticks.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= matchsticks.length <= 15</code></li>
<li><code>1 <= matchsticks[i] <= 10<sup>8</sup></code></li>
</ul>
|
Bit Manipulation; Array; Dynamic Programming; Backtracking; Bitmask
|
Rust
|
impl Solution {
pub fn makesquare(matchsticks: Vec<i32>) -> bool {
let mut matchsticks = matchsticks;
fn dfs(matchsticks: &Vec<i32>, edges: &mut [i32; 4], u: usize, x: i32) -> bool {
if u == matchsticks.len() {
return true;
}
for i in 0..4 {
if i > 0 && edges[i - 1] == edges[i] {
continue;
}
edges[i] += matchsticks[u];
if edges[i] <= x && dfs(matchsticks, edges, u + 1, x) {
return true;
}
edges[i] -= matchsticks[u];
}
false
}
let sum: i32 = matchsticks.iter().sum();
if sum % 4 != 0 {
return false;
}
matchsticks.sort_by(|x, y| y.cmp(x));
let mut edges = [0; 4];
dfs(&matchsticks, &mut edges, 0, sum / 4)
}
}
|
474
|
Ones and Zeroes
|
Medium
|
<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>
<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>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<strong>Output:</strong> 2
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Array; String; Dynamic Programming
|
C++
|
class Solution {
public:
int findMaxForm(vector<string>& strs, int m, int n) {
int sz = strs.size();
int f[sz + 1][m + 1][n + 1];
memset(f, 0, sizeof(f));
for (int i = 1; i <= sz; ++i) {
auto [a, b] = count(strs[i - 1]);
for (int j = 0; j <= m; ++j) {
for (int k = 0; k <= n; ++k) {
f[i][j][k] = f[i - 1][j][k];
if (j >= a && k >= b) {
f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1);
}
}
}
}
return f[sz][m][n];
}
pair<int, int> count(string& s) {
int a = count_if(s.begin(), s.end(), [](char c) { return c == '0'; });
return {a, s.size() - a};
}
};
|
474
|
Ones and Zeroes
|
Medium
|
<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>
<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>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<strong>Output:</strong> 2
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Array; String; Dynamic Programming
|
Go
|
func findMaxForm(strs []string, m int, n int) int {
sz := len(strs)
f := make([][][]int, sz+1)
for i := range f {
f[i] = make([][]int, m+1)
for j := range f[i] {
f[i][j] = make([]int, n+1)
}
}
for i := 1; i <= sz; i++ {
a, b := count(strs[i-1])
for j := 0; j <= m; j++ {
for k := 0; k <= n; k++ {
f[i][j][k] = f[i-1][j][k]
if j >= a && k >= b {
f[i][j][k] = max(f[i][j][k], f[i-1][j-a][k-b]+1)
}
}
}
}
return f[sz][m][n]
}
func count(s string) (int, int) {
a := strings.Count(s, "0")
return a, len(s) - a
}
|
474
|
Ones and Zeroes
|
Medium
|
<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>
<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>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<strong>Output:</strong> 2
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Array; String; Dynamic Programming
|
Java
|
class Solution {
public int findMaxForm(String[] strs, int m, int n) {
int sz = strs.length;
int[][][] f = new int[sz + 1][m + 1][n + 1];
for (int i = 1; i <= sz; ++i) {
int[] cnt = count(strs[i - 1]);
for (int j = 0; j <= m; ++j) {
for (int k = 0; k <= n; ++k) {
f[i][j][k] = f[i - 1][j][k];
if (j >= cnt[0] && k >= cnt[1]) {
f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - cnt[0]][k - cnt[1]] + 1);
}
}
}
}
return f[sz][m][n];
}
private int[] count(String s) {
int[] cnt = new int[2];
for (int i = 0; i < s.length(); ++i) {
++cnt[s.charAt(i) - '0'];
}
return cnt;
}
}
|
474
|
Ones and Zeroes
|
Medium
|
<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>
<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>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<strong>Output:</strong> 2
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Array; String; Dynamic Programming
|
Python
|
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
sz = len(strs)
f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)]
for i, s in enumerate(strs, 1):
a, b = s.count("0"), s.count("1")
for j in range(m + 1):
for k in range(n + 1):
f[i][j][k] = f[i - 1][j][k]
if j >= a and k >= b:
f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1)
return f[sz][m][n]
|
474
|
Ones and Zeroes
|
Medium
|
<p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>
<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>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<strong>Output:</strong> 2
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= strs.length <= 600</code></li>
<li><code>1 <= strs[i].length <= 100</code></li>
<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
<li><code>1 <= m, n <= 100</code></li>
</ul>
|
Array; String; Dynamic Programming
|
TypeScript
|
function findMaxForm(strs: string[], m: number, n: number): number {
const sz = strs.length;
const f = Array.from({ length: sz + 1 }, () =>
Array.from({ length: m + 1 }, () => Array.from({ length: n + 1 }, () => 0)),
);
const count = (s: string): [number, number] => {
let a = 0;
for (const c of s) {
a += c === '0' ? 1 : 0;
}
return [a, s.length - a];
};
for (let i = 1; i <= sz; ++i) {
const [a, b] = count(strs[i - 1]);
for (let j = 0; j <= m; ++j) {
for (let k = 0; k <= n; ++k) {
f[i][j][k] = f[i - 1][j][k];
if (j >= a && k >= b) {
f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - a][k - b] + 1);
}
}
}
}
return f[sz][m][n];
}
|
475
|
Heaters
|
Medium
|
<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>
<p>Every house can be warmed, as long as the house is within the heater's warm radius range. </p>
<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters so that those heaters could cover all houses.</em></p>
<p><strong>Notice</strong> that all the <code>heaters</code> follow your radius standard, and the warm radius will be the same.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3], heaters = [2]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,5], heaters = [2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= houses.length, heaters.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= houses[i], heaters[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
C++
|
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int left = 0, right = 1e9;
while (left < right) {
int mid = left + right >> 1;
if (check(houses, heaters, mid))
right = mid;
else
left = mid + 1;
}
return left;
}
bool check(vector<int>& houses, vector<int>& heaters, int r) {
int m = houses.size(), n = heaters.size();
int i = 0, j = 0;
while (i < m) {
if (j >= n) return false;
int mi = heaters[j] - r;
int mx = heaters[j] + r;
if (houses[i] < mi) return false;
if (houses[i] > mx)
++j;
else
++i;
}
return true;
}
};
|
475
|
Heaters
|
Medium
|
<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>
<p>Every house can be warmed, as long as the house is within the heater's warm radius range. </p>
<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters so that those heaters could cover all houses.</em></p>
<p><strong>Notice</strong> that all the <code>heaters</code> follow your radius standard, and the warm radius will be the same.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3], heaters = [2]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,5], heaters = [2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= houses.length, heaters.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= houses[i], heaters[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Go
|
func findRadius(houses []int, heaters []int) int {
sort.Ints(houses)
sort.Ints(heaters)
m, n := len(houses), len(heaters)
check := func(r int) bool {
var i, j int
for i < m {
if j >= n {
return false
}
mi, mx := heaters[j]-r, heaters[j]+r
if houses[i] < mi {
return false
}
if houses[i] > mx {
j++
} else {
i++
}
}
return true
}
left, right := 0, int(1e9)
for left < right {
mid := (left + right) >> 1
if check(mid) {
right = mid
} else {
left = mid + 1
}
}
return left
}
|
475
|
Heaters
|
Medium
|
<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>
<p>Every house can be warmed, as long as the house is within the heater's warm radius range. </p>
<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters so that those heaters could cover all houses.</em></p>
<p><strong>Notice</strong> that all the <code>heaters</code> follow your radius standard, and the warm radius will be the same.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3], heaters = [2]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,5], heaters = [2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= houses.length, heaters.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= houses[i], heaters[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Java
|
class Solution {
public int findRadius(int[] houses, int[] heaters) {
Arrays.sort(heaters);
int res = 0;
for (int x : houses) {
int i = Arrays.binarySearch(heaters, x);
if (i < 0) {
i = ~i;
}
int dis1 = i > 0 ? x - heaters[i - 1] : Integer.MAX_VALUE;
int dis2 = i < heaters.length ? heaters[i] - x : Integer.MAX_VALUE;
res = Math.max(res, Math.min(dis1, dis2));
}
return res;
}
}
|
475
|
Heaters
|
Medium
|
<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>
<p>Every house can be warmed, as long as the house is within the heater's warm radius range. </p>
<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters so that those heaters could cover all houses.</em></p>
<p><strong>Notice</strong> that all the <code>heaters</code> follow your radius standard, and the warm radius will be the same.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3], heaters = [2]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,5], heaters = [2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= houses.length, heaters.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= houses[i], heaters[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
Python
|
class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
def check(r):
m, n = len(houses), len(heaters)
i = j = 0
while i < m:
if j >= n:
return False
mi = heaters[j] - r
mx = heaters[j] + r
if houses[i] < mi:
return False
if houses[i] > mx:
j += 1
else:
i += 1
return True
left, right = 0, int(1e9)
while left < right:
mid = (left + right) >> 1
if check(mid):
right = mid
else:
left = mid + 1
return left
|
475
|
Heaters
|
Medium
|
<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>
<p>Every house can be warmed, as long as the house is within the heater's warm radius range. </p>
<p>Given the positions of <code>houses</code> and <code>heaters</code> on a horizontal line, return <em>the minimum radius standard of heaters so that those heaters could cover all houses.</em></p>
<p><strong>Notice</strong> that all the <code>heaters</code> follow your radius standard, and the warm radius will be the same.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3], heaters = [2]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,2,3,4], heaters = [1,4]
<strong>Output:</strong> 1
<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.
</pre>
<p><strong class="example">Example 3:</strong></p>
<pre>
<strong>Input:</strong> houses = [1,5], heaters = [2]
<strong>Output:</strong> 3
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= houses.length, heaters.length <= 3 * 10<sup>4</sup></code></li>
<li><code>1 <= houses[i], heaters[i] <= 10<sup>9</sup></code></li>
</ul>
|
Array; Two Pointers; Binary Search; Sorting
|
TypeScript
|
function findRadius(houses: number[], heaters: number[]): number {
houses.sort((a, b) => a - b);
heaters.sort((a, b) => a - b);
const m = houses.length,
n = heaters.length;
let ans = 0;
for (let i = 0, j = 0; i < m; i++) {
let cur = Math.abs(houses[i] - heaters[j]);
while (
j + 1 < n &&
Math.abs(houses[i] - heaters[j]) >= Math.abs(houses[i] - heaters[j + 1])
) {
cur = Math.min(Math.abs(houses[i] - heaters[++j]), cur);
}
ans = Math.max(cur, ans);
}
return ans;
}
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
C++
|
class Solution {
public:
int findComplement(int num) {
return num ^ ((1LL << (64 - __builtin_clzll(num))) - 1);
}
};
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Go
|
func findComplement(num int) int {
return num ^ ((1 << bits.Len(uint(num))) - 1)
}
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Java
|
class Solution {
public int findComplement(int num) {
return num ^ ((1 << (32 - Integer.numberOfLeadingZeros(num))) - 1);
}
}
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
JavaScript
|
/**
* @param {number} num
* @return {number}
*/
var findComplement = function (num) {
return num ^ (2 ** num.toString(2).length - 1);
};
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
Python
|
class Solution:
def findComplement(self, num: int) -> int:
return num ^ ((1 << num.bit_length()) - 1)
|
476
|
Number Complement
|
Easy
|
<p>The <strong>complement</strong> of an integer is the integer you get when you flip all the <code>0</code>'s to <code>1</code>'s and all the <code>1</code>'s to <code>0</code>'s in its binary representation.</p>
<ul>
<li>For example, The integer <code>5</code> is <code>"101"</code> in binary and its <strong>complement</strong> is <code>"010"</code> which is the integer <code>2</code>.</li>
</ul>
<p>Given an integer <code>num</code>, return <em>its complement</em>.</p>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> num = 5
<strong>Output:</strong> 2
<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.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> num = 1
<strong>Output:</strong> 0
<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.
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= num < 2<sup>31</sup></code></li>
</ul>
<p> </p>
<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>
|
Bit Manipulation
|
TypeScript
|
function findComplement(num: number): number {
return num ^ (2 ** num.toString(2).length - 1);
}
|
477
|
Total Hamming Distance
|
Medium
|
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
C++
|
class Solution {
public:
int totalHammingDistance(vector<int>& nums) {
int ans = 0, n = nums.size();
for (int i = 0; i < 32; ++i) {
int a = 0;
for (int x : nums) {
a += x >> i & 1;
}
int b = n - a;
ans += a * b;
}
return ans;
}
};
|
477
|
Total Hamming Distance
|
Medium
|
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
Go
|
func totalHammingDistance(nums []int) (ans int) {
for i := 0; i < 32; i++ {
a := 0
for _, x := range nums {
a += x >> i & 1
}
b := len(nums) - a
ans += a * b
}
return
}
|
477
|
Total Hamming Distance
|
Medium
|
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
Java
|
class Solution {
public int totalHammingDistance(int[] nums) {
int ans = 0, n = nums.length;
for (int i = 0; i < 32; ++i) {
int a = 0;
for (int x : nums) {
a += (x >> i & 1);
}
int b = n - a;
ans += a * b;
}
return ans;
}
}
|
477
|
Total Hamming Distance
|
Medium
|
<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>
<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>
<p> </p>
<p><strong class="example">Example 1:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,2]
<strong>Output:</strong> 6
<strong>Explanation:</strong> In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case).
The answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
</pre>
<p><strong class="example">Example 2:</strong></p>
<pre>
<strong>Input:</strong> nums = [4,14,4]
<strong>Output:</strong> 4
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>4</sup></code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
<li>The answer for the given input will fit in a <strong>32-bit</strong> integer.</li>
</ul>
|
Bit Manipulation; Array; Math
|
Python
|
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
ans, n = 0, len(nums)
for i in range(32):
a = sum(x >> i & 1 for x in nums)
b = n - a
ans += a * b
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.