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
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
C++
class RandomizedSet { public: RandomizedSet() { } bool insert(int val) { if (d.count(val)) { return false; } d[val] = q.size(); q.push_back(val); return true; } bool remove(int val) { if (!d.count(val)) { return false; } int i = d[val]; d[q.back()] = i; q[i] = q.back(); q.pop_back(); d.erase(val); return true; } int getRandom() { return q[rand() % q.size()]; } private: unordered_map<int, int> d; vector<int> q; }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet* obj = new RandomizedSet(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
C#
public class RandomizedSet { private Dictionary<int, int> d = new Dictionary<int, int>(); private List<int> q = new List<int>(); public RandomizedSet() { } public bool Insert(int val) { if (d.ContainsKey(val)) { return false; } d.Add(val, q.Count); q.Add(val); return true; } public bool Remove(int val) { if (!d.ContainsKey(val)) { return false; } int i = d[val]; d[q[q.Count - 1]] = i; q[i] = q[q.Count - 1]; q.RemoveAt(q.Count - 1); d.Remove(val); return true; } public int GetRandom() { return q[new Random().Next(0, q.Count)]; } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * bool param_1 = obj.Insert(val); * bool param_2 = obj.Remove(val); * int param_3 = obj.GetRandom(); */
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Go
type RandomizedSet struct { d map[int]int q []int } func Constructor() RandomizedSet { return RandomizedSet{map[int]int{}, []int{}} } func (this *RandomizedSet) Insert(val int) bool { if _, ok := this.d[val]; ok { return false } this.d[val] = len(this.q) this.q = append(this.q, val) return true } func (this *RandomizedSet) Remove(val int) bool { if _, ok := this.d[val]; !ok { return false } i := this.d[val] this.d[this.q[len(this.q)-1]] = i this.q[i] = this.q[len(this.q)-1] this.q = this.q[:len(this.q)-1] delete(this.d, val) return true } func (this *RandomizedSet) GetRandom() int { return this.q[rand.Intn(len(this.q))] } /** * Your RandomizedSet object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Insert(val); * param_2 := obj.Remove(val); * param_3 := obj.GetRandom(); */
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Java
class RandomizedSet { private Map<Integer, Integer> d = new HashMap<>(); private List<Integer> q = new ArrayList<>(); private Random rnd = new Random(); public RandomizedSet() { } public boolean insert(int val) { if (d.containsKey(val)) { return false; } d.put(val, q.size()); q.add(val); return true; } public boolean remove(int val) { if (!d.containsKey(val)) { return false; } int i = d.get(val); d.put(q.get(q.size() - 1), i); q.set(i, q.get(q.size() - 1)); q.remove(q.size() - 1); d.remove(val); return true; } public int getRandom() { return q.get(rnd.nextInt(q.size())); } } /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Python
class RandomizedSet: def __init__(self): self.d = {} self.q = [] def insert(self, val: int) -> bool: if val in self.d: return False self.d[val] = len(self.q) self.q.append(val) return True def remove(self, val: int) -> bool: if val not in self.d: return False i = self.d[val] self.d[self.q[-1]] = i self.q[i] = self.q[-1] self.q.pop() self.d.pop(val) return True def getRandom(self) -> int: return choice(self.q) # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Rust
use rand::Rng; use std::collections::HashSet; struct RandomizedSet { list: HashSet<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl RandomizedSet { fn new() -> Self { Self { list: HashSet::new(), } } fn insert(&mut self, val: i32) -> bool { self.list.insert(val) } fn remove(&mut self, val: i32) -> bool { self.list.remove(&val) } fn get_random(&self) -> i32 { let i = rand::thread_rng().gen_range(0, self.list.len()); *self.list.iter().collect::<Vec<&i32>>()[i] } }
380
Insert Delete GetRandom O(1)
Medium
<p>Implement the <code>RandomizedSet</code> class:</p> <ul> <li><code>RandomizedSet()</code> Initializes the <code>RandomizedSet</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the set if not present. Returns <code>true</code> if the item was not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the set if present. Returns <code>true</code> if the item was present, <code>false</code> otherwise.</li> <li><code>int getRandom()</code> Returns a random element from the current set of elements (it&#39;s guaranteed that at least one element exists when this method is called). Each element must have the <b>same probability</b> of being returned.</li> </ul> <p>You must implement the functions of the class such that each function works in&nbsp;<strong>average</strong>&nbsp;<code>O(1)</code>&nbsp;time complexity.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedSet&quot;, &quot;insert&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;insert&quot;, &quot;getRandom&quot;] [[], [1], [2], [2], [], [1], [2], []] <strong>Output</strong> [null, true, false, true, 2, true, false, 2] <strong>Explanation</strong> RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 *&nbsp;</code><code>10<sup>5</sup></code> calls will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
TypeScript
class RandomizedSet { private d: Map<number, number> = new Map(); private q: number[] = []; constructor() {} insert(val: number): boolean { if (this.d.has(val)) { return false; } this.d.set(val, this.q.length); this.q.push(val); return true; } remove(val: number): boolean { if (!this.d.has(val)) { return false; } const i = this.d.get(val)!; this.d.set(this.q[this.q.length - 1], i); this.q[i] = this.q[this.q.length - 1]; this.q.pop(); this.d.delete(val); return true; } getRandom(): number { return this.q[Math.floor(Math.random() * this.q.length)]; } } /** * Your RandomizedSet object will be instantiated and called as such: * var obj = new RandomizedSet() * var param_1 = obj.insert(val) * var param_2 = obj.remove(val) * var param_3 = obj.getRandom() */
381
Insert Delete GetRandom O(1) - Duplicates allowed
Hard
<p><code>RandomizedCollection</code> is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.</p> <p>Implement the <code>RandomizedCollection</code> class:</p> <ul> <li><code>RandomizedCollection()</code> Initializes the empty <code>RandomizedCollection</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the multiset, even if the item is already present. Returns <code>true</code> if the item is not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the multiset if present. Returns <code>true</code> if the item is present, <code>false</code> otherwise. Note that if <code>val</code> has multiple occurrences in the multiset, we only remove one of them.</li> <li><code>int getRandom()</code> Returns a random element from the current multiset of elements. The probability of each element being returned is <strong>linearly related</strong> to the number of the same values the multiset contains.</li> </ul> <p>You must implement the functions of the class such that each function works on <strong>average</strong> <code>O(1)</code> time complexity.</p> <p><strong>Note:</strong> The test cases are generated such that <code>getRandom</code> will only be called if there is <strong>at least one</strong> item in the <code>RandomizedCollection</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedCollection&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;getRandom&quot;] [[], [1], [1], [2], [], [1], []] <strong>Output</strong> [null, true, false, true, 2, true, 1] <strong>Explanation</strong> RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 * 10<sup>5</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Java
class RandomizedCollection { private Map<Integer, Set<Integer>> m; private List<Integer> l; private Random rnd; /** Initialize your data structure here. */ public RandomizedCollection() { m = new HashMap<>(); l = new ArrayList<>(); rnd = new Random(); } /** * Inserts a value to the collection. Returns true if the collection did not already contain * the specified element. */ public boolean insert(int val) { m.computeIfAbsent(val, k -> new HashSet<>()).add(l.size()); l.add(val); return m.get(val).size() == 1; } /** * Removes a value from the collection. Returns true if the collection contained the specified * element. */ public boolean remove(int val) { if (!m.containsKey(val)) { return false; } Set<Integer> idxSet = m.get(val); int idx = idxSet.iterator().next(); int lastIdx = l.size() - 1; l.set(idx, l.get(lastIdx)); idxSet.remove(idx); Set<Integer> lastIdxSet = m.get(l.get(lastIdx)); lastIdxSet.remove(lastIdx); if (idx < lastIdx) { lastIdxSet.add(idx); } if (idxSet.isEmpty()) { m.remove(val); } l.remove(lastIdx); return true; } /** Get a random element from the collection. */ public int getRandom() { int size = l.size(); return size == 0 ? -1 : l.get(rnd.nextInt(size)); } } /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection obj = new RandomizedCollection(); * boolean param_1 = obj.insert(val); * boolean param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
381
Insert Delete GetRandom O(1) - Duplicates allowed
Hard
<p><code>RandomizedCollection</code> is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.</p> <p>Implement the <code>RandomizedCollection</code> class:</p> <ul> <li><code>RandomizedCollection()</code> Initializes the empty <code>RandomizedCollection</code> object.</li> <li><code>bool insert(int val)</code> Inserts an item <code>val</code> into the multiset, even if the item is already present. Returns <code>true</code> if the item is not present, <code>false</code> otherwise.</li> <li><code>bool remove(int val)</code> Removes an item <code>val</code> from the multiset if present. Returns <code>true</code> if the item is present, <code>false</code> otherwise. Note that if <code>val</code> has multiple occurrences in the multiset, we only remove one of them.</li> <li><code>int getRandom()</code> Returns a random element from the current multiset of elements. The probability of each element being returned is <strong>linearly related</strong> to the number of the same values the multiset contains.</li> </ul> <p>You must implement the functions of the class such that each function works on <strong>average</strong> <code>O(1)</code> time complexity.</p> <p><strong>Note:</strong> The test cases are generated such that <code>getRandom</code> will only be called if there is <strong>at least one</strong> item in the <code>RandomizedCollection</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;RandomizedCollection&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;insert&quot;, &quot;getRandom&quot;, &quot;remove&quot;, &quot;getRandom&quot;] [[], [1], [1], [2], [], [1], []] <strong>Output</strong> [null, true, false, true, 2, true, 1] <strong>Explanation</strong> RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>-2<sup>31</sup> &lt;= val &lt;= 2<sup>31</sup> - 1</code></li> <li>At most <code>2 * 10<sup>5</sup></code> calls <strong>in total</strong> will be made to <code>insert</code>, <code>remove</code>, and <code>getRandom</code>.</li> <li>There will be <strong>at least one</strong> element in the data structure when <code>getRandom</code> is called.</li> </ul>
Design; Array; Hash Table; Math; Randomized
Python
class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.m = {} self.l = [] def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ idx_set = self.m.get(val, set()) idx_set.add(len(self.l)) self.m[val] = idx_set self.l.append(val) return len(idx_set) == 1 def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if val not in self.m: return False idx_set = self.m[val] idx = list(idx_set)[0] last_idx = len(self.l) - 1 self.l[idx] = self.l[last_idx] idx_set.remove(idx) last_idx_set = self.m[self.l[last_idx]] if last_idx in last_idx_set: last_idx_set.remove(last_idx) if idx < last_idx: last_idx_set.add(idx) if not idx_set: self.m.pop(val) self.l.pop() return True def getRandom(self) -> int: """ Get a random element from the collection. """ return -1 if len(self.l) == 0 else random.choice(self.l) # Your RandomizedCollection object will be instantiated and called as such: # obj = RandomizedCollection() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
382
Linked List Random Node
Medium
<p>Given a singly linked list, return a random node&#39;s value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(ListNode head)</code> Initializes the object with the head of the singly-linked list <code>head</code>.</li> <li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0382.Linked%20List%20Random%20Node/images/getrand-linked-list.jpg" style="width: 302px; height: 62px;" /> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 3, 2, 2, 3] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the linked list is extremely large and its length is unknown to you?</li> <li>Could you solve this efficiently without using extra space?</li> </ul>
Reservoir Sampling; Linked List; Math; Randomized
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* head; Solution(ListNode* head) { this->head = head; } int getRandom() { int n = 0, ans = 0; for (ListNode* node = head; node != nullptr; node = node->next) { n += 1; int x = 1 + rand() % n; if (n == x) ans = node->val; } return ans; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */
382
Linked List Random Node
Medium
<p>Given a singly linked list, return a random node&#39;s value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(ListNode head)</code> Initializes the object with the head of the singly-linked list <code>head</code>.</li> <li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0382.Linked%20List%20Random%20Node/images/getrand-linked-list.jpg" style="width: 302px; height: 62px;" /> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 3, 2, 2, 3] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the linked list is extremely large and its length is unknown to you?</li> <li>Could you solve this efficiently without using extra space?</li> </ul>
Reservoir Sampling; Linked List; Math; Randomized
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type Solution struct { head *ListNode } func Constructor(head *ListNode) Solution { return Solution{head} } func (this *Solution) GetRandom() int { n, ans := 0, 0 for node := this.head; node != nil; node = node.Next { n++ x := 1 + rand.Intn(n) if n == x { ans = node.Val } } return ans } /** * Your Solution object will be instantiated and called as such: * obj := Constructor(head); * param_1 := obj.GetRandom(); */
382
Linked List Random Node
Medium
<p>Given a singly linked list, return a random node&#39;s value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(ListNode head)</code> Initializes the object with the head of the singly-linked list <code>head</code>.</li> <li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0382.Linked%20List%20Random%20Node/images/getrand-linked-list.jpg" style="width: 302px; height: 62px;" /> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 3, 2, 2, 3] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the linked list is extremely large and its length is unknown to you?</li> <li>Could you solve this efficiently without using extra space?</li> </ul>
Reservoir Sampling; Linked List; Math; Randomized
Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { private ListNode head; private Random random = new Random(); public Solution(ListNode head) { this.head = head; } public int getRandom() { int ans = 0, n = 0; for (ListNode node = head; node != null; node = node.next) { ++n; int x = 1 + random.nextInt(n); if (n == x) { ans = node.val; } } return ans; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */
382
Linked List Random Node
Medium
<p>Given a singly linked list, return a random node&#39;s value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(ListNode head)</code> Initializes the object with the head of the singly-linked list <code>head</code>.</li> <li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0382.Linked%20List%20Random%20Node/images/getrand-linked-list.jpg" style="width: 302px; height: 62px;" /> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;, &quot;getRandom&quot;] [[[1, 2, 3]], [], [], [], [], []] <strong>Output</strong> [null, 1, 3, 2, 2, 3] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li> <li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li> </ul> <p>&nbsp;</p> <p><strong>Follow up:</strong></p> <ul> <li>What if the linked list is extremely large and its length is unknown to you?</li> <li>Could you solve this efficiently without using extra space?</li> </ul>
Reservoir Sampling; Linked List; Math; Randomized
Python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def __init__(self, head: Optional[ListNode]): self.head = head def getRandom(self) -> int: n = ans = 0 head = self.head while head: n += 1 x = random.randint(1, n) if n == x: ans = head.val head = head.next return ans # Your Solution object will be instantiated and called as such: # obj = Solution(head) # param_1 = obj.getRandom()
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
C++
class Solution { public: bool canConstruct(string ransomNote, string magazine) { int cnt[26]{}; for (char& c : magazine) { ++cnt[c - 'a']; } for (char& c : ransomNote) { if (--cnt[c - 'a'] < 0) { return false; } } return true; } };
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
C#
public class Solution { public bool CanConstruct(string ransomNote, string magazine) { int[] cnt = new int[26]; foreach (var c in magazine) { ++cnt[c - 'a']; } foreach (var c in ransomNote) { if (--cnt[c - 'a'] < 0) { return false; } } return true; } }
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
Go
func canConstruct(ransomNote string, magazine string) bool { cnt := [26]int{} for _, c := range magazine { cnt[c-'a']++ } for _, c := range ransomNote { cnt[c-'a']-- if cnt[c-'a'] < 0 { return false } } return true }
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
Java
class Solution { public boolean canConstruct(String ransomNote, String magazine) { int[] cnt = new int[26]; for (int i = 0; i < magazine.length(); ++i) { ++cnt[magazine.charAt(i) - 'a']; } for (int i = 0; i < ransomNote.length(); ++i) { if (--cnt[ransomNote.charAt(i) - 'a'] < 0) { return false; } } return true; } }
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
PHP
class Solution { /** * @param String $ransomNote * @param String $magazine * @return Boolean */ function canConstruct($ransomNote, $magazine) { $arrM = str_split($magazine); for ($i = 0; $i < strlen($magazine); $i++) { $hashtable[$arrM[$i]] += 1; } for ($j = 0; $j < strlen($ransomNote); $j++) { if (!isset($hashtable[$ransomNote[$j]]) || $hashtable[$ransomNote[$j]] == 0) { return false; } else { $hashtable[$ransomNote[$j]] -= 1; } } return true; } }
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
Python
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: cnt = Counter(magazine) for c in ransomNote: cnt[c] -= 1 if cnt[c] < 0: return False return True
383
Ransom Note
Easy
<p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p> <p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> ransomNote = "a", magazine = "b" <strong>Output:</strong> false </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab" <strong>Output:</strong> false </pre><p><strong class="example">Example 3:</strong></p> <pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab" <strong>Output:</strong> true </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li> <li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li> </ul>
Hash Table; String; Counting
TypeScript
function canConstruct(ransomNote: string, magazine: string): boolean { const cnt: number[] = Array(26).fill(0); for (const c of magazine) { ++cnt[c.charCodeAt(0) - 97]; } for (const c of ransomNote) { if (--cnt[c.charCodeAt(0) - 97] < 0) { return false; } } return true; }
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
C++
class Solution { public: vector<int> nums; vector<int> original; Solution(vector<int>& nums) { this->nums = nums; this->original.resize(nums.size()); copy(nums.begin(), nums.end(), original.begin()); } vector<int> reset() { copy(original.begin(), original.end(), nums.begin()); return nums; } vector<int> shuffle() { for (int i = 0; i < nums.size(); ++i) { int j = i + rand() % (nums.size() - i); swap(nums[i], nums[j]); } return nums; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * vector<int> param_1 = obj->reset(); * vector<int> param_2 = obj->shuffle(); */
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
Go
type Solution struct { nums, original []int } func Constructor(nums []int) Solution { return Solution{nums, append([]int(nil), nums...)} } func (this *Solution) Reset() []int { copy(this.nums, this.original) return this.nums } func (this *Solution) Shuffle() []int { n := len(this.nums) for i := range this.nums { j := i + rand.Intn(n-i) this.nums[i], this.nums[j] = this.nums[j], this.nums[i] } return this.nums } /** * Your Solution object will be instantiated and called as such: * obj := Constructor(nums); * param_1 := obj.Reset(); * param_2 := obj.Shuffle(); */
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
Java
class Solution { private int[] nums; private int[] original; private Random rand; public Solution(int[] nums) { this.nums = nums; this.original = Arrays.copyOf(nums, nums.length); this.rand = new Random(); } public int[] reset() { nums = Arrays.copyOf(original, original.length); return nums; } public int[] shuffle() { for (int i = 0; i < nums.length; ++i) { swap(i, i + rand.nextInt(nums.length - i)); } return nums; } private void swap(int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int[] param_1 = obj.reset(); * int[] param_2 = obj.shuffle(); */
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
JavaScript
/** * @param {number[]} nums */ const Solution = function (nums) { this.nums = nums || []; }; /** * Resets the array to its original configuration and return it. * @return {number[]} */ Solution.prototype.reset = function () { return this.nums; }; /** * Returns a random shuffling of the array. * @return {number[]} */ Solution.prototype.shuffle = function () { let a = this.nums.slice(); for (let i = 0; i < a.length; i++) { let rand = Math.floor(Math.random() * (a.length - i)) + i; let tmp = a[i]; a[i] = a[rand]; a[rand] = tmp; } return a; }; /** * Your Solution object will be instantiated and called as such: * var obj = Object.create(Solution).createNew(nums) * var param_1 = obj.reset() * var param_2 = obj.shuffle() */
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
Python
class Solution: def __init__(self, nums: List[int]): self.nums = nums self.original = nums.copy() def reset(self) -> List[int]: self.nums = self.original.copy() return self.nums def shuffle(self) -> List[int]: for i in range(len(self.nums)): j = random.randrange(i, len(self.nums)) self.nums[i], self.nums[j] = self.nums[j], self.nums[i] return self.nums # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
Rust
use rand::Rng; struct Solution { nums: Vec<i32>, } /** * `&self` means the method takes an immutable reference. * If you need a mutable reference, change it to `&mut self` instead. */ impl Solution { fn new(nums: Vec<i32>) -> Self { Self { nums } } fn reset(&self) -> Vec<i32> { self.nums.clone() } fn shuffle(&mut self) -> Vec<i32> { let n = self.nums.len(); let mut res = self.nums.clone(); for i in 0..n { let j = rand::thread_rng().gen_range(0, n); res.swap(i, j); } res } }
384
Shuffle an Array
Medium
<p>Given an integer array <code>nums</code>, design an algorithm to randomly shuffle the array. All permutations of the array should be <strong>equally likely</strong> as a result of the shuffling.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the integer array <code>nums</code>.</li> <li><code>int[] reset()</code> Resets the array to its original configuration and returns it.</li> <li><code>int[] shuffle()</code> Returns a random shuffling of the array.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;shuffle&quot;, &quot;reset&quot;, &quot;shuffle&quot;] [[[1, 2, 3]], [], [], []] <strong>Output</strong> [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3]); solution.shuffle(); // Shuffle the array [1,2,3] and return its result. // Any permutation of [1,2,3] must be equally likely to be returned. // Example: return [3, 1, 2] solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3] solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 50</code></li> <li><code>-10<sup>6</sup> &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li>All the elements of <code>nums</code> are <strong>unique</strong>.</li> <li>At most <code>10<sup>4</sup></code> calls <strong>in total</strong> will be made to <code>reset</code> and <code>shuffle</code>.</li> </ul>
Design; Array; Math; Randomized
TypeScript
class Solution { private nums: number[]; constructor(nums: number[]) { this.nums = nums; } reset(): number[] { return this.nums; } shuffle(): number[] { const n = this.nums.length; const res = [...this.nums]; for (let i = 0; i < n; i++) { const j = Math.floor(Math.random() * n); [res[i], res[j]] = [res[j], res[i]]; } return res; } } /** * Your Solution object will be instantiated and called as such: * var obj = new Solution(nums) * var param_1 = obj.reset() * var param_2 = obj.shuffle() */
385
Mini Parser
Medium
<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p> <p>Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;324&quot; <strong>Output:</strong> 324 <strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot; <strong>Output:</strong> [123,[456,[789]]] <strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li> <li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li> <li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Depth-First Search; String
C++
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * public: * // Constructor initializes an empty nested list. * NestedInteger(); * * // Constructor initializes a single integer. * NestedInteger(int value); * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * bool isInteger() const; * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * int getInteger() const; * * // Set this NestedInteger to hold a single integer. * void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * void add(const NestedInteger &ni); * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The result is undefined if this NestedInteger holds a single integer * const vector<NestedInteger> &getList() const; * }; */ class Solution { public: NestedInteger deserialize(string s) { if (s == "" || s == "[]") { return NestedInteger(); } if (s[0] != '[') { return NestedInteger(stoi(s)); } NestedInteger ans; int depth = 0; for (int i = 1, j = 1; i < s.size(); ++i) { if (depth == 0 && (s[i] == ',' || i == s.size() - 1)) { ans.add(deserialize(s.substr(j, i - j))); j = i + 1; } else if (s[i] == '[') { ++depth; } else if (s[i] == ']') { --depth; } } return ans; } };
385
Mini Parser
Medium
<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p> <p>Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;324&quot; <strong>Output:</strong> 324 <strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot; <strong>Output:</strong> [123,[456,[789]]] <strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li> <li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li> <li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Depth-First Search; String
Go
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * type NestedInteger struct { * } * * // Return true if this NestedInteger holds a single integer, rather than a nested list. * func (n NestedInteger) IsInteger() bool {} * * // Return the single integer that this NestedInteger holds, if it holds a single integer * // The result is undefined if this NestedInteger holds a nested list * // So before calling this method, you should have a check * func (n NestedInteger) GetInteger() int {} * * // Set this NestedInteger to hold a single integer. * func (n *NestedInteger) SetInteger(value int) {} * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * func (n *NestedInteger) Add(elem NestedInteger) {} * * // Return the nested list that this NestedInteger holds, if it holds a nested list * // The list length is zero if this NestedInteger holds a single integer * // You can access NestedInteger's List element directly if you want to modify it * func (n NestedInteger) GetList() []*NestedInteger {} */ func deserialize(s string) *NestedInteger { ans := &NestedInteger{} if s == "" || s == "[]" { return ans } if s[0] != '[' { v, _ := strconv.Atoi(s) ans.SetInteger(v) return ans } depth := 0 for i, j := 1, 1; i < len(s); i++ { if depth == 0 && (s[i] == ',' || i == len(s)-1) { (*ans).Add(*deserialize(s[j:i])) j = i + 1 } else if s[i] == '[' { depth++ } else if s[i] == ']' { depth-- } } return ans }
385
Mini Parser
Medium
<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p> <p>Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;324&quot; <strong>Output:</strong> 324 <strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot; <strong>Output:</strong> [123,[456,[789]]] <strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li> <li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li> <li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Depth-First Search; String
Java
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * public interface NestedInteger { * // Constructor initializes an empty nested list. * public NestedInteger(); * * // Constructor initializes a single integer. * public NestedInteger(int value); * * // @return true if this NestedInteger holds a single integer, rather than a nested list. * public boolean isInteger(); * * // @return the single integer that this NestedInteger holds, if it holds a single integer * // Return null if this NestedInteger holds a nested list * public Integer getInteger(); * * // Set this NestedInteger to hold a single integer. * public void setInteger(int value); * * // Set this NestedInteger to hold a nested list and adds a nested integer to it. * public void add(NestedInteger ni); * * // @return the nested list that this NestedInteger holds, if it holds a nested list * // Return empty list if this NestedInteger holds a single integer * public List<NestedInteger> getList(); * } */ class Solution { public NestedInteger deserialize(String s) { if ("".equals(s) || "[]".equals(s)) { return new NestedInteger(); } if (s.charAt(0) != '[') { return new NestedInteger(Integer.parseInt(s)); } NestedInteger ans = new NestedInteger(); int depth = 0; for (int i = 1, j = 1; i < s.length(); ++i) { if (depth == 0 && (s.charAt(i) == ',' || i == s.length() - 1)) { ans.add(deserialize(s.substring(j, i))); j = i + 1; } else if (s.charAt(i) == '[') { ++depth; } else if (s.charAt(i) == ']') { --depth; } } return ans; } }
385
Mini Parser
Medium
<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p> <p>Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;324&quot; <strong>Output:</strong> 324 <strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot; <strong>Output:</strong> [123,[456,[789]]] <strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li> <li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li> <li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Depth-First Search; String
Python
# """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ # class NestedInteger: # def __init__(self, value=None): # """ # If value is not specified, initializes an empty list. # Otherwise initializes a single integer equal to value. # """ # # def isInteger(self): # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # :rtype bool # """ # # def add(self, elem): # """ # Set this NestedInteger to hold a nested list and adds a nested integer elem to it. # :rtype void # """ # # def setInteger(self, value): # """ # Set this NestedInteger to hold a single integer equal to value. # :rtype void # """ # # def getInteger(self): # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # :rtype int # """ # # def getList(self): # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # :rtype List[NestedInteger] # """ class Solution: def deserialize(self, s: str) -> NestedInteger: if not s or s == '[]': return NestedInteger() if s[0] != '[': return NestedInteger(int(s)) ans = NestedInteger() depth, j = 0, 1 for i in range(1, len(s)): if depth == 0 and (s[i] == ',' or i == len(s) - 1): ans.add(self.deserialize(s[j:i])) j = i + 1 elif s[i] == '[': depth += 1 elif s[i] == ']': depth -= 1 return ans
385
Mini Parser
Medium
<p>Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return <em>the deserialized</em> <code>NestedInteger</code>.</p> <p>Each element is either an integer or a list whose elements may also be integers or other lists.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;324&quot; <strong>Output:</strong> 324 <strong>Explanation:</strong> You should return a NestedInteger object which contains a single integer 324. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;[123,[456,[789]]]&quot; <strong>Output:</strong> [123,[456,[789]]] <strong>Explanation:</strong> Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li> <li><code>s</code> consists of digits, square brackets <code>&quot;[]&quot;</code>, negative sign <code>&#39;-&#39;</code>, and commas <code>&#39;,&#39;</code>.</li> <li><code>s</code> is the serialization of valid <code>NestedInteger</code>.</li> <li>All the values in the input are in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li> </ul>
Stack; Depth-First Search; String
TypeScript
/** * // This is the interface that allows for creating nested lists. * // You should not implement it, or speculate about its implementation * class NestedInteger { * If value is provided, then it holds a single integer * Otherwise it holds an empty nested list * constructor(value?: number) { * ... * }; * * Return true if this NestedInteger holds a single integer, rather than a nested list. * isInteger(): boolean { * ... * }; * * Return the single integer that this NestedInteger holds, if it holds a single integer * Return null if this NestedInteger holds a nested list * getInteger(): number | null { * ... * }; * * Set this NestedInteger to hold a single integer equal to value. * setInteger(value: number) { * ... * }; * * Set this NestedInteger to hold a nested list and adds a nested integer elem to it. * add(elem: NestedInteger) { * ... * }; * * Return the nested list that this NestedInteger holds, * or an empty list if this NestedInteger holds a single integer * getList(): NestedInteger[] { * ... * }; * }; */ function deserialize(s: string): NestedInteger { if (s === '' || s === '[]') { return new NestedInteger(); } if (s[0] !== '[') { return new NestedInteger(+s); } const ans: NestedInteger = new NestedInteger(); let depth = 0; for (let i = 1, j = 1; i < s.length; ++i) { if (depth === 0 && (s[i] === ',' || i === s.length - 1)) { ans.add(deserialize(s.slice(j, i))); j = i + 1; } else if (s[i] === '[') { ++depth; } else if (s[i] === ']') { --depth; } } return ans; }
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
C++
class Solution { public: vector<int> lexicalOrder(int n) { vector<int> ans; int v = 1; for (int i = 0; i < n; ++i) { ans.push_back(v); if (v * 10 <= n) { v *= 10; } else { while (v % 10 == 9 || v + 1 > n) { v /= 10; } ++v; } } return ans; } };
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
Go
func lexicalOrder(n int) (ans []int) { v := 1 for i := 0; i < n; i++ { ans = append(ans, v) if v*10 <= n { v *= 10 } else { for v%10 == 9 || v+1 > n { v /= 10 } v++ } } return }
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
Java
class Solution { public List<Integer> lexicalOrder(int n) { List<Integer> ans = new ArrayList<>(n); int v = 1; for (int i = 0; i < n; ++i) { ans.add(v); if (v * 10 <= n) { v *= 10; } else { while (v % 10 == 9 || v + 1 > n) { v /= 10; } ++v; } } return ans; } }
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
JavaScript
/** * @param {number} n * @return {number[]} */ var lexicalOrder = function (n) { const ans = []; let v = 1; for (let i = 0; i < n; ++i) { ans.push(v); if (v * 10 <= n) { v *= 10; } else { while (v % 10 === 9 || v === n) { v = Math.floor(v / 10); } ++v; } } return ans; };
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
Python
class Solution: def lexicalOrder(self, n: int) -> List[int]: ans = [] v = 1 for _ in range(n): ans.append(v) if v * 10 <= n: v *= 10 else: while v % 10 == 9 or v + 1 > n: v //= 10 v += 1 return ans
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
Rust
impl Solution { pub fn lexical_order(n: i32) -> Vec<i32> { let mut ans = Vec::with_capacity(n as usize); let mut v = 1; for _ in 0..n { ans.push(v); if v * 10 <= n { v *= 10; } else { while v % 10 == 9 || v + 1 > n { v /= 10; } v += 1; } } ans } }
386
Lexicographical Numbers
Medium
<p>Given an integer <code>n</code>, return all the numbers in the range <code>[1, n]</code> sorted in lexicographical order.</p> <p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and uses <code>O(1)</code> extra space.&nbsp;</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> n = 13 <strong>Output:</strong> [1,10,11,12,13,2,3,4,5,6,7,8,9] </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> n = 2 <strong>Output:</strong> [1,2] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li> </ul>
Depth-First Search; Trie
TypeScript
function lexicalOrder(n: number): number[] { const ans: number[] = []; let v = 1; for (let i = 0; i < n; ++i) { ans.push(v); if (v * 10 <= n) { v *= 10; } else { while (v % 10 === 9 || v === n) { v = Math.floor(v / 10); } ++v; } } return ans; }
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
C++
class Solution { public: int firstUniqChar(string s) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } int n = s.size(); for (int i = 0; i < n; ++i) { if (cnt[s[i] - 'a'] == 1) { return i; } } return -1; } };
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
Go
func firstUniqChar(s string) int { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } for i, c := range s { if cnt[c-'a'] == 1 { return i } } return -1 }
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
Java
class Solution { public int firstUniqChar(String s) { int[] cnt = new int[26]; int n = s.length(); for (int i = 0; i < n; ++i) { ++cnt[s.charAt(i) - 'a']; } for (int i = 0; i < n; ++i) { if (cnt[s.charAt(i) - 'a'] == 1) { return i; } } return -1; } }
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
JavaScript
/** * @param {string} s * @return {number} */ var firstUniqChar = function (s) { const cnt = new Map(); for (const c of s) { cnt.set(c, (cnt.get(c) || 0) + 1); } for (let i = 0; i < s.length; ++i) { if (cnt.get(s[i]) === 1) { return i; } } return -1; };
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
PHP
class Solution { /** * @param String $s * @return Integer */ function firstUniqChar($s) { for ($i = 0; $i < strlen($s); $i++) { $hashtable[$s[$i]]++; } for ($i = 0; $i < strlen($s); $i++) { if ($hashtable[$s[$i]] == 1) { return $i; } } return -1; } }
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
Python
class Solution: def firstUniqChar(self, s: str) -> int: cnt = Counter(s) for i, c in enumerate(s): if cnt[c] == 1: return i return -1
387
First Unique Character in a String
Easy
<p>Given a string <code>s</code>, find the <strong>first</strong> non-repeating character in it and return its index. If it <strong>does not</strong> exist, return <code>-1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;leetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The character <code>&#39;l&#39;</code> at index 0 is the first character that does not occur at any other index.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;loveleetcode&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;aabb&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">-1</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> </ul>
Queue; Hash Table; String; Counting
TypeScript
function firstUniqChar(s: string): number { const cnt = new Map<string, number>(); for (const c of s) { cnt.set(c, (cnt.get(c) || 0) + 1); } for (let i = 0; i < s.length; ++i) { if (cnt.get(s[i]) === 1) { return i; } } return -1; }
388
Longest Absolute File Path
Medium
<p>Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/mdir.jpg" style="width: 681px; height: 322px;" /></p> <p>Here, we have <code>dir</code> as the only directory in the root. <code>dir</code> contains two subdirectories, <code>subdir1</code> and <code>subdir2</code>. <code>subdir1</code> contains a file <code>file1.ext</code> and subdirectory <code>subsubdir1</code>. <code>subdir2</code> contains a subdirectory <code>subsubdir2</code>, which contains a file <code>file2.ext</code>.</p> <p>In text form, it looks like this (with ⟶ representing the tab character):</p> <pre> dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext </pre> <p>If we were to write this representation in code, it will look like this: <code>&quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot;</code>. Note that the <code>&#39;\n&#39;</code> and <code>&#39;\t&#39;</code> are the new-line and tab characters.</p> <p>Every file and directory has a unique <strong>absolute path</strong> in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by <code>&#39;/&#39;s</code>. Using the above example, the <strong>absolute path</strong> to <code>file2.ext</code> is <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form <code>name.extension</code>, where <code>name</code> and <code>extension</code> consist of letters, digits, and/or spaces.</p> <p>Given a string <code>input</code> representing the file system in the explained format, return <em>the length of the <strong>longest absolute path</strong> to a <strong>file</strong> in the abstracted file system</em>. If there is no file in the system, return <code>0</code>.</p> <p><strong>Note</strong> that the testcases are generated such that the file system is valid and no file or directory name has length 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir1.jpg" style="width: 401px; height: 202px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext&quot; <strong>Output:</strong> 20 <strong>Explanation:</strong> We have only one file, and the absolute path is &quot;dir/subdir2/file.ext&quot; of length 20. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir2.jpg" style="width: 641px; height: 322px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot; <strong>Output:</strong> 32 <strong>Explanation:</strong> We have two files: &quot;dir/subdir1/file1.ext&quot; of length 21 &quot;dir/subdir2/subsubdir2/file2.ext&quot; of length 32. We return 32 since it is the longest absolute path to a file. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> input = &quot;a&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> We do not have any files, just a single directory named &quot;a&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li> <li><code>input</code> may contain lowercase or uppercase English letters, a new line character <code>&#39;\n&#39;</code>, a tab character <code>&#39;\t&#39;</code>, a dot <code>&#39;.&#39;</code>, a space <code>&#39; &#39;</code>, and digits.</li> <li>All file and directory names have <strong>positive</strong> length.</li> </ul>
Stack; Depth-First Search; String
C++
class Solution { public: int lengthLongestPath(string input) { int i = 0, n = input.size(); int ans = 0; stack<int> stk; while (i < n) { int ident = 0; for (; input[i] == '\t'; ++i) { ++ident; } int cur = 0; bool isFile = false; for (; i < n && input[i] != '\n'; ++i) { ++cur; if (input[i] == '.') { isFile = true; } } ++i; // popd while (!stk.empty() && stk.size() > ident) { stk.pop(); } if (stk.size() > 0) { cur += stk.top() + 1; } // pushd if (!isFile) { stk.push(cur); continue; } ans = max(ans, cur); } return ans; } };
388
Longest Absolute File Path
Medium
<p>Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/mdir.jpg" style="width: 681px; height: 322px;" /></p> <p>Here, we have <code>dir</code> as the only directory in the root. <code>dir</code> contains two subdirectories, <code>subdir1</code> and <code>subdir2</code>. <code>subdir1</code> contains a file <code>file1.ext</code> and subdirectory <code>subsubdir1</code>. <code>subdir2</code> contains a subdirectory <code>subsubdir2</code>, which contains a file <code>file2.ext</code>.</p> <p>In text form, it looks like this (with ⟶ representing the tab character):</p> <pre> dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext </pre> <p>If we were to write this representation in code, it will look like this: <code>&quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot;</code>. Note that the <code>&#39;\n&#39;</code> and <code>&#39;\t&#39;</code> are the new-line and tab characters.</p> <p>Every file and directory has a unique <strong>absolute path</strong> in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by <code>&#39;/&#39;s</code>. Using the above example, the <strong>absolute path</strong> to <code>file2.ext</code> is <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form <code>name.extension</code>, where <code>name</code> and <code>extension</code> consist of letters, digits, and/or spaces.</p> <p>Given a string <code>input</code> representing the file system in the explained format, return <em>the length of the <strong>longest absolute path</strong> to a <strong>file</strong> in the abstracted file system</em>. If there is no file in the system, return <code>0</code>.</p> <p><strong>Note</strong> that the testcases are generated such that the file system is valid and no file or directory name has length 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir1.jpg" style="width: 401px; height: 202px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext&quot; <strong>Output:</strong> 20 <strong>Explanation:</strong> We have only one file, and the absolute path is &quot;dir/subdir2/file.ext&quot; of length 20. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir2.jpg" style="width: 641px; height: 322px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot; <strong>Output:</strong> 32 <strong>Explanation:</strong> We have two files: &quot;dir/subdir1/file1.ext&quot; of length 21 &quot;dir/subdir2/subsubdir2/file2.ext&quot; of length 32. We return 32 since it is the longest absolute path to a file. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> input = &quot;a&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> We do not have any files, just a single directory named &quot;a&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li> <li><code>input</code> may contain lowercase or uppercase English letters, a new line character <code>&#39;\n&#39;</code>, a tab character <code>&#39;\t&#39;</code>, a dot <code>&#39;.&#39;</code>, a space <code>&#39; &#39;</code>, and digits.</li> <li>All file and directory names have <strong>positive</strong> length.</li> </ul>
Stack; Depth-First Search; String
Go
func lengthLongestPath(input string) int { i, n := 0, len(input) ans := 0 var stk []int for i < n { ident := 0 for ; input[i] == '\t'; i++ { ident++ } cur, isFile := 0, false for ; i < n && input[i] != '\n'; i++ { cur++ if input[i] == '.' { isFile = true } } i++ // popd for len(stk) > 0 && len(stk) > ident { stk = stk[:len(stk)-1] } if len(stk) > 0 { cur += stk[len(stk)-1] + 1 } // pushd if !isFile { stk = append(stk, cur) continue } ans = max(ans, cur) } return ans }
388
Longest Absolute File Path
Medium
<p>Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/mdir.jpg" style="width: 681px; height: 322px;" /></p> <p>Here, we have <code>dir</code> as the only directory in the root. <code>dir</code> contains two subdirectories, <code>subdir1</code> and <code>subdir2</code>. <code>subdir1</code> contains a file <code>file1.ext</code> and subdirectory <code>subsubdir1</code>. <code>subdir2</code> contains a subdirectory <code>subsubdir2</code>, which contains a file <code>file2.ext</code>.</p> <p>In text form, it looks like this (with ⟶ representing the tab character):</p> <pre> dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext </pre> <p>If we were to write this representation in code, it will look like this: <code>&quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot;</code>. Note that the <code>&#39;\n&#39;</code> and <code>&#39;\t&#39;</code> are the new-line and tab characters.</p> <p>Every file and directory has a unique <strong>absolute path</strong> in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by <code>&#39;/&#39;s</code>. Using the above example, the <strong>absolute path</strong> to <code>file2.ext</code> is <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form <code>name.extension</code>, where <code>name</code> and <code>extension</code> consist of letters, digits, and/or spaces.</p> <p>Given a string <code>input</code> representing the file system in the explained format, return <em>the length of the <strong>longest absolute path</strong> to a <strong>file</strong> in the abstracted file system</em>. If there is no file in the system, return <code>0</code>.</p> <p><strong>Note</strong> that the testcases are generated such that the file system is valid and no file or directory name has length 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir1.jpg" style="width: 401px; height: 202px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext&quot; <strong>Output:</strong> 20 <strong>Explanation:</strong> We have only one file, and the absolute path is &quot;dir/subdir2/file.ext&quot; of length 20. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir2.jpg" style="width: 641px; height: 322px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot; <strong>Output:</strong> 32 <strong>Explanation:</strong> We have two files: &quot;dir/subdir1/file1.ext&quot; of length 21 &quot;dir/subdir2/subsubdir2/file2.ext&quot; of length 32. We return 32 since it is the longest absolute path to a file. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> input = &quot;a&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> We do not have any files, just a single directory named &quot;a&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li> <li><code>input</code> may contain lowercase or uppercase English letters, a new line character <code>&#39;\n&#39;</code>, a tab character <code>&#39;\t&#39;</code>, a dot <code>&#39;.&#39;</code>, a space <code>&#39; &#39;</code>, and digits.</li> <li>All file and directory names have <strong>positive</strong> length.</li> </ul>
Stack; Depth-First Search; String
Java
class Solution { public int lengthLongestPath(String input) { int i = 0; int n = input.length(); int ans = 0; Deque<Integer> stack = new ArrayDeque<>(); while (i < n) { int ident = 0; for (; input.charAt(i) == '\t'; i++) { ident++; } int cur = 0; boolean isFile = false; for (; i < n && input.charAt(i) != '\n'; i++) { cur++; if (input.charAt(i) == '.') { isFile = true; } } i++; // popd while (!stack.isEmpty() && stack.size() > ident) { stack.pop(); } if (stack.size() > 0) { cur += stack.peek() + 1; } // pushd if (!isFile) { stack.push(cur); continue; } ans = Math.max(ans, cur); } return ans; } }
388
Longest Absolute File Path
Medium
<p>Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/mdir.jpg" style="width: 681px; height: 322px;" /></p> <p>Here, we have <code>dir</code> as the only directory in the root. <code>dir</code> contains two subdirectories, <code>subdir1</code> and <code>subdir2</code>. <code>subdir1</code> contains a file <code>file1.ext</code> and subdirectory <code>subsubdir1</code>. <code>subdir2</code> contains a subdirectory <code>subsubdir2</code>, which contains a file <code>file2.ext</code>.</p> <p>In text form, it looks like this (with ⟶ representing the tab character):</p> <pre> dir ⟶ subdir1 ⟶ ⟶ file1.ext ⟶ ⟶ subsubdir1 ⟶ subdir2 ⟶ ⟶ subsubdir2 ⟶ ⟶ ⟶ file2.ext </pre> <p>If we were to write this representation in code, it will look like this: <code>&quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot;</code>. Note that the <code>&#39;\n&#39;</code> and <code>&#39;\t&#39;</code> are the new-line and tab characters.</p> <p>Every file and directory has a unique <strong>absolute path</strong> in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by <code>&#39;/&#39;s</code>. Using the above example, the <strong>absolute path</strong> to <code>file2.ext</code> is <code>&quot;dir/subdir2/subsubdir2/file2.ext&quot;</code>. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form <code>name.extension</code>, where <code>name</code> and <code>extension</code> consist of letters, digits, and/or spaces.</p> <p>Given a string <code>input</code> representing the file system in the explained format, return <em>the length of the <strong>longest absolute path</strong> to a <strong>file</strong> in the abstracted file system</em>. If there is no file in the system, return <code>0</code>.</p> <p><strong>Note</strong> that the testcases are generated such that the file system is valid and no file or directory name has length 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir1.jpg" style="width: 401px; height: 202px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext&quot; <strong>Output:</strong> 20 <strong>Explanation:</strong> We have only one file, and the absolute path is &quot;dir/subdir2/file.ext&quot; of length 20. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0388.Longest%20Absolute%20File%20Path/images/dir2.jpg" style="width: 641px; height: 322px;" /> <pre> <strong>Input:</strong> input = &quot;dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext&quot; <strong>Output:</strong> 32 <strong>Explanation:</strong> We have two files: &quot;dir/subdir1/file1.ext&quot; of length 21 &quot;dir/subdir2/subsubdir2/file2.ext&quot; of length 32. We return 32 since it is the longest absolute path to a file. </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> input = &quot;a&quot; <strong>Output:</strong> 0 <strong>Explanation:</strong> We do not have any files, just a single directory named &quot;a&quot;. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= input.length &lt;= 10<sup>4</sup></code></li> <li><code>input</code> may contain lowercase or uppercase English letters, a new line character <code>&#39;\n&#39;</code>, a tab character <code>&#39;\t&#39;</code>, a dot <code>&#39;.&#39;</code>, a space <code>&#39; &#39;</code>, and digits.</li> <li>All file and directory names have <strong>positive</strong> length.</li> </ul>
Stack; Depth-First Search; String
Python
class Solution: def lengthLongestPath(self, input: str) -> int: i, n = 0, len(input) ans = 0 stk = [] while i < n: ident = 0 while input[i] == '\t': ident += 1 i += 1 cur, isFile = 0, False while i < n and input[i] != '\n': cur += 1 if input[i] == '.': isFile = True i += 1 i += 1 # popd while len(stk) > 0 and len(stk) > ident: stk.pop() if len(stk) > 0: cur += stk[-1] + 1 # pushd if not isFile: stk.append(cur) continue ans = max(ans, cur) return ans
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
C
char findTheDifference(char* s, char* t) { int n = strlen(s); int cnt[26] = {0}; for (int i = 0; i < n; i++) { cnt[s[i] - 'a']++; cnt[t[i] - 'a']--; } cnt[t[n] - 'a']--; for (int i = 0;; i++) { if (cnt[i]) { return 'a' + i; } } }
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
C++
class Solution { public: char findTheDifference(string s, string t) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } for (char& c : t) { if (--cnt[c - 'a'] < 0) { return c; } } return ' '; } };
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
Go
func findTheDifference(s, t string) byte { cnt := [26]int{} for _, ch := range s { cnt[ch-'a']++ } for i := 0; ; i++ { ch := t[i] cnt[ch-'a']-- if cnt[ch-'a'] < 0 { return ch } } }
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
Java
class Solution { public char findTheDifference(String s, String t) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } for (int i = 0;; ++i) { if (--cnt[t.charAt(i) - 'a'] < 0) { return t.charAt(i); } } } }
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
Python
class Solution: def findTheDifference(self, s: str, t: str) -> str: cnt = Counter(s) for c in t: cnt[c] -= 1 if cnt[c] < 0: return c
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
Rust
impl Solution { pub fn find_the_difference(s: String, t: String) -> char { let s = s.as_bytes(); let t = t.as_bytes(); let n = s.len(); let mut count = [0; 26]; for i in 0..n { count[(s[i] - b'a') as usize] += 1; count[(t[i] - b'a') as usize] -= 1; } count[(t[n] - b'a') as usize] -= 1; char::from(b'a' + (count.iter().position(|&v| v != 0).unwrap() as u8)) } }
389
Find the Difference
Easy
<p>You are given two strings <code>s</code> and <code>t</code>.</p> <p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p> <p>Return the letter that was added to <code>t</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;abcd&quot;, t = &quot;abcde&quot; <strong>Output:</strong> &quot;e&quot; <strong>Explanation:</strong> &#39;e&#39; is the letter that was added. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;&quot;, t = &quot;y&quot; <strong>Output:</strong> &quot;y&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 1000</code></li> <li><code>t.length == s.length + 1</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Bit Manipulation; Hash Table; String; Sorting
TypeScript
function findTheDifference(s: string, t: string): string { const cnt: number[] = Array(26).fill(0); for (const c of s) { ++cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } for (const c of t) { --cnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]; } for (let i = 0; ; ++i) { if (cnt[i] < 0) { return String.fromCharCode(i + 'a'.charCodeAt(0)); } } }
390
Elimination Game
Medium
<p>You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>:</p> <ul> <li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li> <li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li> <li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li> </ul> <p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 6 <strong>Explanation:</strong> arr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>] arr = [2, <u>4</u>, 6, <u>8</u>] arr = [<u>2</u>, 6] arr = [6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
C++
class Solution { public: int lastRemaining(int n) { int a1 = 1, an = n, step = 1; for (int i = 0, cnt = n; cnt > 1; cnt >>= 1, step <<= 1, ++i) { if (i % 2) { an -= step; if (cnt % 2) a1 += step; } else { a1 += step; if (cnt % 2) an -= step; } } return a1; } };
390
Elimination Game
Medium
<p>You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>:</p> <ul> <li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li> <li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li> <li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li> </ul> <p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 6 <strong>Explanation:</strong> arr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>] arr = [2, <u>4</u>, 6, <u>8</u>] arr = [<u>2</u>, 6] arr = [6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Go
func lastRemaining(n int) int { a1, an, step := 1, n, 1 for i, cnt := 0, n; cnt > 1; cnt, step, i = cnt>>1, step<<1, i+1 { if i%2 == 1 { an -= step if cnt%2 == 1 { a1 += step } } else { a1 += step if cnt%2 == 1 { an -= step } } } return a1 }
390
Elimination Game
Medium
<p>You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>:</p> <ul> <li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li> <li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li> <li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li> </ul> <p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 6 <strong>Explanation:</strong> arr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>] arr = [2, <u>4</u>, 6, <u>8</u>] arr = [<u>2</u>, 6] arr = [6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Java
class Solution { public int lastRemaining(int n) { int a1 = 1, an = n, step = 1; for (int i = 0, cnt = n; cnt > 1; cnt >>= 1, step <<= 1, ++i) { if (i % 2 == 1) { an -= step; if (cnt % 2 == 1) { a1 += step; } } else { a1 += step; if (cnt % 2 == 1) { an -= step; } } } return a1; } }
390
Elimination Game
Medium
<p>You have a list <code>arr</code> of all integers in the range <code>[1, n]</code> sorted in a strictly increasing order. Apply the following algorithm on <code>arr</code>:</p> <ul> <li>Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.</li> <li>Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.</li> <li>Keep repeating the steps again, alternating left to right and right to left, until a single number remains.</li> </ul> <p>Given the integer <code>n</code>, return <em>the last number that remains in</em> <code>arr</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 9 <strong>Output:</strong> 6 <strong>Explanation:</strong> arr = [<u>1</u>, 2, <u>3</u>, 4, <u>5</u>, 6, <u>7</u>, 8, <u>9</u>] arr = [2, <u>4</u>, 6, <u>8</u>] arr = [<u>2</u>, 6] arr = [6] </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 1 <strong>Output:</strong> 1 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 10<sup>9</sup></code></li> </ul>
Recursion; Math
Python
class Solution: def lastRemaining(self, n: int) -> int: a1, an = 1, n i, step, cnt = 0, 1, n while cnt > 1: if i % 2: an -= step if cnt % 2: a1 += step else: a1 += step if cnt % 2: an -= step cnt >>= 1 step <<= 1 i += 1 return a1
391
Perfect Rectangle
Hard
<p>Given an array <code>rectangles</code> where <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> represents an axis-aligned rectangle. The bottom-left point of the rectangle is <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and the top-right point of it is <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p> <p>Return <code>true</code> <em>if all the rectangles together form an exact cover of a rectangular region</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perectrec1-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] <strong>Output:</strong> true <strong>Explanation:</strong> All 5 rectangles together form an exact cover of a rectangular region. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfectrec2-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because there is a gap between the two rectangular regions. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfecrrec4-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because two of the rectangles overlap with each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>rectangles[i].length == 4</code></li> <li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Hash Table; Math; Line Sweep
C++
#include <bits/stdc++.h> using namespace std; class Solution { public: bool isRectangleCover(vector<vector<int>>& rectangles) { long long area = 0; int minX = rectangles[0][0], minY = rectangles[0][1]; int maxX = rectangles[0][2], maxY = rectangles[0][3]; using pii = pair<int, int>; map<pii, int> cnt; for (auto& r : rectangles) { area += (r[2] - r[0]) * (r[3] - r[1]); minX = min(minX, r[0]); minY = min(minY, r[1]); maxX = max(maxX, r[2]); maxY = max(maxY, r[3]); ++cnt[{r[0], r[1]}]; ++cnt[{r[0], r[3]}]; ++cnt[{r[2], r[3]}]; ++cnt[{r[2], r[1]}]; } if (area != (long long) (maxX - minX) * (maxY - minY) || cnt[{minX, minY}] != 1 || cnt[{minX, maxY}] != 1 || cnt[{maxX, maxY}] != 1 || cnt[{maxX, minY}] != 1) { return false; } cnt.erase({minX, minY}); cnt.erase({minX, maxY}); cnt.erase({maxX, maxY}); cnt.erase({maxX, minY}); return all_of(cnt.begin(), cnt.end(), [](pair<pii, int> e) { return e.second == 2 || e.second == 4; }); } };
391
Perfect Rectangle
Hard
<p>Given an array <code>rectangles</code> where <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> represents an axis-aligned rectangle. The bottom-left point of the rectangle is <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and the top-right point of it is <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p> <p>Return <code>true</code> <em>if all the rectangles together form an exact cover of a rectangular region</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perectrec1-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] <strong>Output:</strong> true <strong>Explanation:</strong> All 5 rectangles together form an exact cover of a rectangular region. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfectrec2-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because there is a gap between the two rectangular regions. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfecrrec4-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because two of the rectangles overlap with each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>rectangles[i].length == 4</code></li> <li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Hash Table; Math; Line Sweep
Go
type pair struct { first int second int } func isRectangleCover(rectangles [][]int) bool { area := 0 minX, minY := rectangles[0][0], rectangles[0][1] maxX, maxY := rectangles[0][2], rectangles[0][3] cnt := make(map[pair]int) for _, r := range rectangles { area += (r[2] - r[0]) * (r[3] - r[1]) minX = min(minX, r[0]) minY = min(minY, r[1]) maxX = max(maxX, r[2]) maxY = max(maxY, r[3]) cnt[pair{r[0], r[1]}]++ cnt[pair{r[0], r[3]}]++ cnt[pair{r[2], r[3]}]++ cnt[pair{r[2], r[1]}]++ } if area != (maxX-minX)*(maxY-minY) || cnt[pair{minX, minY}] != 1 || cnt[pair{minX, maxY}] != 1 || cnt[pair{maxX, maxY}] != 1 || cnt[pair{maxX, minY}] != 1 { return false } delete(cnt, pair{minX, minY}) delete(cnt, pair{minX, maxY}) delete(cnt, pair{maxX, maxY}) delete(cnt, pair{maxX, minY}) for _, c := range cnt { if c != 2 && c != 4 { return false } } return true }
391
Perfect Rectangle
Hard
<p>Given an array <code>rectangles</code> where <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> represents an axis-aligned rectangle. The bottom-left point of the rectangle is <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and the top-right point of it is <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p> <p>Return <code>true</code> <em>if all the rectangles together form an exact cover of a rectangular region</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perectrec1-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] <strong>Output:</strong> true <strong>Explanation:</strong> All 5 rectangles together form an exact cover of a rectangular region. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfectrec2-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because there is a gap between the two rectangular regions. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfecrrec4-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because two of the rectangles overlap with each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>rectangles[i].length == 4</code></li> <li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Hash Table; Math; Line Sweep
Java
class Solution { public boolean isRectangleCover(int[][] rectangles) { long area = 0; int minX = rectangles[0][0], minY = rectangles[0][1]; int maxX = rectangles[0][2], maxY = rectangles[0][3]; Map<Pair, Integer> cnt = new HashMap<>(); for (int[] r : rectangles) { area += (r[2] - r[0]) * (r[3] - r[1]); minX = Math.min(minX, r[0]); minY = Math.min(minY, r[1]); maxX = Math.max(maxX, r[2]); maxY = Math.max(maxY, r[3]); cnt.merge(new Pair(r[0], r[1]), 1, Integer::sum); cnt.merge(new Pair(r[0], r[3]), 1, Integer::sum); cnt.merge(new Pair(r[2], r[3]), 1, Integer::sum); cnt.merge(new Pair(r[2], r[1]), 1, Integer::sum); } if (area != (long) (maxX - minX) * (maxY - minY) || cnt.getOrDefault(new Pair(minX, minY), 0) != 1 || cnt.getOrDefault(new Pair(minX, maxY), 0) != 1 || cnt.getOrDefault(new Pair(maxX, maxY), 0) != 1 || cnt.getOrDefault(new Pair(maxX, minY), 0) != 1) { return false; } cnt.remove(new Pair(minX, minY)); cnt.remove(new Pair(minX, maxY)); cnt.remove(new Pair(maxX, maxY)); cnt.remove(new Pair(maxX, minY)); return cnt.values().stream().allMatch(c -> c == 2 || c == 4); } private static class Pair { final int first; final int second; Pair(int first, int second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair pair = (Pair) o; return first == pair.first && second == pair.second; } @Override public int hashCode() { return Objects.hash(first, second); } } }
391
Perfect Rectangle
Hard
<p>Given an array <code>rectangles</code> where <code>rectangles[i] = [x<sub>i</sub>, y<sub>i</sub>, a<sub>i</sub>, b<sub>i</sub>]</code> represents an axis-aligned rectangle. The bottom-left point of the rectangle is <code>(x<sub>i</sub>, y<sub>i</sub>)</code> and the top-right point of it is <code>(a<sub>i</sub>, b<sub>i</sub>)</code>.</p> <p>Return <code>true</code> <em>if all the rectangles together form an exact cover of a rectangular region</em>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perectrec1-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]] <strong>Output:</strong> true <strong>Explanation:</strong> All 5 rectangles together form an exact cover of a rectangular region. </pre> <p><strong class="example">Example 2:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfectrec2-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because there is a gap between the two rectangular regions. </pre> <p><strong class="example">Example 3:</strong></p> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0300-0399/0391.Perfect%20Rectangle/images/perfecrrec4-plane.jpg" style="width: 300px; height: 294px;" /> <pre> <strong>Input:</strong> rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]] <strong>Output:</strong> false <strong>Explanation:</strong> Because two of the rectangles overlap with each other. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rectangles.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>rectangles[i].length == 4</code></li> <li><code>-10<sup>5</sup> &lt;= x<sub>i</sub> &lt; a<sub>i</sub> &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>5</sup> &lt;= y<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>5</sup></code></li> </ul>
Geometry; Array; Hash Table; Math; Line Sweep
Python
class Solution: def isRectangleCover(self, rectangles: List[List[int]]) -> bool: area = 0 minX, minY = rectangles[0][0], rectangles[0][1] maxX, maxY = rectangles[0][2], rectangles[0][3] cnt = defaultdict(int) for r in rectangles: area += (r[2] - r[0]) * (r[3] - r[1]) minX = min(minX, r[0]) minY = min(minY, r[1]) maxX = max(maxX, r[2]) maxY = max(maxY, r[3]) cnt[(r[0], r[1])] += 1 cnt[(r[0], r[3])] += 1 cnt[(r[2], r[3])] += 1 cnt[(r[2], r[1])] += 1 if ( area != (maxX - minX) * (maxY - minY) or cnt[(minX, minY)] != 1 or cnt[(minX, maxY)] != 1 or cnt[(maxX, maxY)] != 1 or cnt[(maxX, minY)] != 1 ): return False del cnt[(minX, minY)], cnt[(minX, maxY)], cnt[(maxX, maxY)], cnt[(maxX, minY)] return all(c == 2 or c == 4 for c in cnt.values())
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
C
bool isSubsequence(char* s, char* t) { int m = strlen(s); int n = strlen(t); int i = 0; for (int j = 0; i < m && j < n; ++j) { if (s[i] == t[j]) { ++i; } } return i == m; }
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
C++
class Solution { public: bool isSubsequence(string s, string t) { int m = s.size(), n = t.size(); int i = 0, j = 0; for (; i < m && j < n; ++j) { if (s[i] == t[j]) { ++i; } } return i == m; } };
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
C#
public class Solution { public bool IsSubsequence(string s, string t) { int m = s.Length, n = t.Length; int i = 0, j = 0; for (; i < m && j < n; ++j) { if (s[i] == t[j]) { ++i; } } return i == m; } }
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
Go
func isSubsequence(s string, t string) bool { i, j, m, n := 0, 0, len(s), len(t) for i < m && j < n { if s[i] == t[j] { i++ } j++ } return i == m }
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
Java
class Solution { public boolean isSubsequence(String s, String t) { int m = s.length(), n = t.length(); int i = 0, j = 0; while (i < m && j < n) { if (s.charAt(i) == t.charAt(j)) { ++i; } ++j; } return i == m; } }
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
Python
class Solution: def isSubsequence(self, s: str, t: str) -> bool: i = j = 0 while i < len(s) and j < len(t): if s[i] == t[j]: i += 1 j += 1 return i == len(s)
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
Rust
impl Solution { pub fn is_subsequence(s: String, t: String) -> bool { let (s, t) = (s.as_bytes(), t.as_bytes()); let n = t.len(); let mut i = 0; for &c in s.iter() { while i < n && t[i] != c { i += 1; } if i == n { return false; } i += 1; } true } }
392
Is Subsequence
Easy
<p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p> <p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;<u>a</u>b<u>c</u>d<u>e</u>&quot;</code> while <code>&quot;aec&quot;</code> is not).</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre><strong>Input:</strong> s = "abc", t = "ahbgdc" <strong>Output:</strong> true </pre><p><strong class="example">Example 2:</strong></p> <pre><strong>Input:</strong> s = "axc", t = "ahbgdc" <strong>Output:</strong> false </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>0 &lt;= s.length &lt;= 100</code></li> <li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li> </ul> <p>&nbsp;</p> <strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?
Two Pointers; String; Dynamic Programming
TypeScript
function isSubsequence(s: string, t: string): boolean { const m = s.length; const n = t.length; let i = 0; for (let j = 0; i < m && j < n; ++j) { if (s[i] === t[j]) { ++i; } } return i === m; }
393
UTF-8 Validation
Medium
<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p> <ol> <li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li> <li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li> </ol> <p>This is how the UTF-8 encoding would work:</p> <pre> Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx </pre> <p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p> <p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> data = [197,130,1] <strong>Output:</strong> true <strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> data = [235,140,4] <strong>Output:</strong> false <strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that&#39;s correct. But the second continuation byte does not start with 10, so it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= data[i] &lt;= 255</code></li> </ul>
Bit Manipulation; Array
C++
class Solution { public: bool validUtf8(vector<int>& data) { int cnt = 0; for (int& v : data) { if (cnt > 0) { if (v >> 6 != 0b10) { return false; } --cnt; } else if (v >> 7 == 0) { cnt = 0; } else if (v >> 5 == 0b110) { cnt = 1; } else if (v >> 4 == 0b1110) { cnt = 2; } else if (v >> 3 == 0b11110) { cnt = 3; } else { return false; } } return cnt == 0; } };
393
UTF-8 Validation
Medium
<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p> <ol> <li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li> <li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li> </ol> <p>This is how the UTF-8 encoding would work:</p> <pre> Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx </pre> <p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p> <p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> data = [197,130,1] <strong>Output:</strong> true <strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> data = [235,140,4] <strong>Output:</strong> false <strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that&#39;s correct. But the second continuation byte does not start with 10, so it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= data[i] &lt;= 255</code></li> </ul>
Bit Manipulation; Array
Go
func validUtf8(data []int) bool { cnt := 0 for _, v := range data { if cnt > 0 { if v>>6 != 0b10 { return false } cnt-- } else if v>>7 == 0 { cnt = 0 } else if v>>5 == 0b110 { cnt = 1 } else if v>>4 == 0b1110 { cnt = 2 } else if v>>3 == 0b11110 { cnt = 3 } else { return false } } return cnt == 0 }
393
UTF-8 Validation
Medium
<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p> <ol> <li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li> <li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li> </ol> <p>This is how the UTF-8 encoding would work:</p> <pre> Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx </pre> <p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p> <p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> data = [197,130,1] <strong>Output:</strong> true <strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> data = [235,140,4] <strong>Output:</strong> false <strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that&#39;s correct. But the second continuation byte does not start with 10, so it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= data[i] &lt;= 255</code></li> </ul>
Bit Manipulation; Array
Java
class Solution { public boolean validUtf8(int[] data) { int cnt = 0; for (int v : data) { if (cnt > 0) { if (v >> 6 != 0b10) { return false; } --cnt; } else if (v >> 7 == 0) { cnt = 0; } else if (v >> 5 == 0b110) { cnt = 1; } else if (v >> 4 == 0b1110) { cnt = 2; } else if (v >> 3 == 0b11110) { cnt = 3; } else { return false; } } return cnt == 0; } }
393
UTF-8 Validation
Medium
<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p> <ol> <li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li> <li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li> </ol> <p>This is how the UTF-8 encoding would work:</p> <pre> Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx </pre> <p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p> <p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> data = [197,130,1] <strong>Output:</strong> true <strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> data = [235,140,4] <strong>Output:</strong> false <strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that&#39;s correct. But the second continuation byte does not start with 10, so it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= data[i] &lt;= 255</code></li> </ul>
Bit Manipulation; Array
Python
class Solution: def validUtf8(self, data: List[int]) -> bool: cnt = 0 for v in data: if cnt > 0: if v >> 6 != 0b10: return False cnt -= 1 elif v >> 7 == 0: cnt = 0 elif v >> 5 == 0b110: cnt = 1 elif v >> 4 == 0b1110: cnt = 2 elif v >> 3 == 0b11110: cnt = 3 else: return False return cnt == 0
393
UTF-8 Validation
Medium
<p>Given an integer array <code>data</code> representing the data, return whether it is a valid <strong>UTF-8</strong> encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).</p> <p>A character in <strong>UTF8</strong> can be from <strong>1 to 4 bytes</strong> long, subjected to the following rules:</p> <ol> <li>For a <strong>1-byte</strong> character, the first bit is a <code>0</code>, followed by its Unicode code.</li> <li>For an <strong>n-bytes</strong> character, the first <code>n</code> bits are all one&#39;s, the <code>n + 1</code> bit is <code>0</code>, followed by <code>n - 1</code> bytes with the most significant <code>2</code> bits being <code>10</code>.</li> </ol> <p>This is how the UTF-8 encoding would work:</p> <pre> Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx </pre> <p><code>x</code> denotes a bit in the binary form of a byte that may be either <code>0</code> or <code>1</code>.</p> <p><strong>Note: </strong>The input is an array of integers. Only the <strong>least significant 8 bits</strong> of each integer is used to store the data. This means each integer represents only 1 byte of data.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> data = [197,130,1] <strong>Output:</strong> true <strong>Explanation:</strong> data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> data = [235,140,4] <strong>Output:</strong> false <strong>Explanation:</strong> data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one&#39;s and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that&#39;s correct. But the second continuation byte does not start with 10, so it is invalid. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= data.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>0 &lt;= data[i] &lt;= 255</code></li> </ul>
Bit Manipulation; Array
TypeScript
function validUtf8(data: number[]): boolean { let cnt = 0; for (const v of data) { if (cnt > 0) { if (v >> 6 !== 0b10) { return false; } --cnt; } else if (v >> 7 === 0) { cnt = 0; } else if (v >> 5 === 0b110) { cnt = 1; } else if (v >> 4 === 0b1110) { cnt = 2; } else if (v >> 3 === 0b11110) { cnt = 3; } else { return false; } } return cnt === 0; }
394
Decode String
Medium
<p>Given an encoded string, return its decoded string.</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. Note that <code>k</code> is guaranteed to be a positive integer.</p> <p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p> <p>The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a]2[bc]&quot; <strong>Output:</strong> &quot;aaabcbc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a2[c]]&quot; <strong>Output:</strong> &quot;accaccacc&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2[abc]3[cd]ef&quot; <strong>Output:</strong> &quot;abcabccdcdcdef&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 30</code></li> <li><code>s</code> consists of lowercase English letters, digits, and square brackets <code>&#39;[]&#39;</code>.</li> <li><code>s</code> is guaranteed to be <strong>a valid</strong> input.</li> <li>All the integers in <code>s</code> are in the range <code>[1, 300]</code>.</li> </ul>
Stack; Recursion; String
Java
class Solution { public String decodeString(String s) { Deque<Integer> s1 = new ArrayDeque<>(); Deque<String> s2 = new ArrayDeque<>(); int num = 0; String res = ""; for (char c : s.toCharArray()) { if ('0' <= c && c <= '9') { num = num * 10 + c - '0'; } else if (c == '[') { s1.push(num); s2.push(res); num = 0; res = ""; } else if (c == ']') { StringBuilder t = new StringBuilder(); for (int i = 0, n = s1.pop(); i < n; ++i) { t.append(res); } res = s2.pop() + t.toString(); } else { res += String.valueOf(c); } } return res; } }
394
Decode String
Medium
<p>Given an encoded string, return its decoded string.</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. Note that <code>k</code> is guaranteed to be a positive integer.</p> <p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p> <p>The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a]2[bc]&quot; <strong>Output:</strong> &quot;aaabcbc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a2[c]]&quot; <strong>Output:</strong> &quot;accaccacc&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2[abc]3[cd]ef&quot; <strong>Output:</strong> &quot;abcabccdcdcdef&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 30</code></li> <li><code>s</code> consists of lowercase English letters, digits, and square brackets <code>&#39;[]&#39;</code>.</li> <li><code>s</code> is guaranteed to be <strong>a valid</strong> input.</li> <li>All the integers in <code>s</code> are in the range <code>[1, 300]</code>.</li> </ul>
Stack; Recursion; String
Python
class Solution: def decodeString(self, s: str) -> str: s1, s2 = [], [] num, res = 0, '' for c in s: if c.isdigit(): num = num * 10 + int(c) elif c == '[': s1.append(num) s2.append(res) num, res = 0, '' elif c == ']': res = s2.pop() + res * s1.pop() else: res += c return res
394
Decode String
Medium
<p>Given an encoded string, return its decoded string.</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. Note that <code>k</code> is guaranteed to be a positive integer.</p> <p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p> <p>The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a]2[bc]&quot; <strong>Output:</strong> &quot;aaabcbc&quot; </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;3[a2[c]]&quot; <strong>Output:</strong> &quot;accaccacc&quot; </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> s = &quot;2[abc]3[cd]ef&quot; <strong>Output:</strong> &quot;abcabccdcdcdef&quot; </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 30</code></li> <li><code>s</code> consists of lowercase English letters, digits, and square brackets <code>&#39;[]&#39;</code>.</li> <li><code>s</code> is guaranteed to be <strong>a valid</strong> input.</li> <li>All the integers in <code>s</code> are in the range <code>[1, 300]</code>.</li> </ul>
Stack; Recursion; String
TypeScript
function decodeString(s: string): string { let ans = ''; let stack = []; let count = 0; // repeatCount for (let cur of s) { if (/[0-9]/.test(cur)) { count = count * 10 + Number(cur); } else if (/[a-z]/.test(cur)) { ans += cur; } else if ('[' == cur) { stack.push([ans, count]); // reset ans = ''; count = 0; } else { // match ']' let [pre, count] = stack.pop(); ans = pre + ans.repeat(count); } } return ans; }
395
Longest Substring with At Least K Repeating Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p> <p data-pm-slice="1 1 []">if no such substring exists, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabb&quot;, k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababbc&quot;, k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; String; Divide and Conquer; Sliding Window
C++
class Solution { public: int longestSubstring(string s, int k) { function<int(int, int)> dfs = [&](int l, int r) -> int { int cnt[26] = {0}; for (int i = l; i <= r; ++i) { cnt[s[i] - 'a']++; } char split = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0 && cnt[i] < k) { split = 'a' + i; break; } } if (split == 0) { return r - l + 1; } int i = l; int ans = 0; while (i <= r) { while (i <= r && s[i] == split) { ++i; } if (i >= r) { break; } int j = i; while (j <= r && s[j] != split) { ++j; } int t = dfs(i, j - 1); ans = max(ans, t); i = j; } return ans; }; return dfs(0, s.size() - 1); } };
395
Longest Substring with At Least K Repeating Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p> <p data-pm-slice="1 1 []">if no such substring exists, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabb&quot;, k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababbc&quot;, k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; String; Divide and Conquer; Sliding Window
Go
func longestSubstring(s string, k int) int { var dfs func(l, r int) int dfs = func(l, r int) int { cnt := [26]int{} for i := l; i <= r; i++ { cnt[s[i]-'a']++ } var split byte for i, v := range cnt { if v > 0 && v < k { split = byte(i + 'a') break } } if split == 0 { return r - l + 1 } i := l ans := 0 for i <= r { for i <= r && s[i] == split { i++ } if i > r { break } j := i for j <= r && s[j] != split { j++ } t := dfs(i, j-1) ans = max(ans, t) i = j } return ans } return dfs(0, len(s)-1) }
395
Longest Substring with At Least K Repeating Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p> <p data-pm-slice="1 1 []">if no such substring exists, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabb&quot;, k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababbc&quot;, k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; String; Divide and Conquer; Sliding Window
Java
class Solution { private String s; private int k; public int longestSubstring(String s, int k) { this.s = s; this.k = k; return dfs(0, s.length() - 1); } private int dfs(int l, int r) { int[] cnt = new int[26]; for (int i = l; i <= r; ++i) { ++cnt[s.charAt(i) - 'a']; } char split = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0 && cnt[i] < k) { split = (char) (i + 'a'); break; } } if (split == 0) { return r - l + 1; } int i = l; int ans = 0; while (i <= r) { while (i <= r && s.charAt(i) == split) { ++i; } if (i > r) { break; } int j = i; while (j <= r && s.charAt(j) != split) { ++j; } int t = dfs(i, j - 1); ans = Math.max(ans, t); i = j; } return ans; } }
395
Longest Substring with At Least K Repeating Characters
Medium
<p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>such that the frequency of each character in this substring is greater than or equal to</em> <code>k</code>.</p> <p data-pm-slice="1 1 []">if no such substring exists, return 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> s = &quot;aaabb&quot;, k = 3 <strong>Output:</strong> 3 <strong>Explanation:</strong> The longest substring is &quot;aaa&quot;, as &#39;a&#39; is repeated 3 times. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> s = &quot;ababbc&quot;, k = 2 <strong>Output:</strong> 5 <strong>Explanation:</strong> The longest substring is &quot;ababb&quot;, as &#39;a&#39; is repeated 2 times and &#39;b&#39; is repeated 3 times. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li> <li><code>s</code> consists of only lowercase English letters.</li> <li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li> </ul>
Hash Table; String; Divide and Conquer; Sliding Window
Python
class Solution: def longestSubstring(self, s: str, k: int) -> int: def dfs(l, r): cnt = Counter(s[l : r + 1]) split = next((c for c, v in cnt.items() if v < k), '') if not split: return r - l + 1 i = l ans = 0 while i <= r: while i <= r and s[i] == split: i += 1 if i >= r: break j = i while j <= r and s[j] != split: j += 1 t = dfs(i, j - 1) ans = max(ans, t) i = j return ans return dfs(0, len(s) - 1)
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
C++
class Solution { public: int maxRotateFunction(vector<int>& nums) { int f = 0, s = 0, n = nums.size(); for (int i = 0; i < n; ++i) { f += i * nums[i]; s += nums[i]; } int ans = f; for (int i = 1; i < n; ++i) { f = f + s - n * nums[n - i]; ans = max(ans, f); } return ans; } };
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
Go
func maxRotateFunction(nums []int) int { f, s, n := 0, 0, len(nums) for i, v := range nums { f += i * v s += v } ans := f for i := 1; i < n; i++ { f = f + s - n*nums[n-i] if ans < f { ans = f } } return ans }
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
Java
class Solution { public int maxRotateFunction(int[] nums) { int f = 0; int s = 0; int n = nums.length; for (int i = 0; i < n; ++i) { f += i * nums[i]; s += nums[i]; } int ans = f; for (int i = 1; i < n; ++i) { f = f + s - n * nums[n - i]; ans = Math.max(ans, f); } return ans; } }
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
Python
class Solution: def maxRotateFunction(self, nums: List[int]) -> int: f = sum(i * v for i, v in enumerate(nums)) n, s = len(nums), sum(nums) ans = f for i in range(1, n): f = f + s - n * nums[n - i] ans = max(ans, f) return ans
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
Rust
impl Solution { pub fn max_rotate_function(nums: Vec<i32>) -> i32 { let n = nums.len(); let sum: i32 = nums.iter().sum(); let mut pre: i32 = nums.iter().enumerate().map(|(i, &v)| (i as i32) * v).sum(); (0..n) .map(|i| { let res = pre; pre = pre - (sum - nums[i]) + nums[i] * ((n - 1) as i32); res }) .max() .unwrap_or(0) } }
396
Rotate Function
Medium
<p>You are given an integer array <code>nums</code> of length <code>n</code>.</p> <p>Assume <code>arr<sub>k</sub></code> to be an array obtained by rotating <code>nums</code> by <code>k</code> positions clock-wise. We define the <strong>rotation function</strong> <code>F</code> on <code>nums</code> as follow:</p> <ul> <li><code>F(k) = 0 * arr<sub>k</sub>[0] + 1 * arr<sub>k</sub>[1] + ... + (n - 1) * arr<sub>k</sub>[n - 1].</code></li> </ul> <p>Return <em>the maximum value of</em> <code>F(0), F(1), ..., F(n-1)</code>.</p> <p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> nums = [4,3,2,6] <strong>Output:</strong> 26 <strong>Explanation:</strong> F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16 F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23 F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26 So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26. </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> nums = [100] <strong>Output:</strong> 0 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == nums.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Array; Math; Dynamic Programming
TypeScript
function maxRotateFunction(nums: number[]): number { const n = nums.length; const sum = nums.reduce((r, v) => r + v); let res = nums.reduce((r, v, i) => r + v * i, 0); let pre = res; for (let i = 1; i < n; i++) { pre = pre - (sum - nums[i - 1]) + nums[i - 1] * (n - 1); res = Math.max(res, pre); } return res; }
397
Integer Replacement
Medium
<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p> <ol> <li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li> <li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li> </ol> <p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 4 <strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1 or 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Bit Manipulation; Memoization; Dynamic Programming
C++
class Solution { public: int integerReplacement(int N) { int ans = 0; long n = N; while (n != 1) { if ((n & 1) == 0) n >>= 1; else if (n != 3 && (n & 3) == 3) ++n; else --n; ++ans; } return ans; } };
397
Integer Replacement
Medium
<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p> <ol> <li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li> <li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li> </ol> <p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 4 <strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1 or 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Bit Manipulation; Memoization; Dynamic Programming
Go
func integerReplacement(n int) int { ans := 0 for n != 1 { if (n & 1) == 0 { n >>= 1 } else if n != 3 && (n&3) == 3 { n++ } else { n-- } ans++ } return ans }
397
Integer Replacement
Medium
<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p> <ol> <li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li> <li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li> </ol> <p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 4 <strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1 or 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Bit Manipulation; Memoization; Dynamic Programming
Java
class Solution { public int integerReplacement(int n) { int ans = 0; while (n != 1) { if ((n & 1) == 0) { n >>>= 1; } else if (n != 3 && (n & 3) == 3) { ++n; } else { --n; } ++ans; } return ans; } }
397
Integer Replacement
Medium
<p>Given a positive integer <code>n</code>,&nbsp;you can apply one of the following&nbsp;operations:</p> <ol> <li>If <code>n</code> is even, replace <code>n</code> with <code>n / 2</code>.</li> <li>If <code>n</code> is odd, replace <code>n</code> with either <code>n + 1</code> or <code>n - 1</code>.</li> </ol> <p>Return <em>the minimum number of operations needed for</em> <code>n</code> <em>to become</em> <code>1</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> n = 8 <strong>Output:</strong> 3 <strong>Explanation:</strong> 8 -&gt; 4 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> n = 7 <strong>Output:</strong> 4 <strong>Explanation: </strong>7 -&gt; 8 -&gt; 4 -&gt; 2 -&gt; 1 or 7 -&gt; 6 -&gt; 3 -&gt; 2 -&gt; 1 </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> n = 4 <strong>Output:</strong> 2 </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li> </ul>
Greedy; Bit Manipulation; Memoization; Dynamic Programming
Python
class Solution: def integerReplacement(self, n: int) -> int: ans = 0 while n != 1: if (n & 1) == 0: n >>= 1 elif n != 3 and (n & 3) == 3: n += 1 else: n -= 1 ans += 1 return ans
398
Random Pick Index
Medium
<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li> <li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;] [[[1, 2, 3, 3, 3]], [3], [1], [3]] <strong>Output</strong> [null, 4, 0, 2] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>target</code> is an integer from <code>nums</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
C++
class Solution { public: vector<int> nums; Solution(vector<int>& nums) { this->nums = nums; } int pick(int target) { int n = 0, ans = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] == target) { ++n; int x = 1 + rand() % n; if (n == x) ans = i; } } return ans; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(nums); * int param_1 = obj->pick(target); */
398
Random Pick Index
Medium
<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li> <li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;] [[[1, 2, 3, 3, 3]], [3], [1], [3]] <strong>Output</strong> [null, 4, 0, 2] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>target</code> is an integer from <code>nums</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
Go
type Solution struct { nums []int } func Constructor(nums []int) Solution { return Solution{nums} } func (this *Solution) Pick(target int) int { n, ans := 0, 0 for i, v := range this.nums { if v == target { n++ x := 1 + rand.Intn(n) if n == x { ans = i } } } return ans } /** * Your Solution object will be instantiated and called as such: * obj := Constructor(nums); * param_1 := obj.Pick(target); */
398
Random Pick Index
Medium
<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li> <li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;] [[[1, 2, 3, 3, 3]], [3], [1], [3]] <strong>Output</strong> [null, 4, 0, 2] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>target</code> is an integer from <code>nums</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
Java
class Solution { private int[] nums; private Random random = new Random(); public Solution(int[] nums) { this.nums = nums; } public int pick(int target) { int n = 0, ans = 0; for (int i = 0; i < nums.length; ++i) { if (nums[i] == target) { ++n; int x = 1 + random.nextInt(n); if (x == n) { ans = i; } } } return ans; } } /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(nums); * int param_1 = obj.pick(target); */
398
Random Pick Index
Medium
<p>Given an integer array <code>nums</code> with possible <strong>duplicates</strong>, randomly output the index of a given <code>target</code> number. You can assume that the given target number must exist in the array.</p> <p>Implement the <code>Solution</code> class:</p> <ul> <li><code>Solution(int[] nums)</code> Initializes the object with the array <code>nums</code>.</li> <li><code>int pick(int target)</code> Picks a random index <code>i</code> from <code>nums</code> where <code>nums[i] == target</code>. If there are multiple valid i&#39;s, then each index should have an equal probability of returning.</li> </ul> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input</strong> [&quot;Solution&quot;, &quot;pick&quot;, &quot;pick&quot;, &quot;pick&quot;] [[[1, 2, 3, 3, 3]], [3], [1], [3]] <strong>Output</strong> [null, 4, 0, 2] <strong>Explanation</strong> Solution solution = new Solution([1, 2, 3, 3, 3]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li> <li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li> <li><code>target</code> is an integer from <code>nums</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made to <code>pick</code>.</li> </ul>
Reservoir Sampling; Hash Table; Math; Randomized
Python
class Solution: def __init__(self, nums: List[int]): self.nums = nums def pick(self, target: int) -> int: n = ans = 0 for i, v in enumerate(self.nums): if v == target: n += 1 x = random.randint(1, n) if x == n: ans = i return ans # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.pick(target)
399
Evaluate Division
Medium
<p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p> <p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p> <p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p> <p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p> <p><strong>Note:&nbsp;</strong>The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;]], values = [2.0,3.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;e&quot;],[&quot;a&quot;,&quot;a&quot;],[&quot;x&quot;,&quot;x&quot;]] <strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000] <strong>Explanation:</strong> Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em> queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ? </em> return: [6.0, 0.5, -1.0, 1.0, -1.0 ] note: x is undefined =&gt; -1.0</pre> <p><strong class="example">Example 2:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;c&quot;],[&quot;bc&quot;,&quot;cd&quot;]], values = [1.5,2.5,5.0], queries = [[&quot;a&quot;,&quot;c&quot;],[&quot;c&quot;,&quot;b&quot;],[&quot;bc&quot;,&quot;cd&quot;],[&quot;cd&quot;,&quot;bc&quot;]] <strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000] </pre> <p><strong class="example">Example 3:</strong></p> <pre> <strong>Input:</strong> equations = [[&quot;a&quot;,&quot;b&quot;]], values = [0.5], queries = [[&quot;a&quot;,&quot;b&quot;],[&quot;b&quot;,&quot;a&quot;],[&quot;a&quot;,&quot;c&quot;],[&quot;x&quot;,&quot;y&quot;]] <strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000] </pre> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= equations.length &lt;= 20</code></li> <li><code>equations[i].length == 2</code></li> <li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li> <li><code>values.length == equations.length</code></li> <li><code>0.0 &lt; values[i] &lt;= 20.0</code></li> <li><code>1 &lt;= queries.length &lt;= 20</code></li> <li><code>queries[i].length == 2</code></li> <li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li> <li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; String; Shortest Path
C++
class Solution { public: unordered_map<string, string> p; unordered_map<string, double> w; vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { int n = equations.size(); for (auto e : equations) { p[e[0]] = e[0]; p[e[1]] = e[1]; w[e[0]] = 1.0; w[e[1]] = 1.0; } for (int i = 0; i < n; ++i) { vector<string> e = equations[i]; string a = e[0], b = e[1]; string pa = find(a), pb = find(b); if (pa == pb) continue; p[pa] = pb; w[pa] = w[b] * values[i] / w[a]; } int m = queries.size(); vector<double> ans(m); for (int i = 0; i < m; ++i) { string c = queries[i][0], d = queries[i][1]; ans[i] = p.find(c) == p.end() || p.find(d) == p.end() || find(c) != find(d) ? -1.0 : w[c] / w[d]; } return ans; } string find(string x) { if (p[x] != x) { string origin = p[x]; p[x] = find(p[x]); w[x] *= w[origin]; } return p[x]; } };